From 38fd064bc3a66ec7f8c4e699abb6dba5b8c2116f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:25:48 -0800 Subject: [PATCH 01/50] build(deps): pin spiral-sdk 0.16.78, which reads and writes table metadata (ITL-1837) 0.16.79 is newer but deprecates keyed tables, which every SpiralDB path of Orcapod uses: each open would issue a DeprecationWarning. 0.16.74 to 0.16.78 changes only get_metadata/set_metadata on KeyedTable in the Python layer. Co-Authored-By: Claude Opus 5.5 --- RELEASING.md | 4 ++-- pyproject.toml | 2 +- uv.lock | 12 ++++++------ 3 files changed, 9 insertions(+), 9 deletions(-) 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/pyproject.toml b/pyproject.toml index d5db39436..fbb692496 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ # Exact: a pre-alpha that releases daily, and Orcapod reads two attributes that are # not its public API (ITL-1186). How to move it: RELEASING.md. - "spiral-sdk==0.16.74", + "spiral-sdk==0.16.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/uv.lock b/uv.lock index 57da3a714..b1579fcc0 100644 --- a/uv.lock +++ b/uv.lock @@ -1960,8 +1960,8 @@ requires-dist = [ { name = "redis", marker = "extra == 'all'", specifier = ">=6.2.0" }, { name = "redis", marker = "extra == 'redis'", specifier = ">=6.2.0" }, { name = "s3fs", specifier = ">=2025.12.0" }, - { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.74" }, - { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.74" }, + { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.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" }, @@ -3292,16 +3292,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 eb197924d9916a77d1be37ab6454030a760f85a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:31:24 -0800 Subject: [PATCH 02/50] feat(spiraldb): add generation-table writer leases (ITL-1838) --- changelog.d/ITL-1838.md | 3 + docs/dev/plans/itl-1838-spiraldb-lease.md | 38 +++ src/orcapod/databases/spiraldb_connector.py | 11 +- src/orcapod/databases/spiraldb_lease.py | 265 +++++++++++++++++ src/orcapod/databases/store_table_names.py | 11 + tests/test_databases/test_spiral_lease.py | 301 ++++++++++++++++++++ 6 files changed, 626 insertions(+), 3 deletions(-) create mode 100644 changelog.d/ITL-1838.md create mode 100644 docs/dev/plans/itl-1838-spiraldb-lease.md create mode 100644 src/orcapod/databases/spiraldb_lease.py create mode 100644 tests/test_databases/test_spiral_lease.py diff --git a/changelog.d/ITL-1838.md b/changelog.d/ITL-1838.md new file mode 100644 index 000000000..b92b306d1 --- /dev/null +++ b/changelog.d/ITL-1838.md @@ -0,0 +1,3 @@ +### Added + +- Added internal SpiralDB writer leases based on generation tables, with manual recovery by table ID. diff --git a/docs/dev/plans/itl-1838-spiraldb-lease.md b/docs/dev/plans/itl-1838-spiraldb-lease.md new file mode 100644 index 000000000..801989f8b --- /dev/null +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -0,0 +1,38 @@ +# SpiralDB writer lease + +Use exclusive keyed-table creation to claim a dataset's next numbered generation. +Find the newest generation by probing names at powers of two, then bisecting. +Keep generation tables in place so contenders that observed the same predecessor +try the same name. A contender that loses creation refuses once, even if the +winner has already released. + +Use the pinned SDK's keyed-table operations. Put a random claim token in the +key column name so exclusive creation establishes ownership atomically and a +lost create reply can be checked. Use separate keyed rows for owner details and +for the release marker. The release marker wins even when owner details arrive +late. An empty generation is held, including after a crash during acquisition. + +Expose acquire, check, release, and manual clear by immutable table ID in an +internal module. Reopen the exact resource for check and release, and report +uncertain operations without granting ownership. Require an operator to confirm +that the previous writer has stopped before clearing its generation. Job-run +integration is a later stage. + +Use the existing fake SDK for deterministic races, partial failures, stale +handles, and independent datasets. Run the targeted tests, Ruff and +basedpyright, then open a PR against main and address CodeRabbit findings. + +## Integration and recovery + +Use `spiraldb_lease.acquire(client, project_id, dataset, owner=...)` before +issuing any store writes. Pass the returned lease to `check(client, lease)` +before writes and to `release(client, lease)` after all writes have finished. +The generation namespace is separate from record table names and the connector +omits it from listings. + +A refusal identifies the blocking table ID. To clear a stale lease, first stop +the previous writer and ensure all outstanding writes have settled. Then call +`spiraldb_lease.clear(client, table_id, confirm_writer_stopped=True)` on the same +service. Clearing a live writer can admit another writer while an earlier +write is still in flight. The lease has no time limit. Keep all generation +tables, including released ones, so generation discovery remains contiguous. diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 61e695bd9..9a59f17ae 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,6 +49,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -942,8 +943,8 @@ def _require_user_table(self, table_name: str) -> None: def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. - The dataset's schema table is not one of them. A table it records that the - dataset no longer holds is warned about. + The listing excludes internal schema and lease tables. A table recorded in + the schema table that the dataset no longer holds is warned about. Raises: TableSchemaError: If the dataset's schema table is not complete. @@ -965,7 +966,11 @@ def get_table_names(self) -> list[str]: f"the {SCHEMA_TABLE} of SpiralDB dataset {self._project_id}/" f"{self._dataset} records tables that the dataset no longer holds: {gone}", ) - return sorted(name for name in listed.values() if name != SCHEMA_TABLE) + return sorted( + name + for name in listed.values() + if name != SCHEMA_TABLE and not is_spiral_lease_table_name(name) + ) def lookup_table(self, table_name: str) -> SpiralDBTable: """Look the table up once, for several items of its metadata (ITL-1350). diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py new file mode 100644 index 000000000..1a9cf345a --- /dev/null +++ b/src/orcapod/databases/spiraldb_lease.py @@ -0,0 +1,265 @@ +"""Internal one-writer leases for SpiralDB stores.""" + +from __future__ import annotations + +import os +import re +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import TYPE_CHECKING, cast +from uuid import uuid4 + +import pyarrow as pa + +from orcapod.databases import spiraldb_connector as sdk +from orcapod.databases.store_table_names import spiral_lease_table_name +from orcapod.errors import OrcapodDatabaseError + +if TYPE_CHECKING: + from spiral import Client + from spiral.keyed_tables import KeyedTable + +_KEY_PREFIX = "orcapod_lease_v1_" +_KEY_PATTERN = re.compile(rf"{_KEY_PREFIX}[0-9a-f]{{32}}") +_CLAIM = "claim" +_RELEASED = "released" +_CONFLICT = "remote service returned an unknown error (status 409)" + + +class LeaseError(OrcapodDatabaseError): + """A writer lease operation could not be completed or verified.""" + + +class LeaseBusyError(LeaseError): + """Another claim prevents this acquisition.""" + + table_id: str + + def __init__(self, dataset: str, table_id: str, owner: str | None) -> None: + """Identify the conflicting generation and how an operator can release it.""" + self.table_id = table_id + description = f"owner {owner!r}" if owner is not None else "owner unknown" + how_to_clear = ( + f"spiraldb_lease.clear(client, {table_id!r}, confirm_writer_stopped=True)" + ) + conflict = f"SpiralDB dataset {dataset!r} has a conflicting writer lease" + recovery = f"If the lease is stale, confirm the writer has stopped and call {how_to_clear}." + super().__init__( + f"{conflict} ({description}, table ID {table_id!r}). {recovery}" + ) + + +@dataclass(frozen=True) +class Lease: + """A claim on one immutable generation table, held in the acquiring process.""" + + table_id: str + key: str + pid: int + + +@dataclass(frozen=True) +class _State: + """Owner information and the independent release marker.""" + + owner: str | None + released: bool + + +def _open( + client: Client, project_id: str, dataset: str, generation: int +) -> KeyedTable | None: + """Open the latest snapshot of a generation by name.""" + return cast( + "KeyedTable | None", + sdk._open_keyed_table( # pyright: ignore[reportPrivateUsage] + client, project_id, dataset, spiral_lease_table_name(generation) + ), + ) + + +def _newest( + client: Client, project_id: str, dataset: str +) -> tuple[int, KeyedTable | None]: + """Bracket the end of the contiguous generation sequence, then bisect.""" + low, high = 0, 1 + newest = None + while (table := _open(client, project_id, dataset, high)) is not None: + low, newest = high, table + high *= 2 + while high - low > 1: + mid = (low + high) // 2 + table = _open(client, project_id, dataset, mid) + if table is None: + high = mid + else: + low, newest = mid, table + return low, newest + + +def _key(table: KeyedTable) -> str: + """Validate the reserved primary key before reading or mutating a lease.""" + keys = table.key_columns + if len(keys) != 1 or _KEY_PATTERN.fullmatch(keys[0]) is None: + raise LeaseError( + f"SpiralDB table ID {table.resource_id!r} is not a lease table" + ) + return keys[0] + + +def _state(table: KeyedTable, key: str) -> _State: + """Read the two possible states from a snapshot, including a bare claim.""" + owner = None + released = False + rows = cast("list[dict[str, object]]", table.scan(limit=3).to_table().to_pylist()) + for row in rows: + if row[key] == _CLAIM and isinstance(recorded_owner := row.get("owner"), str): + owner = recorded_owner + elif row[key] == _RELEASED: + released = True + else: + raise LeaseError( + f"Invalid lease state in SpiralDB table ID {table.resource_id!r}" + ) + return _State(owner, released) + + +def _row( + key: str, state: str, owner: str | None = None, started_at: str | None = None +) -> pa.Table: + """Make one keyed write for a claim or release.""" + schema = pa.schema( + [ + pa.field(key, pa.large_string(), nullable=False), + pa.field("owner", pa.large_string()), + pa.field("started_at", pa.large_string()), + ] + ) + return pa.Table.from_arrays( + [pa.array([value], pa.large_string()) for value in (state, owner, started_at)], + schema=schema, + ) + + +def _claim_generation( + client: Client, project_id: str, dataset: str, generation: int, key: str +) -> KeyedTable: + """Make one exclusive create attempt and reconcile a lost reply by token.""" + name = spiral_lease_table_name(generation) + key_schema = pa.schema([pa.field(key, pa.large_string(), nullable=False)]) + try: + return client.project(project_id).create_keyed_table( + dataset, name, key_schema, exist_ok=False + ) + except Exception as exc: + conflict = str(exc).strip() == _CONFLICT + location = f"dataset {dataset!r} at generation {generation}" + recovery = "Inspect that generation before clearing it by ID." + uncertain = LeaseError( + f"Could not confirm writer lease creation in {location}. {recovery}" + ) + try: + found = _open(client, project_id, dataset, generation) + except Exception as lookup_error: + uncertain.add_note(f"Generation lookup also failed: {lookup_error}") + raise uncertain from exc + if found is None: + raise uncertain from exc + found_key = _key(found) + if not conflict and found_key == key: + return found + raise LeaseBusyError( + dataset, found.resource_id, _state(found, found_key).owner + ) from exc + + +def acquire(client: Client, project_id: str, dataset: str, *, owner: str) -> Lease: + """Claim a dataset for one writer or raise before any store data can be written.""" + generation, latest = _newest(client, project_id, dataset) + if latest is not None: + state = _state(latest, _key(latest)) + if not state.released: + raise LeaseBusyError(dataset, latest.resource_id, state.owner) + + key = f"{_KEY_PREFIX}{uuid4().hex}" + row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) + claimed = _claim_generation(client, project_id, dataset, generation + 1, key) + if _key(claimed) != key: + raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") + lease = Lease(claimed.resource_id, key, os.getpid()) + # Owner details and release are different keys. An operator's release survives + # even if this write publishes after it. + try: + _ = claimed.append(row) + except Exception as exc: + try: + check(client, lease) + except Exception as verification_error: + verification_error.add_note( + f"Writing lease owner details also failed: {exc}" + ) + raise + else: + check(client, lease) + return lease + + +def _held_table(client: Client, lease: Lease) -> KeyedTable: + """Reopen the lease by ID and verify that it belongs to this process and token.""" + sdk.require_same_process(lease.pid) + table = client.keyed_table_by_id(lease.table_id) + if table.resource_id != lease.table_id or _key(table) != lease.key: + raise LeaseError(f"SpiralDB lease table ID {lease.table_id!r} changed identity") + return table + + +def check(client: Client, lease: Lease) -> None: + """Raise if a claim cannot be verified immediately before use.""" + table = _held_table(client, lease) + state = _state(table, lease.key) + if state.released: + raise LeaseError(f"SpiralDB lease table ID {lease.table_id!r} was released") + if state.owner is None: + raise LeaseError( + f"SpiralDB lease table ID {lease.table_id!r} has no owner record" + ) + + +def _mark_released(client: Client, table: KeyedTable, key: str) -> None: + """Write the release marker once, settling ambiguous replies by the exact ID.""" + if _state(table, key).released: + return + table_id = table.resource_id + try: + _ = table.append(_row(key, _RELEASED)) + except Exception as exc: + try: + latest = client.keyed_table_by_id(table_id) + if ( + latest.resource_id == table_id + and _key(latest) == key + and _state(latest, key).released + ): + return + except Exception as lookup_error: + exc.add_note(f"Lease release verification also failed: {lookup_error}") + raise LeaseError( + f"Could not confirm release of SpiralDB lease table ID {table_id!r}" + ) from exc + + +def release(client: Client, lease: Lease) -> None: + """Release exactly this claim after the writer and all pending writes have stopped.""" + _mark_released(client, _held_table(client, lease), lease.key) + + +def clear(client: Client, table_id: str, *, confirm_writer_stopped: bool) -> None: + """Manually release a stale generation by immutable table ID.""" + if confirm_writer_stopped is not True: + raise ValueError( + "Confirm that the writer has stopped before clearing its lease" + ) + table = client.keyed_table_by_id(table_id) + if table.resource_id != table_id: + raise LeaseError(f"Could not verify SpiralDB lease table ID {table_id!r}") + _mark_released(client, table, _key(table)) diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 96f05453e..fea894bf3 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -10,6 +10,17 @@ """The digest algorithm shared with SpiralDB. The name's grammar carries its version.""" STORE_TABLE_NAME_PREFIX = "o1_" +_SPIRAL_LEASE_TABLE_PREFIX = "orcapod_lease_v1_g" + + +def spiral_lease_table_name(generation: int) -> str: + """Return the reserved SpiralDB name for a writer lease generation.""" + return f"{_SPIRAL_LEASE_TABLE_PREFIX}{generation}" + + +def is_spiral_lease_table_name(name: str) -> bool: + """Return whether the name belongs to the reserved lease namespace.""" + return name.startswith(_SPIRAL_LEASE_TABLE_PREFIX) def store_table_path_json(path: Sequence[str]) -> bytes: diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py new file mode 100644 index 000000000..373aa4266 --- /dev/null +++ b/tests/test_databases/test_spiral_lease.py @@ -0,0 +1,301 @@ +"""Exercise generation leases against the local SDK fake.""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path +from typing import TYPE_CHECKING, cast + +import pyarrow as pa +import pytest + +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_lease import ( + LeaseBusyError, + LeaseError, + acquire, + check, + clear, + release, +) +from orcapod.databases.store_table_names import ( + is_spiral_lease_table_name, + spiral_lease_table_name, + store_table_name, +) +from tests.test_databases import fake_spiral_sdk as fake + +if TYPE_CHECKING: + from spiral import Client + +_PROJECT = "project" +_DATASET = "dataset" + + +def _fake_client() -> Client: + """Treat the fake's SDK subset as a client for the lease module.""" + client: object = fake.FakeClient() + return cast("Client", client) + + +@pytest.fixture +def client(tmp_path: Path) -> Iterator[Client]: + """Install the fake for one test and return its SDK-shaped client.""" + with fake.install(tmp_path): + yield _fake_client() + + +def test_take_check_release_and_retake(client: Client) -> None: + first = acquire(client, _PROJECT, _DATASET, owner="first run") + check(client, first) + release(client, first) + release(client, first) + second = acquire(client, _PROJECT, _DATASET, owner="second run") + assert second.table_id != first.table_id + release(client, first) + check(client, second) + with pytest.raises(LeaseError, match="released"): + check(client, first) + + +def test_crashed_holder_refuses_until_manually_cleared(client: Client) -> None: + first = acquire(client, _PROJECT, _DATASET, owner="same owner") + other = _fake_client() + for _ in range(2): + with pytest.raises(LeaseBusyError) as refused: + _ = acquire(other, _PROJECT, _DATASET, owner="same owner") + message = str(refused.value) + assert _DATASET in message + assert first.table_id in message + assert "same owner" in message + assert "confirm_writer_stopped=True" in message + with pytest.raises(ValueError, match="stopped"): + clear(other, first.table_id, confirm_writer_stopped=False) + check(client, first) + clear(other, first.table_id, confirm_writer_stopped=True) + second = acquire(other, _PROJECT, _DATASET, owner="next run") + clear(other, first.table_id, confirm_writer_stopped=True) + check(other, second) + with pytest.raises(LeaseError, match="released"): + check(client, first) + + +@pytest.mark.parametrize("winner_releases", [False, True]) +def test_two_writers_that_observed_the_same_generation( + client: Client, monkeypatch: pytest.MonkeyPatch, winner_releases: bool +) -> None: + create = fake.FakeProject.create_keyed_table + attempted: list[str] = [] + + def racing_create( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + attempted.append(name) + if len(attempted) == 1: + other = _fake_client() + winner = acquire(other, _PROJECT, _DATASET, owner="winner") + check(other, winner) + if winner_releases: + release(other, winner) + return create(project, dataset, name, key_schema, exist_ok=exist_ok) + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", racing_create) + with pytest.raises(LeaseBusyError, match="winner"): + _ = acquire(client, _PROJECT, _DATASET, owner="loser") + assert attempted == [spiral_lease_table_name(1)] * 2 + + +def test_crash_between_create_and_owner_record(client: Client) -> None: + with pytest.MonkeyPatch.context() as patch: + + def crash(_table: fake.FakeKeyedTable, _rows: pa.Table) -> fake.FakeKeyedTable: + raise KeyboardInterrupt + + patch.setattr(fake.FakeKeyedTable, "append", crash) + with pytest.raises(KeyboardInterrupt): + _ = acquire(client, _PROJECT, _DATASET, owner="first") + with pytest.raises(LeaseBusyError, match="owner unknown") as refused: + _ = acquire(client, _PROJECT, _DATASET, owner="second") + clear(client, refused.value.table_id, confirm_writer_stopped=True) + check(client, acquire(client, _PROJECT, _DATASET, owner="third")) + + +def test_stale_clear_cannot_be_overwritten_by_late_owner_record( + client: Client, monkeypatch: pytest.MonkeyPatch +) -> None: + append = fake.FakeKeyedTable.append + ids: list[str] = [] + + def clear_before_append( + table: fake.FakeKeyedTable, rows: pa.Table + ) -> fake.FakeKeyedTable: + if not ids: + ids.append(table.resource_id) + clear(client, table.resource_id, confirm_writer_stopped=True) + next_lease = acquire(client, _PROJECT, _DATASET, owner="next") + ids.append(next_lease.table_id) + return append(table, rows) + + monkeypatch.setattr(fake.FakeKeyedTable, "append", clear_before_append) + with pytest.raises(LeaseError, match="released"): + _ = acquire(client, _PROJECT, _DATASET, owner="old") + with pytest.raises(LeaseBusyError) as refused: + _ = acquire(client, _PROJECT, _DATASET, owner="third") + assert refused.value.table_id == ids[-1] + + +def test_create_reply_lost_after_exclusive_creation( + client: Client, monkeypatch: pytest.MonkeyPatch +) -> None: + create = fake.FakeProject.create_keyed_table + + def lose_reply( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) + raise TimeoutError("lost reply") + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", lose_reply) + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + check(client, holder) + + +@pytest.mark.parametrize("landed", [True, False]) +def test_release_reply_lost( + client: Client, monkeypatch: pytest.MonkeyPatch, landed: bool +) -> None: + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + append = fake.FakeKeyedTable.append + + def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTable: + if landed: + _ = append(table, rows) + raise TimeoutError("lost reply") + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", lose_reply) + if landed: + release(client, holder) + else: + with pytest.raises(LeaseError, match=holder.table_id): + release(client, holder) + if landed: + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + else: + with pytest.raises(LeaseBusyError): + _ = acquire(client, _PROJECT, _DATASET, owner="next") + + +def test_manual_clear_refuses_store_data_and_listing_keeps_store_data( + client: Client, +) -> None: + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + lease_name = spiral_lease_table_name(1) + data_name = store_table_name([lease_name], hint_length=96, digest_length=64) + assert is_spiral_lease_table_name(lease_name) + assert not is_spiral_lease_table_name(data_name) + data = client.project(_PROJECT).create_keyed_table( + _DATASET, data_name, pa.schema([pa.field("id", pa.int64())]) + ) + with pytest.raises(LeaseError, match=data.resource_id): + clear(client, data.resource_id, confirm_writer_stopped=True) + with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + assert connector.get_table_names() == [data_name] + check(client, holder) + + +def test_other_datasets_have_independent_leases(client: Client) -> None: + first = acquire(client, _PROJECT, _DATASET, owner="first") + second = acquire(client, _PROJECT, "other", owner="second") + assert first.table_id != second.table_id + check(client, first) + check(client, second) + + +@pytest.mark.parametrize("late_create_wins", [False, True]) +def test_create_that_arrives_after_timeout_never_grants_a_second_lease( + client: Client, monkeypatch: pytest.MonkeyPatch, late_create_wins: bool +) -> None: + create = fake.FakeProject.create_keyed_table + pending: list[tuple[fake.FakeProject, str, str, pa.Schema]] = [] + + def delay_create( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + assert not exist_ok + pending.append((project, dataset, name, key_schema)) + raise TimeoutError("request still in flight") + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeProject, "create_keyed_table", delay_create) + with pytest.raises(LeaseError, match="Could not confirm"): + _ = acquire(client, _PROJECT, _DATASET, owner="delayed") + + other = _fake_client() + if late_create_wins: + table = create(*pending[0]) + with pytest.raises(LeaseBusyError, match=table.resource_id): + _ = acquire(other, _PROJECT, _DATASET, owner="second") + else: + holder = acquire(other, _PROJECT, _DATASET, owner="second") + with pytest.raises(fake.SpiralError, match="409"): + _ = create(*pending[0]) + check(other, holder) + + +def test_generation_search_uses_logarithmic_probes( + client: Client, monkeypatch: pytest.MonkeyPatch +) -> None: + for _ in range(19): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + open_by_name = fake.FakeClient.keyed_table + probes: list[str] = [] + + def count_open( + instance: fake.FakeClient, + project: str, + dataset: str, + name: str, + *, + asof: int | None = None, + ) -> fake.FakeKeyedTable: + probes.append(name) + return open_by_name(instance, project, dataset, name, asof=asof) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", count_open) + current = acquire(client, _PROJECT, _DATASET, owner="current") + assert len(probes) <= 11 + assert ( + client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(20)).resource_id + == current.table_id + ) + + +def test_lookup_error_never_licenses_creation( + client: Client, monkeypatch: pytest.MonkeyPatch +) -> None: + def unavailable(*_args: object) -> fake.FakeKeyedTable: + raise fake.SpiralError("remote service returned an unknown error (status 404)") + + def never_create(*_args: object, **_kwargs: object) -> fake.FakeKeyedTable: + pytest.fail("acquire attempted creation without a confirmed missing generation") + + monkeypatch.setattr(fake.FakeClient, "keyed_table", unavailable) + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", never_create) + with pytest.raises(fake.SpiralError, match="404"): + _ = acquire(client, _PROJECT, _DATASET, owner="writer") From 60bf0af4f40df50b8e9a8997df026d27923c2c75 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:32:23 -0800 Subject: [PATCH 03/50] test(spiraldb): type the fake client boundary --- tests/test_databases/test_spiral_lease.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 373aa4266..60d615eae 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -34,8 +34,7 @@ def _fake_client() -> Client: """Treat the fake's SDK subset as a client for the lease module.""" - client: object = fake.FakeClient() - return cast("Client", client) + return cast("Client", cast("object", fake.FakeClient())) @pytest.fixture From 10ac3d07d9786130c092e8c343796c333738a0e9 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:35:02 -0800 Subject: [PATCH 04/50] feat(spiraldb): store table identity record and codec, provisional and internal (ITL-1837) Stage A of the SpiralDB store (ITL-1446), carried from PRs 589, 590 and 595 onto current main: - the fake's table-metadata rules (get_metadata/set_metadata) and their conformance tests; - spiral_store_identity: a store table's name by main's shared rule (store_table_names, hint 96, whole digest; no second label, no golden group) and its identity record in table metadata, with SpiralStoreTableCollisionError; - spiral_store: the codec, with the manifest in table metadata in 8,000-byte chunks; main's four nested-extension type-matrix rows are expected refusals; the header's checksum field is payload_digest. Nothing is public: SpiralDBConnector still refuses every write. The format is a draft, outside the 0.4.0 freeze. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1837.md | 14 + ...026-12-01-itl-1837-spiral-store-stage-a.md | 99 + docs/reference/hashing.md | 1 + src/orcapod/databases/spiral_store.py | 1170 ++++++++++++ .../databases/spiral_store_identity.py | 222 +++ tests/test_databases/fake_spiral_sdk.py | 245 ++- tests/test_databases/test_fake_spiral_sdk.py | 42 + tests/test_databases/test_spiral_store.py | 1596 +++++++++++++++++ .../test_spiral_store_identity.py | 281 +++ .../test_spiraldb_connector_integration.py | 452 +++++ 10 files changed, 4114 insertions(+), 8 deletions(-) create mode 100644 changelog.d/ITL-1837.md create mode 100644 docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md create mode 100644 src/orcapod/databases/spiral_store.py create mode 100644 src/orcapod/databases/spiral_store_identity.py create mode 100644 tests/test_databases/test_fake_spiral_sdk.py create mode 100644 tests/test_databases/test_spiral_store.py create mode 100644 tests/test_databases/test_spiral_store_identity.py diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md new file mode 100644 index 000000000..c883c9105 --- /dev/null +++ b/changelog.d/ITL-1837.md @@ -0,0 +1,14 @@ +### Changed + +- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), the release that reads + and writes a SpiralDB table's own metadata. 0.16.79 is not used: it deprecates the keyed + tables Orcapod reads, with a warning on every open. Orcapod still only reads SpiralDB. + (ITL-1837) + +### Known limitations + +- Orcapod cannot yet use SpiralDB as a job's database: `SpiralDBConnector` still refuses + every write. The groundwork for it (the encoding of a stored table's columns and the + identity record kept in a table's metadata) is internal and its format is provisional: + outside the 0.4.0 freeze, it may change before the store is offered, and tables written + in it may then need to be written again. (ITL-1837) diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md new file mode 100644 index 000000000..6bffdec0f --- /dev/null +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -0,0 +1,99 @@ +# ITL-1837: SpiralDB store, stage A (dependency, identity record, codec) + +Stage A of using SpiralDB as a job's pipeline and result database (ITL-1446). It carries +the still-valid parts of PRs 589 (ITL-1495) and 590 (ITL-1497) onto current `main`, and the +manifest-in-metadata part of PR 595 (ITL-1498). Those branches were sources to copy from; +none is merged. Nothing here is public: no way to open a store exists, and +`SpiralDBConnector` still refuses every write (`SpiralDBWriteNotSupportedError`). + +## The store format is provisional + +Everything this stage defines about what a store table holds is **provisional**: outside +the 0.4.0 freeze, free to change until the store is switched on (a later stage, with a +developer decision). That covers the identity record's keys and values, the manifest's +header and chunking, the codec's physical encoding and its name escape. Both markers say +so: the identity record's format is `orcapod.spiral_store.draft` +(`spiral_store_identity.STORE_FORMAT`), the manifest's `orcapod.spiral_store.draft` +version 0 (`spiral_store.MANIFEST_FORMAT`). When the format is fixed it gets a new marker, +and what to do with draft tables is decided then. No golden value pins any of it. + +## 1. spiral-sdk 0.16.78 + +Table metadata (`KeyedTable.get_metadata` / `set_metadata`) exists from 0.16.78. Compared +with `main`'s 0.16.74, the Python layer of 0.16.78 changes only those two methods (and the +generated service schemas); the snapshot pinning (`keyed_table_by_id(..., asof=)`), +projection (`scan(columns=)`) and key ranges `main` uses are untouched there. + +0.16.79 (2026-11-27) is newer but not chosen: it marks keyed tables deprecated, and +`Client.keyed_table`, `keyed_table_by_id` and `Project.create_keyed_table` each issue a +`DeprecationWarning`. Every SpiralDB path of Orcapod (the source, the connector, the store) +is on keyed tables. Its other change is a description of the ingest writer's lifetime. + +The bump is a dependency change for the developer to approve; it is one commit of its own +(`pyproject.toml`, `uv.lock`, `RELEASING.md`). + +## 2. The fake's table metadata + +`tests/test_databases/fake_spiral_sdk.py`, rule `table-metadata` (measured live with +0.16.78 on 2026-11-26): bytes by text key; an upsert that never deletes (an empty value is +stored); not versioned (every snapshot, `asof` included, sees the latest; a metadata write +makes no snapshot); readable before any row; a key over 255 UTF-8 bytes, or a key and value +together over 8,192 bytes, is refused with status 400 and nothing is written. Upserts of +different keys from two clients are all kept, and a reader never sees a half-written file. + +## 3. The identity record + +`src/orcapod/databases/spiral_store_identity.py`, on `main`'s shared rule +(`store_table_names.py`, ITL-1552): the table name is +`store_table_name(path, hint_length=96, digest_length=64)`. The label +`SPIRAL_TABLE_NAME_LABEL` stays defined there only, and no golden group is added (PR 589's +`spiral_table_name` group is not carried over); `test_store_table_names.py` keeps the test +vector. + +The table's metadata records, as four entries: the store format, the full path (compact +UTF-8 JSON array), the layout (the path's last component) and the data context of the +writer that created it. A table whose record is partial, of another format, unreadable, or +of another path than the one looked up raises `SpiralStoreTableCollisionError`; a table with +none of the entries is unmarked (`None`), for the caller to judge. + +## 4. The codec + +`src/orcapod/databases/spiral_store.py` (pure; no client), from PR 590 with PR 595's +manifest functions. Names (`encode_name`), types (`physical_schema`, `encode_rows`, +`decode_rows`), refusals before anything is written (`REFUSALS`), and the manifest: the +record path, the kind, the logical schema and the stored names at every depth, as one +payload (`manifest_bytes`) cut into metadata entries of at most 8,000 bytes +(`manifest_entries`) under a header naming the format, version, chunk count and a SHA-256 of +the payload (`payload_digest`; renamed from PR 595's `sha256` key, which the hash label rule +reads as a label literal). A header names exactly its chunks, so chunks of an earlier, +longer manifest are never read. + +`main`'s type matrix gained four rows after PR 590 (ITL-1372): a live logical type in a +struct child, a list item and a map value, and in dictionary values. The codec refuses all +four, naming the column: it records a logical type only on a whole column, and a dictionary +is an encoding it refuses. They are now listed as expected refusals; the four rows and the +round trip of every other row in one manifest pass. + +### Measured live with spiral-sdk 0.16.78 (2026-11-26, throwaway tables; PR 590) + +| What | Result | +|---|---| +| booleans, integers (`uint64` max), floats (signed zeros and NaN payloads, `float16` too), `decimal128/256`, `date32`, `date64` off midnight, `null` | kept bit for bit | +| timestamps of every unit, with and without a zone, every `int64` value | kept bit for bit: written as they are | +| `time32` / `time64` within a day | kept; outside one day the whole write is refused, so times are written as integers | +| `decimal32/64` | come back as `decimal128`: written as such, restored | +| strings, binaries, lists | come back in their small variants: normalized on read | +| struct fields | sorted by name at the top level (not inside a list): restored by name | +| map `keys_sorted` | dropped: restored from the manifest | +| a null fixed-size list of structs | kept | +| a null struct item inside a list | kept by the service; refused by the codec, which does not carry a struct's validity yet | +| a null struct at the top level, an empty struct, `fixed_size_binary`, `duration`, `interval` | refused | +| column and struct field names | refused: a `__` or `$` prefix, any `.`, exactly `*`, the empty name; NUL is cut silently. The codec's escape covers each | +| a write of no rows | publishes nothing; a key-only write is refused | + +## What is left (later stages of ITL-1446) + +Store mode in `SpiralDBConnector` and `ConnectorArrowDatabase` (create on first write, find +by name, the identity and manifest checks, data-context checks, listing for stale layouts), +the write rules of ITL-1386 for the store, the one-writer lease, the public switch-on with +save and load, and every table kind end to end. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index edb21d4c0..b51b425b9 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -391,6 +391,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | +| SpiralDB store manifest checksum | a store table's manifest payload (record path and Arrow schemas, canonical JSON); the store is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_store.py:_checksum` | | Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | | random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) | diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py new file mode 100644 index 000000000..c43c7855a --- /dev/null +++ b/src/orcapod/databases/spiral_store.py @@ -0,0 +1,1170 @@ +"""The codec of an Orcapod store table in SpiralDB (ITL-1446, ITL-1837). + +Pure functions, with no SpiralDB client: they say how a table Orcapod stores is written to +SpiralDB and how it is read back. Nothing calls them yet, and the format they write is +provisional (outside the 0.4.0 freeze). What SpiralDB keeps was measured live with +spiral-sdk 0.16.78; the measurements and the design are summarized in +``docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md``. + +* **Names.** ``encode_name`` gives a value column, or a struct field at any depth, a + name SpiralDB accepts. The key column ``__record_id`` keeps its name. Nothing decodes + a name: a read looks for exactly the stored names the manifest lists. +* **Types.** Rows are written in a *physical* form (``physical_schema``, ``encode_rows``) + and restored to the *logical* one (``decode_rows``). A type either comes back exactly + or is refused. Every refusal of a type, a name or a value that may be lifted is an + entry of one table, ``REFUSALS``. +* **The manifest.** One a table, written before its first rows; a table that still has + no rows may be recorded again (``manifest_entries``, ``read_manifest``): the + record path, the kind, the logical schema, and the stored names at every depth. It is + kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's identity + record (``spiral_store_identity``); never in the dataset's schema table, which is all + or nothing under one completion marker (decision of 2026-11-26). + +Logical types are handled by their identifier (extension name and metadata) alone, as +``ARROW:extension:*`` field metadata over the storage type: neither writing nor reading +a manifest consults the types registered in the process. +``canonical_form.declaration_form_schema`` makes them live. + +A SpiralDB store is a set of rows: the order of rows is not kept. An order-sensitive +step (``Batch``) over a stored source may therefore group differently than over a Delta +store. +""" + +from __future__ import annotations + +import base64 +import binascii +import hashlib +import json +import re +from collections.abc import Callable, Iterator, Mapping +from contextlib import contextmanager +from dataclasses import dataclass +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pyarrow.compute as pc + +from orcapod.databases.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 = 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 pa.types.is_dictionary(arrow_type): + # An encoding, not a type: refused here, before a dictionary of a logical + # type's values is taken for that type (``identity_node`` looks through it). + raise UnstorableInSpiralError(f"a SpiralDB store keeps no type {arrow_type}") + if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): + arrow_type = arrow_type.storage_type + _refuse_nested_identifier(arrow_type) + if _holds(arrow_type, _types.is_string_view) or _holds( + arrow_type, _types.is_binary_view + ): + raise VIEW.error() + metadata = _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") + if field.name == KEY_COLUMN and pc.count_distinct(column).as_py() < len( + column + ): + # The service refuses the whole write: refused before any table is made. + raise UnstorableInSpiralError("a record id repeated in one write") + chunks = [_encode(_storage(c), field) for c in column.chunks] + columns.append(cast(Any, pa.chunked_array)(chunks, type=stored.type)) + return pa.Table.from_arrays(columns, schema=physical) + + +def _storage(array: Any) -> Any: + """The storage of an extension array; any other array as it is.""" + return array.storage if isinstance(array, pa.ExtensionArray) else array + + +def _require_flag(array: Any, field: pa.Field[Any]) -> None: + """Refuse a null under a non-null field.""" + if not field.nullable and array.null_count: + raise UnstorableInSpiralError("a null in a non-nullable field") + + +def _encode(array: Any, field: pa.Field[Any]) -> Any: + """Return ``array``, the values of ``field``, in its physical form. + + Nested types are rebuilt around their converted children, from the rows a reader + sees: what a null list hides is not written. + """ + _require_flag(array, field) + logical: Any = field.type + t = pa.types + if t.is_struct(logical): + if array.null_count: + raise NULL_STRUCT.error() + children: list[Any] = [] + for i, child in enumerate(logical): + with _at(child.name): + children.append(_encode(array.field(i), child)) + fields = _children(_physical_type(logical)) + return pa.StructArray.from_arrays(children, fields=fields) + if _is_list(logical): + with _at("[]"): + items = _encode(array.flatten(), logical.value_field) + return _large_list(array, items, _physical_type(logical)) + if t.is_fixed_size_list(logical): + with _at("[]"): + items = _encode(array.flatten(), logical.value_field) + return _fixed_size_list(array, items, _physical_type(logical)) + if t.is_map(logical): + with _at("[]"): + rows = _map_rows(array) + keys = _encode(array.keys.take(rows), logical.key_field) + items = _encode(array.items.take(rows), logical.item_field) + return _map(array, keys, items, _physical_type(logical)) + if t.is_time(logical): + return array.view(_physical_type(logical)) # the same integers + return array.cast(_physical_type(logical)) + + +# ------------------------------------------------------------- nested array builders + + +def _valid(array: Any) -> Any: + """The rows of ``array`` that are not null, as a NumPy mask.""" + return array.is_valid().to_numpy(zero_copy_only=False) + + +def _lengths(array: Any) -> Any: + """The number of items of each row of a list or map array; 0 of a null row.""" + return np.diff(array.offsets.to_numpy(zero_copy_only=False)) * _valid(array) + + +def _offsets(array: Any) -> Any: + """Offsets from zero for the items of the non-null rows of a list or map array.""" + return np.concatenate([[0], np.cumsum(_lengths(array))]) + + +def _map_rows(array: Any) -> Any: + """Where the items of a map array's non-null rows are, in row order.""" + starts = array.offsets.to_numpy(zero_copy_only=False)[:-1] + lengths, offsets = _lengths(array), _offsets(array) + first = np.repeat(starts - offsets[:-1], lengths) + return pa.array((first + np.arange(offsets[-1])).astype(np.int64)) + + +def _map(array: Any, keys: Any, items: Any, target: Any) -> Any: + """Rebuild a map array around new keys and items, of its non-null rows.""" + return pa.MapArray.from_arrays( + pa.array(_offsets(array).astype(np.int32)), + keys, + items, + type=target, + mask=array.is_null() if array.null_count else None, + ) + + +def _fixed_size_list(array: Any, items: Any, target: Any) -> Any: + """Rebuild a fixed-size list array around new items, one per item of its non-null + rows; a null row's slots are filled with nulls, which no reader sees.""" + valid = _valid(array) + if not valid.all(): + slots = np.repeat(valid, target.list_size) + positions = np.cumsum(slots, dtype=np.int64) - 1 + items = items.take(pa.array(positions, pa.int64(), mask=~slots)) + # From buffers: a zero-width list keeps its row count, and a non-null item field + # may have the null slots of a null row. + return pa.Array.from_buffers( + target, + len(array), + cast(Any, [None if valid.all() else pa.array(valid).buffers()[1]]), + null_count=int((~valid).sum()), + children=[items], + ) + + +def _large_list(array: Any, items: Any, target: Any) -> Any: + """Rebuild a list array around new items, one per item of its non-null rows.""" + offsets = _offsets(array).astype(np.int64) + return pa.LargeListArray.from_arrays( + pa.array(offsets, pa.int64()), + items, + type=target, + mask=array.is_null() if array.null_count else None, + ) + + +# ------------------------------------------------------------------- rows, as read + + +def require_stored_schema(found: pa.Schema, manifest: StoreManifest) -> None: + """Refuse a table whose stored columns are not exactly the ones the manifest lists. + + For rows as read, and for the first commit of a table read back. + + Args: + found: The stored schema; columns and struct fields in any order, in small or + large variants. + manifest: The table's manifest. + + Raises: + StoredRowsError: If a column or a struct field, at any depth, is missing, extra, + repeated or of another type. + """ + _require_names(found.names, manifest.physical.names) + for field, physical in zip(manifest.schema, manifest.physical): + with _at(field.name): + _require_type(found.field(physical.name).type, field.type, physical.type) + + +def _require_names(found: list[str], expected: list[str]) -> None: + """Refuse stored sibling names other than the expected ones.""" + if sorted(found) != sorted(expected): + missing = sorted(set(expected) - set(found)) + extra = sorted(set(found) - set(expected)) + repeated = sorted({n for n in found if found.count(n) > 1}) + raise StoredRowsError( + f"stored names missing {missing}, not expected {extra}, repeated {repeated}" + ) + + +def _require_type(found: Any, logical: Any, stored: Any) -> None: + """Refuse a stored type other than ``stored``, under which ``logical`` is kept.""" + if pa.types.is_struct(stored) and pa.types.is_struct(found): + _require_names( + [f.name for f in _children(found)], [f.name for f in _children(stored)] + ) + for field, kept in zip(_children(logical), _children(stored)): + with _at(field.name): + _require_type(found.field(kept.name).type, field.type, kept.type) + elif _is_list(stored) and _is_list(found): + with _at("[]"): + _require_type(*(cast(Any, x).value_type for x in (found, logical, stored))) + elif pa.types.is_fixed_size_list(stored) and pa.types.is_fixed_size_list(found): + sizes = [cast(Any, x).list_size for x in (found, stored)] + if sizes[0] != sizes[1]: + raise StoredRowsError(f"stored as {found}, not as {stored} ({logical})") + with _at("[]"): + _require_type(*(cast(Any, x).value_type for x in (found, logical, stored))) + elif pa.types.is_map(stored) and pa.types.is_map(found): + with _at("[]"): + for part in ("key_type", "item_type"): + _require_type(*(getattr(x, part) for x in (found, logical, stored))) + elif arrow_utils.normalize_to_large_types(found, keep_null=True) != stored: + raise StoredRowsError(f"stored as {found}, not as {stored} ({logical})") + + +def decode_rows( + rows: pa.Table, manifest: StoreManifest, schema: pa.Schema | None = None +) -> pa.Table: + """Return rows read from SpiralDB as the logical rows they were written from. + + Args: + rows: Rows as read: stored names, columns and struct fields in any order. + manifest: The table's manifest. Columns are found by the stored names it lists. + schema: The manifest's schema with some of its logical types live, to give the + rows; the manifest's own when ``None``. + + Returns: + The rows under the schema, columns and struct fields in its order. + + Raises: + StoredRowsError: If the stored columns are not the manifest's + (``require_stored_schema``), or a value is not one that was written; the + column is named. + ManifestError: If ``schema`` is not the manifest's. + """ + target = manifest.schema if schema is None else schema + try: + difference = schema_difference(manifest.schema, target) + except UnstorableInSpiralError as exc: + raise ManifestError(f"not the recorded schema: {exc}") from exc + if difference is not None or target.names != manifest.schema.names: + raise ManifestError(f"not the recorded schema: {difference or 'column order'}") + require_stored_schema(rows.schema, manifest) + columns: list[Any] = [] + for out, field, physical in zip(target, manifest.schema, manifest.physical): + with _at(field.name): + column = rows.column(physical.name) + if field.name == KEY_COLUMN and column.null_count: + raise StoredRowsError("a null key") + chunks = [_decode(c, field, physical) for c in column.chunks] + live = isinstance(out.type, pa.BaseExtensionType) + storage: Any = out.type.storage_type if live else out.type + if storage != field.type: + chunks = [_retyped(c, storage) for c in chunks] + if live: + chunks = [ + pa.ExtensionArray.from_storage(cast(Any, out.type), c) + for c in chunks + ] + columns.append(cast(Any, pa.chunked_array)(chunks, type=out.type)) + return pa.Table.from_arrays(columns, schema=target) + + +def empty_rows(manifest: StoreManifest) -> pa.Table: + """Return zero rows of the recorded schema. + + What a table with a manifest and no value columns reads as (a crash before its first + rows). Such a table is never scanned: the service refuses a key-only scan. + + Args: + manifest: The table's manifest. + + Returns: + A table with no rows. + """ + return manifest.schema.empty_table() + + +def _retyped(array: Any, target: Any) -> Any: + """Return decoded values in another layout of their type (small or large variants). + + A type holding a map is rebuilt from its parts: pyarrow aborts the process when it + casts a map between layouts. Any other type is cast. + """ + t = pa.types + if not _holds(target, t.is_map): + return array.cast(target) + mask = array.is_null() if array.null_count else None + if t.is_struct(target): + children = [ + _retyped(array.field(i), target.field(i).type) + for i in range(target.num_fields) + ] + return pa.StructArray.from_arrays(children, fields=_children(target), mask=mask) + if t.is_map(target): + rows = _map_rows(array) + keys = _retyped(array.keys.take(rows), target.key_type) + items = _retyped(array.items.take(rows), target.item_type) + return _map(array, keys, items, target) + items = _retyped(array.flatten(), target.value_type) + if t.is_fixed_size_list(target): + return _fixed_size_list(array, items, target) + if t.is_list(target): + 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 + 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, written only while no public way opens a store: the persisted format and +# version are fixed when the store is switched on, with a decision then on reading the +# tables written in this draft format. Provisional: outside the 0.4.0 freeze. +MANIFEST_FORMAT = "orcapod.spiral_store.draft" +MANIFEST_VERSION = 0 +# In the recorded Arrow schema an ``ARROW:extension:*`` key is written behind this +# mark (and a key that starts with the mark too, so the marking is reversible), so +# reading it back never builds an extension type that happens to be registered. +_MARKED = b"orcapod:key:" +_EXTENSION_KEYS = b"ARROW:extension:" + + +@dataclass(frozen=True) +class StoreManifest: + """What a store table's manifest says. Make one with ``new_manifest``. + + Attributes: + record_path: The table's full record path, each component exact. + kind: What the table is, as text; the codec does not interpret it. + schema: The table's logical schema (``logical_schema``). + physical: The stored schema (``physical_schema``), field for field in the order + of ``schema`` at every depth: it lists the stored names. + """ + + record_path: tuple[str, ...] + kind: str + schema: pa.Schema + physical: pa.Schema + + +def new_manifest( + record_path: tuple[str, ...], kind: str, schema: pa.Schema +) -> StoreManifest: + """Return the manifest of a table to be created. + + Args: + record_path: The table's full record path. + kind: What the table is. + schema: The schema of its rows. + + Returns: + The manifest. + + Raises: + UnstorableInSpiralError: If the schema cannot be stored, or 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 payload that records ``manifest``. + + ``manifest_entries`` cuts it into a table's metadata entries. Writing the same + manifest again gives the same bytes. Two manifests whose schemas are equivalent but + represented differently (field metadata in another insertion order) can give + different bytes, because the Arrow IPC inside is not canonical: compare schemas with + ``schema_difference``, never by these bytes. + + Args: + manifest: The manifest. + + Returns: + Canonical JSON: the format and its version, the kind, the record path, and both + schemas as base64 of their Arrow IPC form. + """ + return json.dumps( + { + "format": MANIFEST_FORMAT, + "kind": manifest.kind, + "physical": _schema_text(manifest.physical), + "record_path": list(manifest.record_path), + "schema": _schema_text(_map_metadata(manifest.schema, _mark)), + "version": MANIFEST_VERSION, + }, + separators=(",", ":"), + sort_keys=True, + ).encode("ascii") + + +def _schema_text(schema: pa.Schema) -> str: + """An Arrow schema as base64 of its IPC form.""" + return base64.b64encode(schema.serialize().to_pybytes()).decode("ascii") + + +def _schema_of(text: object) -> pa.Schema: + """The inverse of ``_schema_text``.""" + if not isinstance(text, str): + raise ManifestError("a schema is not text") + try: + raw = base64.b64decode(text, validate=True) + return pa.ipc.read_schema(pa.py_buffer(raw)) + except (binascii.Error, ValueError, pa.ArrowException, OSError) as exc: + raise ManifestError(f"a schema cannot be read ({exc})") from exc + + +def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: + """Return the manifest ``manifest_bytes`` recorded. + + Args: + recorded: The payload, as reassembled from the chunks in the table's metadata + (``read_manifest``). + record_path: The record path the table was looked up for. + + Returns: + The manifest. + + Raises: + ManifestError: If the bytes are not a manifest, of an unknown format or version, + or of another path; or the recorded schemas are not a store table's. + """ + try: + body = json.loads(recorded.decode("ascii")) + except (ValueError, RecursionError) as exc: + raise ManifestError(f"a manifest is not JSON ({exc})") from exc + if not isinstance(body, dict): + raise ManifestError("a manifest is not a JSON object") + fields = cast("dict[str, Any]", body) + if fields.get("format") != MANIFEST_FORMAT: + raise ManifestError(f"unknown manifest format {fields.get('format')!r}") + version = fields.get("version") + if type(version) is not int or version != MANIFEST_VERSION: + raise ManifestError( + f"unsupported manifest version {version!r} " + f"(this Orcapod reads {MANIFEST_VERSION})" + ) + path, kind = fields.get("record_path"), fields.get("kind") + if not isinstance(path, list) or not all( + isinstance(part, str) for part in cast("list[object]", path) + ): + raise ManifestError("the record path is not a list of strings") + if not isinstance(kind, str): + raise ManifestError("the kind is not text") + if tuple(cast("list[str]", path)) != record_path: + raise ManifestError( + f"the table is recorded as {path}, not as {list(record_path)}" + ) + try: + schema = _map_metadata(_schema_of(fields.get("schema")), _unmark) + physical = _schema_of(fields.get("physical")) + usable = logical_schema(schema) + expected = physical_schema(schema) + except UnstorableInSpiralError as exc: + raise ManifestError( + f"the recorded schema is not a store schema: {exc}" + ) from exc + except UnicodeDecodeError as exc: + # pyarrow holds a name of any bytes, and fails where it is read as text. + raise ManifestError(f"a recorded name is not UTF-8 text ({exc})") from exc + # The stored names are read from the manifest, never recomputed; its shape and types + # must be the ones the logical schema is kept in. + if _without_names(physical) != _without_names(expected) or ( + usable.names.index(KEY_COLUMN) != physical.get_field_index(KEY_COLUMN) + ): + raise ManifestError("the recorded stored schema is not the logical one's") + try: + _require_distinct(physical) + except UnicodeDecodeError as exc: + raise ManifestError(f"a recorded name is not UTF-8 text ({exc})") from exc + return StoreManifest(record_path, kind, usable, physical) + + +MANIFEST_KEY = "orcapod.manifest" +"""The metadata key of a manifest's header; its chunks are ``/``.""" +# SpiralDB holds a key and its value in 8,192 bytes together (measured with spiral-sdk +# 0.16.78); a chunk leaves room for its key. Part of the format: one payload is always +# cut at the same places. +_CHUNK_BYTES = 8_000 + + +def manifest_entries(manifest: StoreManifest) -> dict[str, bytes]: + """Return the metadata entries that record ``manifest`` in its table. + + The chunks of the payload, then the header: the format, the version, the number of + chunks and the SHA-256 of the payload, a checksum of what the chunks hold. Written in + one upsert; a header always names exactly its chunks, so chunks of an earlier, + interrupted manifest are never read. + + Args: + manifest: The manifest. + + Returns: + The entries, chunks first. + """ + payload = manifest_bytes(manifest) + pieces = [ + payload[i : i + _CHUNK_BYTES] for i in range(0, len(payload), _CHUNK_BYTES) + ] + header = { + "chunks": len(pieces), + "format": MANIFEST_FORMAT, + "payload_digest": _checksum(payload), + "version": MANIFEST_VERSION, + } + entries = {f"{MANIFEST_KEY}/{i}": piece for i, piece in enumerate(pieces)} + entries[MANIFEST_KEY] = json.dumps( + header, separators=(",", ":"), sort_keys=True + ).encode("ascii") + return entries + + +def read_manifest( + metadata: Mapping[str, bytes], record_path: tuple[str, ...] +) -> StoreManifest | None: + """Return the manifest in a table's metadata. + + Args: + metadata: All of the table's metadata. + record_path: The record path the table was looked up for. + + Returns: + The manifest, or ``None`` when the table holds no header (a creation that + stopped before its manifest). + + Raises: + ManifestError: If the header or its chunks cannot be read in full, the header + is of another format or version, the chunks do not match their checksum, + or the manifest is not one of ``read_manifest_bytes``. + """ + raw = metadata.get(MANIFEST_KEY) + if raw is None: + return None + try: + header = json.loads(raw.decode("ascii")) + except (ValueError, RecursionError) as exc: + raise ManifestError(f"a manifest header is not JSON ({exc})") from exc + if not isinstance(header, dict): + raise ManifestError("a manifest header is not a JSON object") + fields = cast("dict[str, Any]", header) + if fields.get("format") != MANIFEST_FORMAT: + raise ManifestError(f"unknown manifest format {fields.get('format')!r}") + version = fields.get("version") + if type(version) is not int or version != MANIFEST_VERSION: + raise ManifestError( + f"unsupported manifest header version {version!r} " + f"(this Orcapod reads {MANIFEST_VERSION})" + ) + count = fields.get("chunks") + if type(count) is not int or count < 1: + raise ManifestError(f"invalid chunk count {count!r}") + if count > len(metadata): + # More chunks than the metadata has entries: some must be missing. Refused + # before a key is listed for each, so a corrupt count allocates nothing. + raise ManifestError( + f"the manifest names {count} chunks; the metadata holds " + f"{len(metadata)} entries" + ) + keys = [f"{MANIFEST_KEY}/{i}" for i in range(count)] + missing = [k for k in keys if k not in metadata] + if missing: + raise ManifestError(f"the manifest's chunks {missing} are missing") + payload = b"".join(metadata[k] for k in keys) + if fields.get("payload_digest") != _checksum(payload): + raise ManifestError("the manifest's chunks do not match its checksum") + return read_manifest_bytes(payload, record_path) + + +def _checksum(payload: bytes) -> str: + """The SHA-256 of a manifest payload, as hex: the header's check of its chunks.""" + return hashlib.sha256(payload).hexdigest() + + +def _without_names(fields: Any) -> list[object]: + """The types of fields at every depth, without names.""" + shape: list[object] = [] + for field in fields: + arrow_type = field.type + inner = _children(arrow_type) + size = getattr(arrow_type, "list_size", None) + shape.append( + (arrow_type.id, size, _without_names(inner)) if inner else arrow_type + ) + return shape + + +def _require_distinct(fields: Any) -> None: + """Refuse a recorded stored schema with two siblings of one name.""" + names = [field.name for field in fields] + if len(set(names)) != len(names): + raise ManifestError("the recorded stored schema repeats a name") + for field in fields: + _require_distinct(_children(field.type)) + + +def _mark(key: bytes) -> bytes: + """The form a field metadata key is recorded in.""" + return _MARKED + key if key.startswith((_MARKED, _EXTENSION_KEYS)) else key + + +def _unmark(key: bytes) -> bytes: + """The inverse of ``_mark``.""" + return key.removeprefix(_MARKED) + + +def _map_metadata(schema: pa.Schema, change: Any) -> pa.Schema: + """Return ``schema`` with every field metadata key, at every depth, changed.""" + return pa.schema( + [_map_field(field, change) for field in schema], + metadata=cast(Any, schema.metadata), + ) + + +def _map_field(field: pa.Field[Any], change: Any) -> pa.Field[Any]: + """``_map_metadata`` for one field. A map has no metadata inside.""" + arrow_type: Any = field.type + if pa.types.is_struct(arrow_type): + arrow_type = pa.struct([_map_field(f, change) for f in _children(arrow_type)]) + elif pa.types.is_large_list(arrow_type): + arrow_type = pa.large_list(_map_field(arrow_type.value_field, change)) + elif pa.types.is_fixed_size_list(arrow_type): + arrow_type = pa.list_( + _map_field(arrow_type.value_field, change), arrow_type.list_size + ) + metadata = {change(k): v for k, v in (field.metadata or {}).items()} + return pa.field(field.name, arrow_type, field.nullable, cast(Any, metadata or None)) + + +# ------------------------------------------------- comparing a schema with a manifest's + + +def schema_difference(recorded: pa.Schema, other: pa.Schema) -> str | None: + """Return how a schema differs from a recorded one, or ``None`` when it is the same. + + Compared as decoded, never as bytes: the schema metadata, and each column by name, + with its type, nullability and metadata, field by field at every depth. The order of + columns and of metadata entries does not count: one pipeline's table may be written + with its columns in another order. + + Args: + recorded: A manifest's schema. + other: Another one, in any form ``logical_schema`` takes. + + Returns: + The first difference, in words. + + Raises: + UnstorableInSpiralError: If a schema cannot be stored. + """ + left, right = logical_schema(recorded), logical_schema(other) + if dict(left.metadata or {}) != dict(right.metadata or {}): + return "the schema metadata differs" + if set(left.names) != set(right.names): + return f"columns {sorted(left.names)} and {sorted(right.names)}" + for field in left: + difference = _field_difference(field, right.field(field.name), repr(field.name)) + if difference is not None: + return difference + return None + + +def _field_difference(a: pa.Field[Any], b: pa.Field[Any], where: str) -> str | None: + """How two fields differ. Arrow's own equality ignores nested names.""" + for what, x, y in ( + ("name", a.name, b.name), + ("nullable", a.nullable, b.nullable), + ("metadata", dict(a.metadata or {}), dict(b.metadata or {})), + ("type", a.type.id, b.type.id), + ("number of fields", a.type.num_fields, b.type.num_fields), + ): + if x != y: + shown = (a.type, b.type) if what == "type" else (x, y) + return f"{where}: {what} {shown[0]} and {shown[1]}" + if not a.type.num_fields: + return None if a.type == b.type else f"{where}: type {a.type} and {b.type}" + for what in ("list_size", "keys_sorted"): + x, y = (getattr(f.type, what, None) for f in (a, b)) + if x != y: + return f"{where}: {what} {x} and {y}" + struct = pa.types.is_struct(a.type) + for x, y in zip(_children(a.type), _children(b.type)): + inner = f"{where}.{x.name}" if struct else f"{where}[]" + difference = _field_difference(x, y, inner) + if difference is not None: + return difference + return None diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py new file mode 100644 index 000000000..ba4510410 --- /dev/null +++ b/src/orcapod/databases/spiral_store_identity.py @@ -0,0 +1,222 @@ +"""The name and identity record of a SpiralDB store table (ITL-1837). + +A store table's full path (the store's base path plus the record path) is too long for a +SpiralDB table name, so the table is named by the rule every connector store shares, +``store_table_names.store_table_name``, with SpiralDB's budget: a hint of at most +``SPIRAL_HINT_LENGTH`` characters and the whole 64-digit digest. The full path is written +into the table's own metadata, with the store format, the layout and the data context of +the writer that created it. A store computes the name to find a table and never lists to +find one; the record says which path a table holds, and a table recording another path is +refused (``SpiralStoreTableCollisionError``). + +The store format is provisional: it is outside the 0.4.0 freeze, and no public way to +open a store exists yet. Its marker (``STORE_FORMAT``) says so, so a table written in it +is told apart from one written in the format that is eventually fixed. + +The module is pure: it imports no SpiralDB client. +""" + +from __future__ import annotations + +import json +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +from typing import cast + +from orcapod.databases.store_table_names import ( + STORE_TABLE_NAME_PREFIX, + store_table_name, + store_table_path_json, + table_name_hint, +) + + +class SpiralStoreTableCollisionError(ValueError): + """A SpiralDB table under a store table's name is not that store table. + + A store table's name is computed from its full path; its metadata records the path, + the store format, the layout and the data context. A table whose record names another + path or format, or is incomplete or unreadable, is refused: never read, written or + adopted. Internal while the store is not offered (it moves to ``orcapod.errors`` when + a store can be opened). + + Attributes: + reason: What is wrong. + table: The table, as ``"//"``, added by the caller that + knows it; ``None`` otherwise. + """ + + def __init__(self, reason: str, *, table: str | None = None) -> None: + self.reason = reason + self.table = table + where = "" if table is None else f"table {table}: " + super().__init__(f"{where}not this store's table: {reason}") + + +SPIRAL_HINT_LENGTH = 96 +"""The most characters of a SpiralDB store table name's hint.""" + +SPIRAL_DIGEST_LENGTH = 64 +"""The hex digits of the path digest a SpiralDB store table name keeps: all of them.""" + +STORE_FORMAT = "orcapod.spiral_store.draft" +"""The format of a store table, recorded in its metadata. Provisional: fixed (and renamed) +when the store is switched on.""" + +MAX_METADATA_ENTRY_BYTES = 8192 +"""The most UTF-8 bytes of a metadata entry's key and value together that SpiralDB accepts +(measured with spiral-sdk 0.16.78).""" + +STORE_KEY = "orcapod.store" +PATH_KEY = "orcapod.path" +LAYOUT_KEY = "orcapod.layout" +DATA_CONTEXT_KEY = "orcapod.data_context" +_RECORD_KEYS = (STORE_KEY, PATH_KEY, LAYOUT_KEY, DATA_CONTEXT_KEY) + + +def spiral_store_table_name(path: Sequence[str]) -> str: + """Return the SpiralDB name of the store table at ``path``. + + Args: + path: The full path components: the store's base path, then the record path. + + Returns: + ``o1__``, at most 164 characters, all in ``[a-z0-9_]``. + + Raises: + ValueError: If the path cannot be named (``store_table_path_json``). + """ + return store_table_name( + path, hint_length=SPIRAL_HINT_LENGTH, digest_length=SPIRAL_DIGEST_LENGTH + ) + + +def spiral_store_table_name_prefix(prefix: Sequence[str]) -> str: + """Return the start of the name of every store table whose path starts with ``prefix``. + + Tables of other paths can share it: a listing narrowed by it is a superset, and each + table's recorded path decides. + + Args: + prefix: Leading full path components; empty for every store table. + """ + if not prefix: + return STORE_TABLE_NAME_PREFIX + return STORE_TABLE_NAME_PREFIX + table_name_hint( + prefix, hint_length=SPIRAL_HINT_LENGTH + ) + + +@dataclass(frozen=True) +class StoreTableRecord: + """What a store table's metadata records. + + Attributes: + path: The full path components. + layout: The table's layout, the path's last component. + data_context_key: The data context of the writer that created the table. + """ + + path: tuple[str, ...] + layout: str + data_context_key: str + + +def store_table_metadata( + path: Sequence[str], data_context_key: str +) -> dict[str, bytes]: + """Return the metadata a new store table at ``path`` is given. + + Args: + path: The full path components. + data_context_key: The data context of the writer creating the table. + + Raises: + ValueError: If the path cannot be named, the data context key is empty, or an + entry is over SpiralDB's entry limit (``MAX_METADATA_ENTRY_BYTES``). + """ + path_json = store_table_path_json(path) + 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. + """ + if not any(k in metadata for k in _RECORD_KEYS): + return None + missing = [k for k in _RECORD_KEYS if k not in metadata] + if missing: + raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + if metadata[STORE_KEY] != STORE_FORMAT.encode(): + raise SpiralStoreTableCollisionError( + f"its format is {metadata[STORE_KEY]!r}, not {STORE_FORMAT!r}" + ) + try: + path: object = json.loads(metadata[PATH_KEY].decode()) # pyright: ignore[reportAny] # checked below + layout = metadata[LAYOUT_KEY].decode() + data_context_key = metadata[DATA_CONTEXT_KEY].decode() + except (ValueError, RecursionError) as exc: # JSON, UTF-8, the integer limit, depth + raise SpiralStoreTableCollisionError( + f"its record cannot be read: {exc}" + ) from exc + items = cast("list[object]", path) if isinstance(path, list) else [] + if not items or not all(isinstance(c, str) for c in items): + raise SpiralStoreTableCollisionError( + f"its path is not a list of names: {path!r}" + ) + components = tuple(cast("list[str]", items)) + try: + _ = store_table_path_json(components) # what a writer refuses, a reader refuses + 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/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index e022d4207..26349b244 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -7,7 +7,8 @@ Each rule of ``RULES`` was seen on the service with spiral-sdk 0.16.74 and 0.16.75 on November 24, 2026, on throwaway tables, unless it says otherwise; its name is cited where -the rule is applied. +the rule is applied. The table-metadata and store-codec conformance tests passed live with +spiral-sdk 0.16.78 on November 26, 2026 (ITL-1495, ITL-1497). """ from __future__ import annotations @@ -16,6 +17,7 @@ import operator import os import struct +import threading import types import urllib.parse import uuid @@ -60,8 +62,12 @@ "null-key": "a null key is refused", "key-only": "a write without a value column is refused", "no-key": "a write without a key column is refused", - "reserved": "a value column starting with '__' or '$', or any with '.', is refused", - "nul": "a column name is cut at a NUL character", + "reserved": "a value column or struct field starting with '__' or '$', any with '.', " + "and one named '' or '*' (spiral-sdk 0.16.78, November 26, 2026) is refused", + "time-of-day": "spiral-sdk 0.16.78 (November 26, 2026): a time32 or time64 value outside " + "one day, at any depth, refuses the whole write", + "nul": "a column name is cut at a NUL character; so is a struct field name, at every " + "depth (spiral-sdk 0.16.78, November 26, 2026)", "type-conflict": "a column of another type than stored is refused", "unsupported": "duration, interval, fixed-size binary, union, an empty struct and a " "null struct outside a list are refused", @@ -75,8 +81,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" @@ -198,11 +215,128 @@ def _refused_type(t: pa.DataType) -> str | None: def _reserved(name: str) -> str | None: """Return the refusal of a reserved column name (``reserved``).""" - if name.startswith(("__", "$")) or "." in name: + if name.startswith(("__", "$")) or "." in name or name in ("", "*"): return f'Column name "{name}" is reserved' return None +_DAY = {"s": 86_400, "ms": 86_400_000, "us": 86_400_000_000, "ns": 86_400_000_000_000} + + +def _decoded(array: Any) -> Any: + """``array`` with every dictionary and run-end encoding at its top undone, as the + service stores it (``types``); a run-end-encoded struct included, which pyarrow + cannot decode itself.""" + if isinstance(array, pa.ExtensionArray): + array = array.storage + if pa.types.is_dictionary(array.type): + return _decoded(array.dictionary_decode()) + if pa.types.is_run_end_encoded(array.type): + return _decoded(array.values.take(pa.array(_run_indices(array), pa.int64()))) + return array + + +def _run_indices(array: Any) -> list[int]: + """The run of each row of a run-end-encoded array (a slice of one included): only + the runs that overlap the slice are expanded, and only where they overlap it.""" + start, stop = array.offset, array.offset + len(array) + indices: list[int] = [] + begin = 0 + for run, end in enumerate(array.run_ends.to_pylist()): + low, high = max(begin, start), min(end, stop) + if low < high: + indices.extend([run] * (high - low)) + if end >= stop: + break + begin = end + return indices + + +def _needs_decoding(t: Any, *, in_extension: bool = False) -> bool: + """Whether a column must be rebuilt as the service stores it before its names are + cut (``types``, ``nul``): it holds a dictionary or run-end encoding at any depth, or + an extension type whose storage holds a struct field name with NUL.""" + if pa.types.is_dictionary(t) or pa.types.is_run_end_encoded(t): + return True + if isinstance(t, pa.BaseExtensionType): + return _needs_decoding(t.storage_type, in_extension=True) + if in_extension and pa.types.is_struct(t): + if any("\0" in t.field(i).name for i in range(t.num_fields)): + return True + return any( + _needs_decoding(t.field(i).type, in_extension=in_extension) + for i in range(t.num_fields) + ) + + +def _deep_decoded(array: Any) -> Any: + """``array`` with every dictionary and run-end encoding undone, at any depth, as the + service stores it (``types``), so nested names are cut as at the top (``nul``).""" + a = _decoded(array) + if a.offset: + a = pa.concat_arrays([a]) # rebuilt from offset zero: pyarrow builds no slice + t = a.type + mask = a.is_null() if a.null_count else None + if pa.types.is_struct(t): + children = [_deep_decoded(a.field(i)) for i in range(t.num_fields)] + fields = [t.field(i).with_type(c.type) for i, c in enumerate(children)] + return pa.StructArray.from_arrays(children, fields=fields, mask=mask) + if pa.types.is_list(t) or pa.types.is_large_list(t): + values = _deep_decoded(a.values) + kind: Any = pa.list_ if pa.types.is_list(t) else pa.large_list + cls: Any = pa.ListArray if pa.types.is_list(t) else pa.LargeListArray + target = kind(t.value_field.with_type(values.type)) + return cls.from_arrays(a.offsets, values, type=target, mask=mask) + if pa.types.is_fixed_size_list(t): + size = t.list_size + values = _deep_decoded(a.values.slice(a.offset * size, len(a) * size)) + target = pa.list_(t.value_field.with_type(values.type), size) + if size == 0: # no values to count the rows by: from buffers + valid = pc.is_valid(a).buffers()[1] if a.null_count else None + return pa.Array.from_buffers( + target, + len(a), + cast(Any, [valid]), # the stubs take no None for an absent buffer + null_count=a.null_count, + children=[values], + ) + return cast(Any, pa.FixedSizeListArray).from_arrays( + values, type=target, mask=mask + ) + if pa.types.is_map(t): + keys, items = _deep_decoded(a.keys), _deep_decoded(a.items) + target = cast(Any, pa.map_)( + t.key_field.with_type(keys.type), + t.item_field.with_type(items.type), + keys_sorted=t.keys_sorted, + ) + return cast(Any, pa.MapArray).from_arrays( + a.offsets, keys, items, type=target, mask=mask + ) + return a + + +def _time_outside_a_day(array: Any) -> bool: + """Whether a time value outside one day is in ``array``, at any depth (``time-of-day``).""" + array = _decoded(array) + t = array.type + if pa.types.is_time(t): + ticks = array.view(pa.int32() if pa.types.is_time32(t) else pa.int64()) + day = _DAY[t.unit] + return any(v is not None and not 0 <= v < day for v in ticks.to_pylist()) + if pa.types.is_struct(t): + return any(_time_outside_a_day(array.field(i)) for i in range(t.num_fields)) + if pa.types.is_map(t): + return _time_outside_a_day(array.keys) or _time_outside_a_day(array.items) + if ( + pa.types.is_list(t) + or pa.types.is_large_list(t) + or pa.types.is_fixed_size_list(t) + ): + return _time_outside_a_day(array.flatten()) + return False + + def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: """Return ``array`` as it is stored, of type ``target``. @@ -216,10 +350,7 @@ def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: a: Any = array if isinstance(a, pa.ExtensionArray): a = a.storage - if pa.types.is_dictionary(a.type): - a = a.dictionary_decode() - if pa.types.is_run_end_encoded(a.type): - a = cast(Any, pc).run_end_decode(a) + a = _decoded(a) if a.type == target: return a t: Any = target @@ -253,12 +384,54 @@ def _stored_array(array: pa.Array[Any], target: pa.DataType) -> pa.Array[Any]: values = _stored_array( a.values.slice(a.offset * t.list_size, len(a) * t.list_size), t.value_type ) + if t.list_size == 0: # no values to count the rows by: from buffers + valid = pc.is_valid(a).buffers()[1] if a.null_count else None + return pa.Array.from_buffers( + t, + len(a), + cast(Any, [valid]), # the stubs take no None for an absent buffer + null_count=a.null_count, + children=[values], + ) return cast(Any, pa.FixedSizeListArray).from_arrays( values, type=t, mask=a.is_null() if a.null_count else None ) return a.cast(target) +def _names_cut_at_nul(t: Any) -> Any: + """Return ``t`` with every struct field name cut at its first NUL (``nul``).""" + if isinstance(t, pa.BaseExtensionType): + return t + if pa.types.is_struct(t): + return pa.struct( + [ + pa.field( + f.name.split("\0")[0], + _names_cut_at_nul(f.type), + f.nullable, + f.metadata, + ) + for f in t + ] + ) + if pa.types.is_large_list(t) or pa.types.is_list(t): + item = t.value_field + kind: Any = pa.large_list if pa.types.is_large_list(t) else pa.list_ + return kind(item.with_type(_names_cut_at_nul(item.type))) + if pa.types.is_fixed_size_list(t): + item = t.value_field + return pa.list_(item.with_type(_names_cut_at_nul(item.type)), t.list_size) + if pa.types.is_map(t): + map_of: Any = pa.map_ # the stubs take no fields and keys_sorted together + return map_of( + t.key_field.with_type(_names_cut_at_nul(t.key_type)), + t.item_field.with_type(_names_cut_at_nul(t.item_type)), + keys_sorted=t.keys_sorted, + ) + return t + + def _check_nulls(array: Any, field: pa.Field[Any], *, in_list: bool) -> None: """Refuse a null where the written type has none, or a null struct (``non-null``, ``unsupported``). @@ -368,6 +541,33 @@ def drop(self, table_id: str) -> None: path.unlink() folder.rmdir() + def metadata(self, table_id: str) -> dict[str, bytes]: + """Return a table's metadata (``table-metadata``).""" + _ = self.by_id(table_id) + path = self.root / table_id / "metadata.json" + if not path.exists(): + return {} + stored = cast("dict[str, str]", json.loads(path.read_text())) + return {k: bytes.fromhex(v) for k, v in stored.items()} + + def set_metadata(self, table_id: str, entries: dict[str, bytes]) -> None: + """Upsert ``entries`` into a table's metadata (``table-metadata``).""" + for key, value in entries.items(): + size = len(key.encode()) + if ( + size > _MAX_METADATA_KEY_BYTES + or size + len(value) > _MAX_METADATA_ENTRY_BYTES + ): + raise _status(400) + with _metadata_lock: # one upsert at a time: concurrent keys are all kept + stored = self.metadata(table_id) + stored.update(entries) + # Written beside, then put in place: a reader sees a whole mapping. + target = self.root / table_id / "metadata.json" + written = target.with_suffix(".json.tmp") + _ = written.write_text(json.dumps({k: v.hex() for k, v in stored.items()})) + _ = written.replace(target) + def keys(self, table_id: str) -> pa.Schema: """Return a table's key schema.""" raw = (self.root / table_id / "keys.arrow").read_bytes() @@ -402,6 +602,22 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: """Validate ``rows`` and return them as they are stored (``stage``).""" names = [name.split("\0")[0] for name in rows.column_names] # nul rows = rows.rename_columns(names) + for i, field in enumerate(rows.schema): # nul, at every depth + if _needs_decoding(field.type): + # Stored as its values (``types``): decoded first, so its names are cut. + decoded = pa.chunked_array( + [_deep_decoded(c) for c in rows.column(i).chunks] + ) + rows = rows.set_column(i, field.with_type(decoded.type), decoded) + field = rows.schema.field(i) + cut = _names_cut_at_nul(field.type) + if cut != field.type: + column = rows.column(i) + rows = rows.set_column( + i, + field.with_type(cut), # the field, flag and metadata kept + pa.chunked_array([c.view(cut) for c in column.chunks], type=cut), + ) for key in keys: if key not in names: raise _refuse(f"Input batch is missing key field '{key}'") @@ -422,6 +638,11 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: rows.column(field.name).chunks or [pa.array([], field.type)] ) _check_nulls(array, field, in_list=False) + if _time_outside_a_day(array): + raise SpiralError( + "Scandal:Internal (message: Vortex error: Invalid time scalar: adding " + "duration to time overflowed)" + ) target = _stored_type(field.type) if field.name in stored.names: kept = stored.field(field.name).type @@ -675,6 +896,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_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py new file mode 100644 index 000000000..152de88c9 --- /dev/null +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -0,0 +1,42 @@ +"""The SpiralDB fake's own decoding of what it is given (CodeRabbit on PR 595).""" + +from __future__ import annotations + +from typing import Any + +import pyarrow as pa +import pytest + +from tests.test_databases import fake_spiral_sdk as fake + + +def test_a_run_end_encoded_slice_expands_only_its_own_rows() -> None: + """Every slice decodes to its own values, and a slice of one row of a run of two + billion values builds one index, not one per value of the run.""" + small = pa.RunEndEncodedArray.from_arrays( + pa.array([3, 5, 9], pa.int32()), pa.array(["a", "b", "c"]) + ) + for offset in range(10): + for length in range(10 - offset): + piece: Any = small.slice(offset, length) + assert fake._decoded(piece).to_pylist() == piece.to_pylist() # pyright: ignore[reportPrivateUsage] + huge = pa.RunEndEncodedArray.from_arrays( + pa.array([1, 2**31 - 1], pa.int32()), pa.array(["a", "b"]) + ) + last = huge.slice(2**31 - 2, 1) + assert fake._run_indices(last) == [1] # pyright: ignore[reportPrivateUsage] + assert fake._decoded(last).to_pylist() == ["b"] # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.parametrize("offset", [0, 1]) +def test_a_zero_width_fixed_size_list_of_dictionaries_keeps_its_rows( + offset: int, +) -> None: + """A fixed-size list of size 0 has no values to count its rows by: it is rebuilt + from its buffers, rows and nulls kept.""" + arrow_type = pa.list_(pa.dictionary(pa.int8(), pa.string()), 0) + given: Any = pa.array([[], None, [], []], arrow_type).slice(offset) + got = fake._deep_decoded(given) # pyright: ignore[reportPrivateUsage] + assert len(got) == len(given) + assert got.to_pylist() == given.to_pylist() + assert got.type == pa.list_(pa.string(), 0) diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py new file mode 100644 index 000000000..1ee252c49 --- /dev/null +++ b/tests/test_databases/test_spiral_store.py @@ -0,0 +1,1596 @@ +"""The codec of a SpiralDB store table: names, types, rows and the manifest (ITL-1446, ITL-1497). + +No SpiralDB and no fake: ``as_spiral_returns`` does to encoded rows what SpiralDB does +(columns and struct fields sorted by name, rows in another order and other chunks, other +list item names, small or large variants). +""" + +from __future__ import annotations + +import base64 +import datetime as dt +import decimal +import json +import math +import random +import re +import subprocess +import sys +from collections.abc import Callable +from pathlib import Path +from typing import Any, cast + +import numpy as np +import pyarrow as pa +import pytest + +from orcapod.contexts import get_default_context +from orcapod.databases import spiral_store as store +from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.utils.arrow_utils import normalize_to_large_types +from tests.test_databases.type_matrix import ( + ROWS, + Row, + build_table, + field_difference, +) +from tests.test_databases.type_matrix import ( + _same_values as same_values, # pyright: ignore[reportPrivateUsage] +) + +KEY = store.KEY_COLUMN +NAME_KEY, METADATA_KEY = b"ARROW:extension:name", b"ARROW:extension:metadata" + +chunked: Any = pa.chunked_array # the stubs type ``type=`` as None +map_of: Any = pa.map_ # the stubs lack fields and keys_sorted +schema_of: Any = pa.schema # the stubs take no mix of fields and pairs +# The stubs take literal units and zones only. +timestamp: Any = pa.timestamp +duration: Any = pa.duration + + +# ------------------------------------------------------------------------- helpers + + +def ids(n: int) -> Any: + return pa.array([f"r{i:04d}".encode() for i in range(n)], pa.large_binary()) + + +def keyed(columns: dict[str, Any], fields: list[Any] | None = None) -> pa.Table: + """A table of ``columns`` (arrays) with a key column in the middle.""" + n = len(next(iter(columns.values()))) + fields = fields or [pa.field(k, v.type) for k, v in columns.items()] + half = len(fields) // 2 + fields = [*fields[:half], pa.field(KEY, pa.large_binary(), False), *fields[half:]] + arrays = [ids(n) if f.name == KEY else columns[f.name] for f in fields] + return pa.Table.from_arrays(arrays, schema=schema_of(fields)) + + +def _returned(array: Any, small: bool) -> Any: + """One array as SpiralDB may give it back.""" + t = pa.types + if t.is_struct(array.type): + assert array.null_count == 0 + order = sorted( + range(array.type.num_fields), key=lambda i: array.type.field(i).name + ) + children = [_returned(array.field(i), small) for i in order] + names = [array.type.field(i).name for i in order] + return pa.StructArray.from_arrays( + children, fields=[pa.field(n, c.type) for n, c in zip(names, children)] + ) + mask = array.is_null() if array.null_count else None + if t.is_large_list(array.type): + items = _returned(array.flatten(), small) + offsets = array.offsets + offsets = pa.array(offsets.to_numpy() - offsets.to_numpy()[0], pa.int64()) + target = (pa.list_ if small else pa.large_list)(pa.field("element", items.type)) + cls: Any = pa.ListArray if small else pa.LargeListArray + return cls.from_arrays( + offsets.cast(pa.int32() if small else pa.int64()), + items, + type=target, + mask=mask, + ) + if small and t.is_large_string(array.type): + return array.cast(pa.string()) + if small and t.is_large_binary(array.type): + return array.cast(pa.binary()) + return array + + +def as_spiral_returns(rows: pa.Table, seed: int = 0, small: bool = False) -> pa.Table: + """Encoded rows as a scan gives them: a set of rows, columns sorted by name.""" + rng = random.Random(seed) + order = list(range(rows.num_rows)) + rng.shuffle(order) + columns: dict[str, Any] = {} + for name in sorted(rows.column_names): + whole = rows.column(name).combine_chunks().take(pa.array(order, pa.int64())) + cut = rng.randint(0, len(whole)) + pieces = [_returned(p, small) for p in (whole[:cut], whole[cut:])] + columns[name] = chunked(pieces, type=pieces[0].type) + return pa.table(columns) + + +def by_id(rows: pa.Table) -> pa.Table: + """Rows sorted by key: a store is a set of rows.""" + keys = rows.column(KEY).to_pylist() + return rows.take( + pa.array(sorted(range(len(keys)), key=lambda i: keys[i]), pa.int64()) + ) + + +PATH = ("run", "fn", "pdb_v1") + + +def new(schema: pa.Schema, path: tuple[str, ...] = PATH) -> store.StoreManifest: + """A manifest of a table of ``schema`` at ``path``, in memory (not serialized).""" + return store.new_manifest(path, "function_pipeline", schema) + + +def entries(schema: pa.Schema, path: tuple[str, ...] = PATH) -> bytes: + """The recorded manifest of a table of ``schema`` at ``path``.""" + return store.manifest_bytes(new(schema, path)) + + +def read(recorded: bytes, path: tuple[str, ...] = PATH) -> store.StoreManifest: + """Parse a raw manifest payload (``manifest_bytes``), not a table's metadata.""" + return store.read_manifest_bytes(recorded, path) + + +def decode(rows: pa.Table, schema: pa.Schema) -> pa.Table: + """Decode through a manifest read back, giving ``schema`` (live types kept).""" + return store.decode_rows(rows, read(entries(schema)), large(schema)) + + +def large_type(arrow_type: Any) -> Any: + """An Arrow type in its large variants, at every depth (no other change).""" + return normalize_to_large_types(arrow_type, keep_null=True) + + +def large(schema: pa.Schema) -> pa.Schema: + """A schema with every field's type in its large variants, metadata kept.""" + return schema_of( + [f.with_type(normalize_to_large_types(f.type, keep_null=True)) for f in schema], + metadata=cast(Any, schema.metadata), + ) + + +def assert_same(got: pa.Table, expected: pa.Table) -> None: + """Schema exactly (every depth); values bit for bit, as sets of rows.""" + assert got.schema.names == expected.schema.names + assert got.schema.metadata == expected.schema.metadata + for a, b in zip(expected.schema, got.schema): + assert field_difference(a, b, a.name) is None + got, expected = by_id(got), by_id(expected) + for name in expected.column_names: + left, right = got.column(name), expected.column(name) + assert same_values(left.combine_chunks(), right.combine_chunks()), name + got.validate() + + +def _storage_form(schema: pa.Schema) -> pa.Schema: + """What a read gives without making logical types live, derived from the input, + never by the codec: large variants, every field's metadata kept at every depth, and + a top-level logical type as its storage type with its identifier as metadata.""" + fields: list[Any] = [] + for field in schema: + arrow_type = field.type + metadata = dict(field.metadata or {}) + if isinstance(arrow_type, pa.BaseExtensionType): + metadata[NAME_KEY] = arrow_type.extension_name.encode() + metadata[METADATA_KEY] = cast(Any, arrow_type).__arrow_ext_serialize__() + arrow_type = arrow_type.storage_type + elif NAME_KEY in metadata: + metadata.setdefault(METADATA_KEY, b"") + fields.append( + pa.field( + field.name, + large_type(arrow_type), + field.nullable, + cast(Any, metadata or None), + ) + ) + return schema_of(fields, metadata=cast(Any, schema.metadata)) + + +def round_trip(rows: pa.Table, *, live: bool = False) -> pa.Table: + """Write, return as SpiralDB does, and restore through the manifest: every slice, + both variants.""" + expected_schema = large(rows.schema) + manifest = read(entries(rows.schema)) + schema = manifest.schema + if live: + converter = get_default_context().type_converter + schema = declaration_form_schema(schema, converter) + else: + expected_schema = _storage_form(rows.schema) + result = None + assert rows.num_rows + for piece in (rows, rows.slice(1), rows.slice(0, 1)): + if not piece.num_rows: + continue + encoded = store.encode_rows(piece) + assert encoded.schema.equals( + store.physical_schema(rows.schema), check_metadata=True + ) + _assert_physical(encoded.schema) + encoded.validate() # full: pyarrow refuses a date64 off midnight + for seed, small in ((1, False), (2, True)): + got = store.decode_rows( + as_spiral_returns(encoded, seed, small), manifest, schema + ) + want = pa.Table.from_arrays( + [ + chunked([_as_target(c, f) for c in col.chunks], type=f.type) + for col, f in zip(piece.columns, expected_schema) + ], + schema=expected_schema, + ) + assert_same(got, want) + result = result or got + assert result is not None + return result + + +def _as_target(chunk: Any, field: Any) -> Any: + """What was written, under the expected field (its storage, its large variants).""" + if chunk.type == field.type: + return chunk + if isinstance(chunk, pa.ExtensionArray): + chunk = chunk.storage + return chunk if chunk.type == field.type else chunk.cast(field.type) + + +def _assert_physical(schema: pa.Schema) -> None: + """SpiralDB's known rules on names and types, at every depth.""" + + def walk(field: Any, named: bool, in_map: bool = False) -> None: + assert (field.nullable or in_map) and not field.metadata + if named and field.name != KEY: + assert field.name and not field.name.startswith(("__", "$")) + assert not set(field.name) & set(".$*\0") + t = field.type + assert not ( + pa.types.is_fixed_size_binary(t) + or pa.types.is_duration(t) + or pa.types.is_interval(t) + or isinstance(t, pa.BaseExtensionType) + # spiral-sdk 0.16.78: a time of day outside one day is refused, so times are + # written as integers; timestamps, zoned or not, are written as they are. + or pa.types.is_time(t) + ) + if pa.types.is_map(t): + walk(t.key_field, False, in_map=True) + walk(t.item_field, False) + return + for i in range(t.num_fields): + walk(t.field(i), pa.types.is_struct(t)) + + for f in schema: + walk(f, True) + + +def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: + with pytest.raises(store.UnstorableInSpiralError) as info: + _ = store.encode_rows(rows) + for word in words: + assert word in str(info.value) + return info.value + + +# --------------------------------------------------------------------------- names + + +@pytest.mark.parametrize( + ("name", "stored"), + [ + ("x", "x"), + ("_source_x", "_source_x"), + ("_tag_source_id::ab", "_tag_source_id::ab"), + ("a;b", "a;b"), + ("é", "é"), + ("a b", "a b"), + ("__data_context", "ox___data_context"), + ("a.b", "ox_a;2Eb"), + ("a;2Eb", "a;2Eb"), + ("ox_a;2Eb", "ox_ox_a;3B2Eb"), + ("ox_", "ox_ox_"), + ("", "ox_"), + ("$a*\x00\x7f\n", "ox_;24a;2A;00;7F;0A"), + ], +) +def test_the_names_of_the_design(name: str, stored: str) -> None: + assert store.encode_name(name) == stored + assert decoded(stored) == name + + +def decoded(stored: str) -> str: + """The inverse of ``encode_name``, which only the tests need.""" + if not stored.startswith("ox_"): + return stored + return re.sub(";([0-9A-F]{2})", lambda m: chr(int(m[1], 16)), stored[3:]) + + +def adversarial_names(count: int) -> set[str]: + rng = random.Random(1446) + pieces = ( + ["_", "__", "ox_", "ox", ".", ";", ";2E", ";3B", ";2e", ";G", "$", "*", "%2E"] + + ["a", "B", "é", "é", "::", " ", "\n", "\x00", "\x7f", "\x80", "{", '"'] + + ["x_", "o", "\U0001f600", "
", "2E", "3B"] + ) + names = {"", KEY, "ox_", "a.b", "a;2Eb", "ox_a;2Eb", "ox_order", "Å", "Å"} + names |= {chr(i) for i in range(0x300)} | {f"a{chr(i)}b" for i in range(0x300)} + while len(names) < count: + names.add("".join(rng.choices(pieces, k=rng.randint(0, 8)))) + return names + + +def test_names_round_trip_and_are_injective() -> None: + names = adversarial_names(210_000) + assert len(names) >= 200_000 + encoded = {name: store.encode_name(name) for name in names} + assert len(set(encoded.values())) == len(names) + for name, stored in encoded.items(): + assert decoded(stored) == name + assert stored and not stored.startswith("__") + assert not any(c in ".$*\x7f" or ord(c) < 32 for c in stored) + + +def test_an_already_stored_name_is_itself_encoded_injectively() -> None: + names = sorted(adversarial_names(5_000)) + once = [store.encode_name(n) for n in names] + twice = [store.encode_name(n) for n in once] + assert len(set(twice)) == len(names) + assert [decoded(decoded(t)) for t in twice] == names + + +@pytest.mark.parametrize( + "names", [["a.b", "a;2Eb", "ox_a;2Eb", "__a"], ["", "ox_", "$"]] +) +@pytest.mark.parametrize("depth", [0, 1, 2, 3]) +def test_names_in_rows_at_every_depth(names: list[str], depth: int) -> None: + for order in (names, list(reversed(names))): + columns = {n: pa.array([i, i + 1], pa.int64()) for i, n in enumerate(order)} + arrays, fields = ( + list(columns.values()), + [pa.field(n, pa.int64()) for n in order], + ) + for level in range(depth): + inner = pa.StructArray.from_arrays(arrays, fields=fields) + if level % 2: + inner = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2], pa.int64()), inner + ) + arrays = [inner, pa.array([5, 6])] + fields = [pa.field("s.t", inner.type), pa.field("__z", pa.int64())] + _ = round_trip(keyed({f.name: a for f, a in zip(fields, arrays)}, fields)) + + +@pytest.mark.parametrize("nested", [False, True]) +def test_a_stored_name_never_matches_a_logical_name(nested: bool) -> None: + """``E("a.b")`` is ``ox_a;2Eb``, which is also another column's own name.""" + values = {"a.b": 1, "ox_a;2Eb": 2, "__record": 3, "ox___record": 4} + for order in (list(values), list(reversed(values))): + if nested: + ty = pa.struct([(n, pa.int64()) for n in order]) + table = keyed({"s": pa.array([values], ty)}) + assert round_trip(table).column("s").to_pylist() == [values] + else: + got = round_trip(keyed({n: pa.array([values[n]]) for n in order})) + assert {n: got.column(n)[0].as_py() for n in values} == values + + +def test_the_key_is_not_a_value_column_of_the_same_name() -> None: + inner = pa.array([{KEY: 7}], pa.struct([(KEY, pa.int64())])) + table = keyed({"ox_" + KEY: pa.array([1]), "s": inner}) + got = round_trip(table) + assert got.column(KEY).to_pylist() == ids(1).to_pylist() + assert got.column("ox_" + KEY).to_pylist() == [1] + encoded = store.encode_rows(table) + renamed = encoded.rename_columns( + ["ox_" + KEY if n == KEY else n for n in encoded.column_names] + ) + with pytest.raises(store.StoredRowsError, match="missing"): + _ = decode(renamed, table.schema) + + +@pytest.mark.parametrize("name", ["\ud800", "a\udfff", "__\ud800.b"]) +def test_a_lone_surrogate_is_refused(name: str) -> None: + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + _ = store.encode_name(name) + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + _ = new(schema_of([("a", pa.int8()), (KEY, pa.large_binary())]), (name,)) + + +def test_a_name_that_is_not_utf8_is_refused_at_every_depth() -> None: + bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) + for field in ( + bad, + pa.field("s", pa.struct([bad])), + pa.field("l", pa.list_(pa.struct([bad]))), + pa.field("i", pa.list_(bad)), + ): + with pytest.raises(store.UnstorableInSpiralError, match="UTF-8"): + _ = store.logical_schema(schema_of([field, (KEY, pa.large_binary())])) + + +def wrappings(inner: Any) -> list[Any]: + """``inner`` alone, below each kind of nesting, and as a logical type's storage.""" + return [ + inner, + pa.list_(inner), + pa.struct([("s", pa.large_list(inner))]), + Labelled(inner, "test.storage", b""), + Labelled(pa.large_list(inner), "test.storage", b""), + ] + + +def test_duplicate_sibling_names_are_refused_at_every_depth() -> None: + twice = pa.struct([("a.b", pa.int8()), ("c", pa.int8()), ("a.b", pa.int8())]) + for ty in wrappings(twice): + with pytest.raises(store.UnstorableInSpiralError, match="more than once"): + _ = store.logical_schema(schema_of([("x", ty), (KEY, pa.large_binary())])) + same_in_two_structs = pa.struct([("a", pa.struct([("a", pa.int8())]))]) + _ = store.logical_schema( + schema_of([("a", same_in_two_structs), (KEY, pa.large_binary())]) + ) + + +def test_names_that_differ_only_in_case_or_normal_form_are_kept_apart() -> None: + """The service folds neither (measured live).""" + names = ["A", "a", "a.B", "a.b", "__A", "__a", "\u00e9", "e\u0301", "a.\u00e9"] + for order in (names, list(reversed(names))): + inner = pa.array( + [{n: i for i, n in enumerate(order)}], + pa.struct([(n, pa.int8()) for n in order]), + ) + columns = {n: pa.array([i]) for i, n in enumerate(order)} + _ = round_trip(keyed({**columns, "s": inner})) + + +@pytest.mark.parametrize("as_storage", [False, True]) +def test_a_struct_parent_must_be_valid_also_in_a_logical_types_storage( + as_storage: bool, +) -> None: + struct = pa.struct([pa.field("a.b", pa.int8(), False)]) + for ty, value in ((struct, None), (pa.large_list(struct), [{"a.b": 1}, None])): + array = pa.array([value], ty) + if as_storage: + live = Labelled(ty, "test.parent", b"") + array = pa.ExtensionArray.from_storage(live, array) + _ = refused(keyed({"c": array}), "'c'", "null struct") + + +# --------------------------------------------------------------------------- types + +REFUSED_ROWS = { + "struct<> (no fields)": "no fields", + "fixed_size_binary[4]": "fixed-size binary", + "uuid (Arrow's canonical extension type)": "fixed-size binary", + "map, keys sorted": "named key and value", + "map (item metadata)": "metadata inside a map", + "map (key metadata)": "metadata inside a map", + "map> (metadata inside the item)": "metadata inside a map", + **{r.label: "duration" for r in ROWS if r.label.startswith("duration")}, + # A live logical type below the top level (ITL-1372's rows): Orcapod never builds + # one, and the codec records a logical type only on a whole column. + "extension type in struct child": "logical type nested", + "extension type in list item": "logical type nested", + "extension type in map value": "logical type nested", + # A dictionary is an encoding, refused before its values' type is looked at. + "extension type in dictionary values": "no type dictionary", +} +# The matrix's second column holds a null row. +NULL_STRUCT_ROWS = { + "struct", + "struct[2]>", + "struct", + "user class, exact (dataclass)", + "user class, structural (orcapod.dataclass)", +} + + +def test_the_expectations_name_rows_of_the_matrix() -> None: + assert set(REFUSED_ROWS) | NULL_STRUCT_ROWS <= {r.label for r in ROWS} + + +@pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") +@pytest.mark.parametrize("row", ROWS, ids=lambda r: r.label) +def test_every_row_of_the_type_matrix_is_kept_or_refused( + row: Row, tmp_path: Path +) -> None: + """Two columns of each type (the second nullable, with a null), both forms of a + logical type, and the column naming its refusal.""" + if row.label.startswith("torch"): + _ = pytest.importorskip("torch") + rows = build_table(row, tmp_path).rename_columns([KEY, "x", "y"]) + if row.label in REFUSED_ROWS: + _ = refused(rows, REFUSED_ROWS[row.label], "'x'") + return + if row.label in NULL_STRUCT_ROWS: + _ = refused(rows, "null struct", "'y'") + rows = rows.drop_columns(["y"]) + _ = round_trip(rows) + _ = round_trip(rows, live=True) + + +def scalar_cases() -> list[tuple[str, pa.DataType, list[Any]]]: + D = decimal.Decimal + return [ + ("int8", pa.int8(), [-128, 127, 0]), + ("uint64", pa.uint64(), [0, 2**64 - 1, 2**63]), + ("int64", pa.int64(), [-(2**63), 2**63 - 1, 0]), + ("bool", pa.bool_(), [True, False, True]), + ("float32", pa.float32(), [1.5, 0.0, -3.25]), + ("float64", pa.float64(), [0.1, math.inf, 5e-324]), + ("float16", pa.float16(), [0.5, -0.0, math.nan]), + ("decimal128", pa.decimal128(38, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("decimal256", pa.decimal256(70, 4), [D("1.2500"), D("-9.0001"), D("0")]), + ("date64", pa.date64(), [-(2**63), 1, 2**63 - 1]), + ("decimal32", pa.decimal32(9, 2), [D("1.25"), D("-9999999.99"), D("0")]), + ( + "decimal64", + pa.decimal64(18, 2), + [D("1.25"), D("-9999999999999999.99"), D("0")], + ), + ("null", pa.null(), [None, None, None]), + ("time32_s", pa.time32("s"), [0, 86_399, 1]), + ("time32_ms", pa.time32("ms"), [0, 86_399_999, 1]), + ("time64_us", pa.time64("us"), [0, 86_400 * 10**6 - 1, 1]), + ("time64_ns", pa.time64("ns"), [0, 86_400 * 10**9 - 1, 1]), + ( + "date32", + pa.date32(), + [dt.date(1, 1, 1), dt.date(9999, 12, 31), dt.date(1970, 1, 1)], + ), + ("large_string", pa.large_string(), ["", "é\x00", "x" * 100]), + ("string", pa.string(), ["", "é\x00", "y"]), + ("binary", pa.binary(), [b"", b"\x00\xff", b"a"]), + *( + (f"ts_{u}_{z}", timestamp(u, tz=z), [-1, 0, 2**40 + 1]) + for u in ("s", "ms", "us", "ns") + for z in (None, "UTC", "Asia/Kathmandu", "-03:30") + ), + ] + + +@pytest.mark.parametrize("case", scalar_cases(), ids=lambda c: c[0]) +@pytest.mark.parametrize("nullable", [True, False]) +def test_every_type_at_every_nesting_depth( + case: tuple[str, pa.DataType, list[Any]], nullable: bool +) -> None: + """Each kept type alone and below lists, fixed-size lists, structs and their + combinations, in several columns at once, in two column orders.""" + _, arrow_type, values = case + nullable = nullable or pa.types.is_null(arrow_type) + if nullable: + values = [*values, None] + else: + values = [*values, values[0]] + leaf = pa.field("v.1", arrow_type, nullable, {"unit": "m"}) + item = leaf.with_name("odd item") + plain_item = item.remove_metadata() + v, n = values, len(values) + shapes: dict[str, tuple[pa.DataType, list[Any]]] = { + "plain": (arrow_type, v), + "list": (pa.list_(item), [v, [], None, v[:1]]), + "large": (pa.large_list(item), [None, v[:2], v, []]), + "fixed": (pa.list_(item, 2), [v[:2], None, v[2:], v[1:3]]), + "fixed_fixed": ( + pa.list_(pa.list_(item, 1), 2), + [[v[:1], None], None, [v[1:2], v[2:3]], [v[:1], v[:1]]], + ), + "fixed0": (pa.list_(item, 0), [[], None, [], []]), + "list_fixed": (pa.list_(pa.list_(item, 1)), [[v[:1], None], [], None, [v[3:]]]), + "map": ( + map_of(pa.string(), item.with_name("value").remove_metadata()), + [[("b", v[0]), ("a", v[1])], None, [], [("", x) for x in v]], + ), + "map_sorted_list": ( + map_of(pa.binary(), pa.list_(plain_item), keys_sorted=True), + [None, [(b"a", v), (b"b", None)], [(b"", [])], []], + ), + "list_map": ( + pa.list_(map_of(pa.int16(), plain_item.with_name("value"))), + [[[(1, v[0])], None, []], None, [], [[(2, x)] for x in v]], + ), + "map_struct": ( + map_of( + pa.string(), + pa.struct( + [pa.field("z", pa.int8()), pa.field("a.b", arrow_type, nullable)] + ), + ), + [ + None, + [("k", {"z": 1, "a.b": v[0]})], + [], + [("", {"z": None, "a.b": v[1]})], + ], + ), + "fixed_struct": ( + pa.list_(pa.struct([pa.field("z", pa.int8()), leaf]), 1), + [[{"z": 1, "v.1": x}] for x in v], + ), + "struct": ( + pa.struct([leaf, pa.field("__b", pa.int8())]), + [{"v.1": x, "__b": i} for i, x in enumerate(v)], + ), + "struct_list": ( + pa.struct([pa.field("z", pa.list_(item)), pa.field("a", pa.int8())]), + [{"z": x, "a": 1} for x in ([], v, None, v[:1])], + ), + "list_struct": ( + pa.list_(pa.field("i", pa.struct([pa.field("z", pa.int8()), leaf]))), + [[{"z": 1, "v.1": v[0]}], None, [], [{"z": None, "v.1": x} for x in v]], + ), + "list_list": (pa.list_(pa.list_(item)), [[v, [], None], [], None, [v[:1]]]), + "deep": ( + pa.list_( + pa.struct([pa.field("s", pa.struct([pa.field("l", pa.list_(item))]))]) + ), + [[{"s": {"l": v}}, {"s": {"l": None}}], [], None, [{"s": {"l": []}}]], + ), + } + if not nullable or pa.types.is_null(arrow_type): + # pyarrow cannot cast a null fixed-size list over non-null items, or a sliced + # list of structs with a null-typed field, so the test + # could not state what it expects of the small variants. + shapes = {k: (large_type(t), rows) for k, (t, rows) in shapes.items()} + columns = {k: pa.array(rows, t) for k, (t, rows) in shapes.items()} + assert all(len(c) == n for c in columns.values()) + fields = [ + pa.field(k, c.type, nullable if k == "plain" else True, {"k": k}) + for k, c in columns.items() + ] + table = keyed(columns, fields) + _ = round_trip(table) + _ = round_trip(table.select(list(reversed(table.column_names)))) + + +@pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) +@pytest.mark.parametrize( + "zone", [None, "UTC", "Europe/Berlin", "Asia/Kathmandu", "+05:45", "-03:30"] +) +def test_zone_aware_timestamps_are_exact(unit: str, zone: str) -> None: + """Extremes of the integer, the far past and sub-second ticks.""" + ticks = [-(2**63), 2**63 - 1, -(2**63) + 1, 0, -1, 1, -(10**15) - 7, 10**15 + 3] + ticks += [-62135596800 * {"s": 1, "ms": 10**3, "us": 10**6, "ns": 1}[unit] - 1] + values = [*ticks, None] + ts = timestamp(unit, tz=zone) + plain: Any = pa.array(values, pa.int64()).cast(ts) + columns = { + "t": plain, + "l": pa.array([[x, None] for x in values], pa.list_(pa.int64())).cast( + pa.list_(ts) + ), + "s": pa.StructArray.from_arrays([plain], fields=[pa.field("t", ts)]), + } + got = by_id(round_trip(keyed(columns))) + assert got.column("t").cast(pa.int64()).to_pylist() == values + assert got.schema.field("t").type == ts + encoded = store.encode_rows(keyed(columns)) + # Written as they are (measured live with spiral-sdk 0.16.78: every int64, every + # unit, zoned or not, bit for bit). + assert encoded.schema.field("t").type == ts + assert encoded.column("t").cast(pa.int64()).to_pylist() == values + + +def _float(bits: int, width: int) -> Any: + ints = np.array([bits], dtype=f"u{width // 8}") + return pa.array(ints).view(pa.float32() if width == 32 else pa.float64()) + + +FLOATS = { + 32: [0, 0x80000000, 1, 0x80000001, 0x7F800000, 0xFF800000, 0x7FC00000, 0x7F7FFFFF] + + [0x7FC00001, 0xFFC00000, 0x7F800001, 0xFF800001, 0x7FFFFFFF], + 64: [0, 1 << 63, 1, (1 << 63) + 1, 0x7FF << 52, 0xFFF << 52, 0x7FF8 << 48] + + [(0x7FF8 << 48) + 1, 0xFFF8 << 48, (0x7FF << 52) + 1, (1 << 63) - 1], +} + + +@pytest.mark.parametrize("width", [16, 32, 64]) +@pytest.mark.parametrize("nested", ["plain", "list", "fixed", "struct"]) +def test_float_bits_are_kept(width: int, nested: str) -> None: + """Negative zero and every NaN payload, signalling ones included, bit for bit.""" + if width == 16: # every float16 there is + array: Any = pa.array(np.arange(2**16, dtype=np.uint16)).view(pa.float16()) + else: + array = pa.concat_arrays([_float(b, width) for b in FLOATS[width]]) + if nested == "list": + array = pa.ListArray.from_arrays( + pa.array(range(len(array) + 1), pa.int32()), array + ) + elif nested == "fixed": + array = pa.FixedSizeListArray.from_arrays(array, 1) + elif nested == "struct": + array = pa.StructArray.from_arrays([array], names=["f"]) + _ = round_trip(keyed({"f": array})) + + +def test_datetime_max_and_min_are_kept() -> None: + """pyspiral's service refused a timestamp after 9999-12-30; spiral-sdk's keeps it.""" + utc = dt.timezone.utc + values = [ + dt.datetime.max, + dt.datetime.min, + dt.datetime(9999, 12, 30, 22, 0, 1), + None, + ] + table = keyed( + { + "naive": pa.array(values, timestamp("us")), + "utc": pa.array( + [v and v.replace(tzinfo=utc) for v in values], timestamp("us", tz="UTC") + ), + } + ) + got = by_id(round_trip(table)) + assert got.column("naive").to_pylist() == values + + +@pytest.mark.parametrize("arrow_type", [pa.time32("s"), pa.time32("ms")], ids=str) +def test_every_time32_is_kept(arrow_type: Any) -> None: + """Also one outside a day, which the service refuses as a time.""" + ticks = [0, 86_399, 86_400, 86_400_000, -1, -(2**31), 2**31 - 1, None] + array: Any = pa.array(ticks, pa.int32()).view(arrow_type) + got: Any = by_id(round_trip(keyed({"t": array}))) + assert got.column("t").combine_chunks().view(pa.int32()).to_pylist() == ticks + + +@pytest.mark.parametrize("arrow_type", [pa.time64("us"), pa.time64("ns")], ids=str) +@pytest.mark.parametrize("nested", ["plain", "list", "fixed", "struct", "map"]) +def test_every_time64_is_kept(arrow_type: Any, nested: str) -> None: + ticks = [0, 86_400 * 10**6, 86_400 * 10**9, -1, -(2**63), 2**63 - 1] + array: Any = pa.array(ticks, pa.int64()).view(arrow_type) + offsets: Any = pa.array(range(len(ticks) + 1), pa.int32()) + if nested == "list": + array = pa.ListArray.from_arrays(offsets, array) + elif nested == "fixed": + array = pa.FixedSizeListArray.from_arrays(array, 2) + elif nested == "struct": + array = pa.StructArray.from_arrays([array], names=["t"]) + elif nested == "map": + array = pa.MapArray.from_arrays(offsets, pa.array(list("abcdef")), array) + _ = round_trip(keyed({"t": array})) + + +def test_what_a_null_list_or_map_hides_is_not_written() -> None: + raw = pa.array([-1, 5], pa.int64()).view(pa.time64("us")) + offsets: Any = pa.array([0, 1, 2], pa.int32()) + mask = pa.array([True, False]) + lists = pa.ListArray.from_arrays(offsets, raw, mask=mask) + maps = pa.MapArray.from_arrays(offsets, pa.array(["hidden", "b"]), raw, mask=mask) + table = keyed({"l": lists, "m": maps}) + _ = round_trip(table) + encoded: Any = store.encode_rows(table) + assert len(encoded.column("l").chunk(0).values) == 1 + assert encoded.column("m").chunk(0).keys.to_pylist() == ["b"] + + +def test_no_rows_are_never_written() -> None: + _ = refused(keyed({"a": pa.array([1])}).slice(1), "no rows") + + +@pytest.mark.parametrize( + "make", + [ + lambda: pa.array([None, {"a": 1}], pa.struct([("a", pa.int8())])), + lambda: pa.array( + [[{"a": 1}, None], []], pa.list_(pa.struct([("a", pa.int8())])) + ), + lambda: pa.array( + [{"s": None}, {"s": {"a": 1}}], + pa.struct([("s", pa.struct([("a", pa.int8())]))]), + ), + ], +) +def test_a_null_struct_at_any_depth_is_refused(make: Any) -> None: + _ = refused(keyed({"ok": pa.array([1, 2]), "bad": make()}), "'bad'", "null") + + +def test_a_null_struct_hidden_by_a_null_list_is_not_written() -> None: + items = pa.array([None, {"a": 1}], pa.struct([("a", pa.int8())])) + lists = pa.ListArray.from_arrays( + pa.array([0, 1, 2], pa.int32()), items, mask=pa.array([True, False]) + ) + _ = round_trip(keyed({"l": lists})) + + +def test_a_null_under_a_non_null_field_is_refused_at_any_depth() -> None: + not_null: Any = pa.field("v", pa.int64(), nullable=False) + for arrow_type, value in ( + (pa.list_(not_null), [[1, None]]), + (pa.struct([not_null]), [{"v": None}]), + (pa.list_(pa.struct([not_null])), [[{"v": 1}, {"v": None}]]), + ): + table = keyed({"x": pa.array(value, arrow_type)}) + error = refused(table, "'x'", "non-nullable") + assert error.path[0] == "x" and len(error.path) > 1 + _ = refused( + keyed( + {"x": pa.array([None], pa.int8())}, + [not_null.with_name("x").with_type(pa.int8())], + ), + "'x'", + ) + + +def test_a_null_list_over_non_null_items_is_kept() -> None: + item = pa.field("item", pa.int64(), nullable=False) + _ = round_trip(keyed({"b": pa.array([[1], None, []], pa.list_(item))})) + + +@pytest.mark.parametrize( + "arrow_type", + [ + pa.string_view(), + pa.binary_view(), + pa.binary(4), + pa.duration("us"), + pa.month_day_nano_interval(), + pa.dictionary(pa.int32(), pa.string()), + pa.run_end_encoded(pa.int32(), pa.string()), + pa.list_view(pa.int64()), + pa.large_list_view(pa.int64()), + map_of(pa.field("k", pa.string(), False), pa.field("v", pa.int8())), + pa.sparse_union([pa.field("a", pa.int8())]), + pa.struct([]), + map_of(pa.string(), pa.field("value", pa.int8(), metadata={"k": "v"})), + map_of(pa.string(), pa.list_(pa.field("i", pa.int8(), metadata={"k": "v"}))), + ], + ids=str, +) +def test_a_type_the_store_does_not_keep_is_refused_at_every_depth( + arrow_type: pa.DataType, +) -> None: + for wrapped in ( + arrow_type, + pa.list_(arrow_type), + pa.struct([("ok", pa.int8()), ("s", arrow_type)]), + pa.list_(pa.struct([("s", pa.large_list(arrow_type))])), + ): + schema = schema_of( + [("a", pa.int64()), ("bad", wrapped), (KEY, pa.large_binary())] + ) + for call in (store.physical_schema, store.logical_schema, entries): + with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): + _ = call(schema) + + +def test_every_refusal_is_in_one_table() -> None: + assert [r.what for r in store.REFUSALS] == [ + "a null struct", + "a struct with no fields", + "a write of no rows", + "a map whose fields are not named key and value", + "field metadata inside a map", + "a string view or binary view", + "a fixed-size binary", + "a duration", + "an interval", + ] + assert all(r.why for r in store.REFUSALS) + + +def test_lifting_a_type_is_one_entry(monkeypatch: pytest.MonkeyPatch) -> None: + """A type shown to be kept natively moves from one table to the other.""" + matches = pa.types.is_duration + table = keyed({"d": pa.array([1, None, -2], duration("us"))}) + _ = refused(table, "duration", "refuses") + monkeypatch.setattr( + store, + "REFUSALS", + tuple(r for r in store.REFUSALS if r.matches is not matches), + ) + _ = refused(table, "keeps no type duration") + monkeypatch.setattr(store, "_NATIVE", (*store._NATIVE, matches)) # pyright: ignore[reportPrivateUsage] + encoded = store.encode_rows(table) + assert_same(decode(as_spiral_returns(encoded), table.schema), table) + + +def test_a_null_fixed_size_list_of_structs_is_kept() -> None: + """Measured live with spiral-sdk 0.16.78: the null row's struct slots are accepted.""" + struct = pa.struct([("a", pa.int8())]) + for ty, value in ( + (pa.list_(struct, 1), [[{"a": 1}], None]), + (pa.list_(pa.list_(struct, 1), 1), [[[{"a": 1}]], None]), + ): + rows = keyed({"f": pa.array(value, ty)}) + assert by_id(round_trip(rows)).column("f").to_pylist() == value + + +@pytest.mark.parametrize("nullable", [True, False]) +def test_a_null_key_is_refused_whatever_the_schema_says(nullable: bool) -> None: + key = pa.array([b"a", None], pa.large_binary()) + schema = schema_of([pa.field(KEY, pa.large_binary(), nullable), ("a", pa.int8())]) + column = pa.array([1, 2], pa.int8()) + _ = refused(pa.Table.from_arrays([key, column], schema=schema), KEY) + with pytest.raises(store.StoredRowsError, match="null key"): + _ = decode(pa.table({KEY: key, "a": column}), schema) + + +@pytest.mark.parametrize( + ("fields", "words"), + [ + ([("a", pa.int8())], "key column"), + ([(KEY, pa.large_binary())], "no column beside"), + ([(KEY, pa.int64()), ("a", pa.int8())], "must be binary"), + ([(KEY, pa.binary()), ("a", pa.int8()), ("a", pa.int8())], "more than once"), + ([(KEY, pa.binary()), (KEY, pa.binary()), ("a", pa.int8())], "key column"), + ( + [ + (KEY, pa.binary()), + ("a", pa.struct([("x", pa.int8()), ("x", pa.int8())])), + ], + "'a'", + ), + ], +) +def test_a_table_the_store_cannot_hold_is_refused(fields: Any, words: str) -> None: + with pytest.raises(store.UnstorableInSpiralError, match=words): + _ = store.physical_schema(schema_of(fields)) + + +# ------------------------------------------------------------------- logical types + + +_ALIVE: list[Any] = [] +"""Arrow asks the class to read a type whose Python object is gone: keep them all.""" + + +class Labelled(pa.ExtensionType): + """An extension type registered or not, whose reading may fail.""" + + def __init__(self, storage: Any, name: str, metadata: bytes) -> None: + self._metadata = metadata + _ALIVE.append(self) + super().__init__(storage, name) + + def __arrow_ext_serialize__(self) -> bytes: + return self._metadata + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + raise AssertionError("the codec reads identifiers, never registered types") + + +@pytest.mark.parametrize("metadata", [b"", b'{"version":1}', b"\xff\x00\xfe"]) +@pytest.mark.parametrize("registered", [False, True]) +def test_a_logical_type_is_kept_by_its_identifier( + metadata: bytes, registered: bool +) -> None: + """Live and annotated give one schema; a registered type is never consulted.""" + storage = pa.struct( + [pa.field("z.1", timestamp("us", tz="UTC")), ("a", pa.binary())] + ) + name = f"test.itl1446.{metadata.hex()}" + live = Labelled(storage, name, metadata) + values = [{"z.1": dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc), "a": b"xy"}] * 2 + stored = pa.array(values, storage) + annotated = pa.field( + "c", + storage, + True, + {NAME_KEY: name.encode(), METADATA_KEY: metadata, b"k": b"v"}, + ) # pyright: ignore[reportArgumentType] + if registered: + pa.register_extension_type(cast(Any, live)) + try: + one = keyed( + {"c": pa.ExtensionArray.from_storage(live, stored), "d": pa.array([1, 2])}, + [pa.field("c", live, True, {"k": "v"}), pa.field("d", pa.int64())], + ) + two = keyed( + {"c": stored, "d": pa.array([1, 2])}, [annotated, pa.field("d", pa.int64())] + ) + assert store.encode_rows(one).equals(store.encode_rows(two)) + assert_same(round_trip(one), round_trip(two)) + schema = read(entries(one.schema)).schema + assert schema.field("c").metadata == annotated.metadata + assert pa.types.is_struct(schema.field("c").type) + back = decode(as_spiral_returns(store.encode_rows(one)), one.schema) + assert by_id(back).column("c").chunk(0).type == live + finally: + if registered: + pa.unregister_extension_type(name) + + +def test_another_identifier_is_another_schema() -> None: + def schema(name: str, metadata: bytes) -> pa.Schema: + live = Labelled(pa.large_string(), name, metadata) + return schema_of([("c", live), (KEY, pa.large_binary())]) + + base = schema("n", b"1") + assert store.schema_difference(base, schema("n", b"1")) is None + for other in (schema("n", b"2"), schema("m", b"1"), schema("n", b"")): + difference = store.schema_difference(base, other) + assert difference is not None and "'c'" in difference + + +def test_a_logical_type_below_a_plain_type_is_refused() -> None: + live = Labelled(pa.int8(), "test.nested", b"") + annotated = pa.field("v", pa.int8(), metadata={NAME_KEY: b"n"}) + inners: Any = (pa.field("v", live), annotated, pa.field("v", pa.uuid())) + for inner in inners: + for arrow_type in ( + pa.list_(inner), + pa.struct([inner]), + pa.list_(pa.struct([inner])), + map_of(pa.string(), inner), + ): + schema = schema_of([("c", arrow_type), (KEY, pa.large_binary())]) + with pytest.raises(store.UnstorableInSpiralError, match="nested"): + _ = store.logical_schema(schema) + # A live type whose field is annotated as another one is two logical types. + both = pa.field("c", live, metadata={NAME_KEY: b"n"}) + with pytest.raises(store.UnstorableInSpiralError, match="nested"): + _ = store.logical_schema(schema_of([both, (KEY, pa.large_binary())])) + + +# ------------------------------------------------------------------- rows, as read + + +def _stored(table: pa.Table) -> pa.Table: + return as_spiral_returns(store.encode_rows(table)) + + +def large_table(table: pa.Table) -> pa.Table: + return table.cast(large(table.schema)) + + +def test_rows_that_are_not_what_was_written_are_refused() -> None: + inner = pa.struct([pa.field("a.b", pa.int8(), False), pa.field("c", pa.int8())]) + fields = [ + pa.field("n", pa.int64(), False), + pa.field("t", timestamp("us", tz="UTC")), + pa.field("s", inner), + pa.field("l", pa.list_(inner)), + pa.field("f", pa.list_(pa.int8(), 2)), + pa.field("m", pa.map_(pa.string(), pa.int8())), + ] + table = keyed( + { + "n": pa.array([1]), + "t": pa.array([1], timestamp("us", tz="UTC")), + "s": pa.array([{"a.b": 1, "c": 2}], inner), + "l": pa.array([[{"a.b": 1, "c": 2}]], pa.list_(inner)), + "f": pa.array([[1, 2]], pa.list_(pa.int8(), 2)), + "m": pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int8())), + }, + fields, + ) + schema, good = table.schema, _stored(table) + manifest = new(schema) + assert_same(decode(good, schema), large_table(table)) + store.require_stored_schema(good.schema, manifest) + + def bad(name: str, array: Any, *words: str, value: bool = False) -> None: + rows = good.set_column(good.column_names.index(name), name, array) + calls: list[Any] = [lambda: decode(rows, schema)] + if not value: + calls.append(lambda: store.require_stored_schema(rows.schema, manifest)) + for call in calls: + with pytest.raises(store.StoredRowsError) as info: + call() + assert all(w in str(info.value) for w in (f"'{name}'", *words)) + + stored = pa.struct([("c", pa.int8()), ("ox_a;2Eb", pa.int8())]) + more = pa.struct([*stored, pa.field("x", pa.int8())]) + raw = pa.struct([("c", pa.int8()), ("a.b", pa.int8())]) + bad("n", pa.array([None], pa.int64()), "null", value=True) + bad("n", pa.array([1], pa.int32()), "int32") + bad("t", pa.array([1], timestamp("us")), "timestamp[us]") + bad("t", pa.array([1], timestamp("us", tz="Europe/Paris")), "Europe/Paris") + bad("t", pa.array([1], timestamp("ms", tz="UTC")), "timestamp[ms") + bad("t", pa.array([1], pa.int64()), "int64") + bad("t", pa.array([1], pa.int32()), "int32") + bad("s", pa.array([{"c": 1}], pa.struct([("c", pa.int8())])), "missing") + bad("s", pa.array([{"c": 1}], more), "not expected ['x']") + bad("s", pa.array([{"c": 1}], raw), "not expected ['a.b']") + bad("s", pa.array([1]), "int64") + bad("s", pa.array([[]], pa.list_(pa.int8())), "list") + bad("s", pa.array([None], stored), "null struct", value=True) + bad("s", pa.array([{"c": 1}], stored), "a.b", "null", value=True) + bad("l", pa.array([[{"c": 1}]], pa.list_(stored)), "a.b", "null", value=True) + bad("l", pa.array([[{"c": 1}]], pa.list_(raw)), "not expected ['a.b']") + bad("l", pa.array([1]), "int64") + bad("f", pa.array([[1, 2, 3]], pa.list_(pa.int8(), 3)), "[3]") + bad("f", pa.array([[1, 2]], pa.list_(pa.int16(), 2)), "int16") + bad("f", pa.array([[1, 2]], pa.list_(pa.int8())), "list") + bad("m", pa.array([[("a", 1)]], pa.map_(pa.string(), pa.int16())), "int16") + bad("m", pa.array([[(b"a", 1)]], pa.map_(pa.binary(), pa.int8())), "binary") + bad("m", pa.array([1]), "int64") + for rows in (good.drop_columns(["n"]), good.append_column("m", pa.array([1]))): + with pytest.raises(store.StoredRowsError, match="'(n|m)'"): + _ = decode(rows, schema) + repeated = pa.Table.from_arrays( + [*good.columns, good.column("n")], names=[*good.column_names, "n"] + ) + with pytest.raises(store.StoredRowsError, match="repeated"): + _ = decode(repeated, schema) + + +def test_rows_are_given_the_recorded_schema_only() -> None: + table = keyed({"a": pa.array([1]), "b": pa.array(["x"])}) + manifest, stored = new(table.schema), _stored(table) + for schema in ( + table.schema.set(0, pa.field("a", pa.int32())), + table.schema.remove(0), + schema_of(list(reversed(list(table.schema)))), + table.schema.set(0, pa.field("a", pa.int64(), metadata={"k": "v"})), + ): + with pytest.raises(store.ManifestError, match="not the recorded schema"): + _ = store.decode_rows(stored, manifest, schema) + + +def test_a_table_with_a_manifest_and_no_rows_reads_as_no_rows() -> None: + schema = wide_schema(20) + rows = store.empty_rows(read(entries(schema))) + assert rows.num_rows == 0 + assert rows.schema.equals(store.logical_schema(schema), check_metadata=True) + + +# ------------------------------------------------------------------------ manifest + + +def wide_schema(columns: int = 200) -> pa.Schema: + """Several tags, data columns and nested ones, each with metadata.""" + fields: list[Any] = [pa.field(KEY, pa.large_binary(), False)] + for i in range(columns - 1): + arrow_type: Any = [ + pa.int64(), + timestamp("ns", tz="Asia/Kathmandu"), + pa.struct([pa.field("__a.b", pa.string(), False, {"depth": "1"})]), + pa.list_(pa.field("odd", pa.binary(), False, {"unit": "m" * 30})), + Labelled(pa.large_string(), f"test.wide.{i}", b'{"version":1}'), + ][i % 5] + metadata = {"orcapod:data_tag": "1", "note": f"{i:040d}", b"\xff": b"\x00\xfe"} + fields.append( + pa.field(f"__col.{i}", arrow_type, i % 3 > 0, cast(Any, metadata)) + ) + return schema_of(fields, metadata={"table": "x" * 100}) + + +def test_a_manifest_of_200_columns_with_metadata() -> None: + schema = wide_schema() + assert len(schema) == 200 + path = ("run", "a", "b", "", "é", '"', "\u2028") + recorded = entries(schema, path) + assert recorded.isascii() + manifest = read(recorded, path) + assert manifest == new(schema, path) + assert manifest.record_path == path + assert manifest.kind == "function_pipeline" + assert manifest.schema.equals(store.logical_schema(schema), check_metadata=True) + for a, b in zip(store.logical_schema(schema), manifest.schema): + assert field_difference(a, b, a.name) is None + + +def test_a_payload_of_another_pyarrow_is_the_same_schema(monkeypatch: Any) -> None: + """Other bytes (field metadata written in another order) decode to one schema.""" + schema = wide_schema(20) + first = entries(schema) + + def reordered(field: Any) -> Any: + t = field.type + if pa.types.is_struct(t): + t = pa.struct([reordered(f) for f in t]) + elif pa.types.is_large_list(t): + t = pa.large_list(reordered(t.value_field)) + metadata = dict(reversed(list((field.metadata or {}).items()))) + return pa.field(field.name, t, field.nullable, cast(Any, metadata or None)) + + original = store.logical_schema + monkeypatch.setattr( + store, + "logical_schema", + lambda s: schema_of([reordered(f) for f in original(s)], metadata=s.metadata), + ) + second = entries(schema) + monkeypatch.undo() + assert first != second + one, two = read(first).schema, read(second).schema + assert list(one.field(1).metadata or {}) != list(two.field(1).metadata or {}) + assert store.schema_difference(one, two) is None + + +def test_every_row_of_the_matrix_round_trips_in_one_manifest(tmp_path: Path) -> None: + fields: list[Any] = [pa.field(KEY, pa.large_binary(), False)] + for row in ROWS: + if row.label in REFUSED_ROWS: + continue + if row.provisional: + continue + for name in ("x", "y"): + fields.append( + build_table(row, tmp_path) + .schema.field(name) + .with_name(f"{row.label}.{name}") + ) + for order in (fields, list(reversed(fields))): + schema = schema_of(order) + got = read(entries(schema)).schema + assert got.names == schema.names + for a, b in zip(store.logical_schema(schema), got): + assert field_difference(a, b, a.name) is None + + +def test_metadata_keys_that_look_like_the_marks_are_kept() -> None: + metadata = { + b"orcapod:key:ARROW:extension:name": b"1", + b"orcapod:key:": b"2", + b"orcapod:key:orcapod:key:x": b"3", + b"ARROW:extension:other": b"4", + NAME_KEY: b"n", + METADATA_KEY: b"m", + } + field = pa.field("a", pa.int8(), metadata=cast(Any, metadata)) + schema = schema_of([field, (KEY, pa.large_binary())]) + assert read(entries(schema)).schema.field("a").metadata == metadata + + +BASE: list[Any] = [ + pa.field("a", pa.struct([pa.field("x", pa.int8()), pa.field("y", pa.int8())])), + pa.field("l", pa.large_list(pa.field("item", timestamp("us", tz="UTC")))), + pa.field("f", pa.large_list(pa.field("item", pa.int8()))), + pa.field(KEY, pa.large_binary(), False), +] +MAPPED: list[Any] = [*BASE, pa.field("x", map_of(pa.string(), pa.int8()))] + + +def test_the_order_of_columns_is_no_difference() -> None: + for order in ([3, 2, 1, 0], [1, 0, 3, 2]): + other = schema_of([BASE[i] for i in order]) + assert store.schema_difference(schema_of(BASE), other) is None + + +@pytest.mark.parametrize( + "changed", + [ + BASE[0].with_name("b"), + BASE[0].with_nullable(False), + BASE[0].with_metadata({"k": "v"}), + BASE[0].with_type(pa.struct([("x", pa.int8()), ("z", pa.int8())])), + BASE[0].with_type(pa.struct([("y", pa.int8()), ("x", pa.int8())])), + BASE[0].with_type(pa.struct([("x", pa.int8())])), + BASE[0].with_type( + pa.struct([pa.field("x", pa.int8(), False), ("y", pa.int8())]) + ), + BASE[0].with_type( + pa.struct([pa.field("x", pa.int8(), metadata={"k": "v"}), ("y", pa.int8())]) + ), + BASE[0].with_type(pa.int8()), + BASE[1].with_type(pa.large_list(pa.field("other", timestamp("us", tz="UTC")))), + BASE[1].with_type(pa.large_list(timestamp("us", tz="Etc/UTC"))), + BASE[1].with_type(pa.large_list(timestamp("us"))), + BASE[1].with_type(pa.large_list(timestamp("ms", tz="UTC"))), + BASE[2].with_type(pa.large_list(pa.int16())), + BASE[2].with_type(pa.list_(pa.int8(), 2)), + pa.field("x", map_of(pa.string(), pa.int8(), keys_sorted=True)), + BASE[2].with_type(pa.large_list(pa.large_list(pa.int8()))), + ], + ids=str, +) +def test_another_schema_is_a_difference(changed: Any) -> None: + index = next((i for i, f in enumerate(MAPPED) if f.name == changed.name), 0) + fields = list(MAPPED) + fields[index] = changed + one, other = read(entries(schema_of(MAPPED))).schema, schema_of(fields) + for a, b in ((one, other), (other, one)): + assert store.schema_difference(a, b) is not None + + +def test_schema_metadata_and_more_columns_are_a_difference() -> None: + schema = schema_of(BASE) + for other in ( + schema.with_metadata({"k": "v"}), + schema_of([*BASE, ("more", pa.int8())]), + ): + assert store.schema_difference(schema, other) is not None + + +def test_a_manifest_of_another_path_is_refused() -> None: + recorded = entries(schema_of(BASE), ("a", "b")) + for path in (("a",), ("b", "a"), ("a", "b", ""), ("a_b",), ()): + with pytest.raises(store.ManifestError, match="recorded as"): + _ = store.read_manifest_bytes(recorded, path) + + +@pytest.mark.parametrize("part", ["a/b", "a\0", "\udc00"]) +def test_a_path_component_the_store_cannot_name_is_refused(part: str) -> None: + with pytest.raises(store.UnstorableInSpiralError): + _ = new(schema_of(BASE), ("x", part)) + + +def test_stored_names_come_from_the_manifest_not_from_the_rule( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A table written under an earlier naming rule is still read by its own names.""" + table = keyed( + { + "a.b": pa.array([1]), + "ox_a;2Eb": pa.array([2]), + "s": pa.array([{"c.d": 3}], pa.struct([("c.d", pa.int64())])), + } + ) + metadata, stored = entries(table.schema), _stored(table) + + def renamed(name: str) -> str: + return "new_" + name.encode().hex() + + monkeypatch.setattr(store, "encode_name", renamed) + manifest = read(metadata) + assert "ox_a;2Eb" in manifest.physical.names + got = store.decode_rows(stored, manifest) + assert [got.column(n)[0].as_py() for n in table.column_names if n != KEY] == [ + 1, 2, {"c.d": 3}, + ] # fmt: skip + + +def _payload(**changes: Any) -> bytes: + """The recorded manifest of ``BASE`` with fields of its JSON changed.""" + body = {**json.loads(entries(schema_of(BASE))), **changes} + return json.dumps(body).encode() + + +def _ipc(schema: pa.Schema) -> str: + return base64.b64encode(schema.serialize().to_pybytes()).decode() + + +_A = pa.struct([("x", pa.int8()), ("y", pa.int8())]) +_TWICE = pa.struct([("x", pa.int8()), ("x", pa.int8())]) +_B = pa.large_binary() +_L = pa.large_list(timestamp("us")) + + +def _physical(index: int, field: Any) -> Any: + """The stored schema of ``BASE`` with one column changed.""" + return store.physical_schema(schema_of(BASE)).set(index, field) + + +def test_the_changed_payload_helper_builds_a_readable_manifest() -> None: + assert read(_payload()) == new(schema_of(BASE)) + + +_BROKEN_MANIFESTS: list[Callable[[bytes], bytes]] = [ + lambda m: b"", + lambda m: b"[]", + lambda m: b"\xff", + lambda m: m + b" junk", + lambda m: b'"text"', + lambda m: _payload(format="other"), + lambda m: _payload(format=None), + lambda m: _payload(version=1), + lambda m: _payload(version=False), + lambda m: _payload(kind=1), + lambda m: _payload(record_path=["other"]), + lambda m: _payload(physical=_ipc(schema_of([("a", pa.int8())]))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field("a", pa.int8())))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field(KEY, _A)))), + lambda m: _payload(physical=_ipc(_physical(3, pa.field("k", _B)))), + lambda m: _payload(physical=_ipc(_physical(1, pa.field("f", _L)))), + lambda m: _payload(physical=_ipc(_physical(0, pa.field("a", _TWICE)))), + lambda m: _payload(record_path="a"), + lambda m: _payload(record_path=[1]), + lambda m: _payload(schema=1), + lambda m: _payload(schema="!!"), + lambda m: _payload(schema=base64.b64encode(b"junk").decode()), + lambda m: _payload(schema=_ipc(schema_of([("a", pa.int8())]))), + lambda m: _payload(schema=_ipc(schema_of([*BASE, ("m", pa.binary(2))]))), +] + + +@pytest.mark.parametrize("make", _BROKEN_MANIFESTS) +def test_a_manifest_that_cannot_be_read_in_full_is_an_error( + make: Callable[[bytes], bytes], +) -> None: + recorded = make(entries(schema_of(BASE))) + with pytest.raises(store.ManifestError): + _ = store.read_manifest_bytes(recorded, PATH) + + +def test_a_large_manifest_is_kept() -> None: + """A raw manifest payload has no size bound of its own: 7 MB of field metadata + round-trips through ``manifest_bytes`` and ``read_manifest_bytes``. The chunk + tests below cover the metadata entry limit of a table.""" + field = pa.field("a", pa.int8(), metadata={"k": "v" * 7_000_000}) + schema = schema_of([field, (KEY, pa.large_binary())]) + assert read(entries(schema)).schema.equals(schema, check_metadata=True) + + +def test_writing_the_same_manifest_twice_changes_nothing() -> None: + one = entries(wide_schema()) + assert entries(wide_schema()) == one + assert store.manifest_bytes(read(one)) == one + + +def test_the_codec_needs_no_spiral_client() -> None: + code = ( + "import sys, orcapod.databases.spiral_store\n" + "assert not [m for m in sys.modules if m.split('.')[0] == 'spiral']" + ) + assert subprocess.run([sys.executable, "-c", code], check=False).returncode == 0 + + +_NARROWED_MAP = """ +import pyarrow as pa +from orcapod.databases import spiral_store as store + +maps = pa.map_(pa.string(), pa.int64()) +rows = pa.table( + { + store.KEY_COLUMN: pa.array([b"a", b"b", b"c"], pa.large_binary()), + "m": pa.array([[("x", 1), ("y", None)], None, []], maps), + "s": pa.array([{"m": [("x", 1)]}] * 3, pa.struct([("m", maps)])), + "l": pa.array([[[("x", 1)]], None, [[]]], pa.list_(maps)), + } +) +manifest = store.new_manifest(("p", "rdb_v1"), "k", rows.schema) +got = store.decode_rows(store.encode_rows(rows), manifest, rows.schema) +assert got.schema == rows.schema, got.schema +assert got.to_pylist() == rows.to_pylist(), got.to_pylist() +""" + + +def test_a_map_given_back_in_small_variants_is_rebuilt_not_cast() -> None: + """Review of PR 590, finding 1: pyarrow aborts the process casting a map from large to + small variants. Run in a subprocess, so an abort fails this test only.""" + done = subprocess.run( + [sys.executable, "-c", _NARROWED_MAP], + capture_output=True, + text=True, + check=False, + ) + assert done.returncode == 0, done.stderr[-2000:] + + +def test_a_record_id_repeated_in_one_write_is_refused() -> None: + """Review of PR 590, finding 2: refused before anything is written.""" + rows = keyed({"a": pa.array([1, 2])}) + rows = rows.set_column( + rows.column_names.index(KEY), KEY, pa.array([b"x", b"x"], pa.large_binary()) + ) + refused(rows, "repeated") + + +# ------------------------------------------------- the manifest in a table's metadata + + +def test_a_manifest_in_chunks_round_trips_within_the_entry_limit() -> None: + manifest = new(wide_schema(), PATH) + entries_ = store.manifest_entries(manifest) + assert len(entries_) > 2 # several chunks and the header + for key, value in entries_.items(): + assert len(key.encode()) + len(value) <= 8192 + others = {"orcapod.path": b"[]", "someone.else": b"x"} + assert store.read_manifest({**others, **entries_}, PATH) == manifest + + +def test_a_table_without_a_manifest_header_has_none() -> None: + entries_ = store.manifest_entries(new(schema_of(BASE))) + chunks = {k: v for k, v in entries_.items() if k != store.MANIFEST_KEY} + assert store.read_manifest({}, PATH) is None + assert store.read_manifest(chunks, PATH) is None + + +def test_chunks_of_an_earlier_longer_manifest_are_not_read() -> None: + longer = store.manifest_entries(new(wide_schema(), PATH)) + shorter = store.manifest_entries(new(schema_of(BASE), PATH)) + assert len(longer) > len(shorter) + assert store.read_manifest({**longer, **shorter}, PATH) == new(schema_of(BASE)) + + +def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, bytes]: + header = {**json.loads(entries_[store.MANIFEST_KEY]), **changes} + return {**entries_, store.MANIFEST_KEY: json.dumps(header).encode()} + + +_BROKEN_ENTRIES: list[Callable[[dict[str, bytes]], dict[str, bytes]]] = [ + lambda e: {k: v for k, v in e.items() if k != f"{store.MANIFEST_KEY}/0"}, + lambda e: {**e, f"{store.MANIFEST_KEY}/0": e[f"{store.MANIFEST_KEY}/0"] + b" "}, + lambda e: {**e, store.MANIFEST_KEY: b"\xff"}, + lambda e: {**e, store.MANIFEST_KEY: b"[]"}, + lambda e: _header_changed(e, format="other"), + lambda e: _header_changed(e, chunks=0), + lambda e: _header_changed(e, chunks="1"), + lambda e: _header_changed(e, chunks=10**6), + lambda e: _header_changed(e, payload_digest="0" * 64), +] + + +@pytest.mark.parametrize("make", _BROKEN_ENTRIES) +def test_a_manifest_in_chunks_that_cannot_be_read_is_an_error( + make: Callable[[dict[str, bytes]], dict[str, bytes]], +) -> None: + with pytest.raises(store.ManifestError): + _ = store.read_manifest(make(store.manifest_entries(new(wide_schema()))), PATH) + + +# --------------------------------------- CodeRabbit on PR 590 (b433047e) + + +def test_a_schema_override_that_is_not_a_store_schema_is_a_manifest_error() -> None: + """``decode_rows`` raises its documented ``ManifestError``, also for a schema that + is no store schema at all (no key column).""" + table = keyed({"a": pa.array([1])}) + manifest = new(table.schema) + without_key = table.schema.remove(table.schema.get_field_index(KEY)) + with pytest.raises(store.ManifestError): + _ = store.decode_rows(_stored(table), manifest, without_key) + + +@pytest.mark.parametrize("where", ["schema", "physical"]) +def test_a_recorded_name_that_is_not_utf8_is_a_manifest_error(where: str) -> None: + """``read_manifest`` raises only ``ManifestError``, also for a name of bytes: in the + logical schema, and in a stored schema of the right shape (so that the name, not the + shape, is what is refused).""" + if where == "schema": + bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) + recorded = _payload(schema=_ipc(schema_of([bad, (KEY, pa.large_binary())]))) + else: + first = store.physical_schema(schema_of(BASE)).field(0) + renamed: Any = pa.field(cast(Any, b"a\xff"), first.type, first.nullable) + recorded = _payload(physical=_ipc(_physical(0, renamed))) + with pytest.raises(store.ManifestError, match="UTF-8"): + _ = store.read_manifest_bytes(recorded, PATH) + + +# --------------------------------------- CodeRabbit on PR 595 (49f1642d) + + +def test_an_impossible_chunk_count_is_refused_before_any_key_is_listed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A header naming more chunks than the metadata holds entries is refused at once: + no key is built for each (a count of 10**12 would exhaust memory).""" + entries_ = store.manifest_entries(new(schema_of(BASE))) + real_range = range + + def bounded(*args: Any) -> Any: + stop = args[0] if len(args) == 1 else args[1] + if stop > len(entries_): + raise AssertionError(f"a key listed for each of {stop} declared chunks") + return real_range(*args) + + monkeypatch.setattr(store, "range", bounded, raising=False) + with pytest.raises(store.ManifestError, match="10000000000"): + _ = store.read_manifest(_header_changed(entries_, chunks=10**10), PATH) + monkeypatch.undo() + # A complete manifest of many chunks still reads, and a surplus chunk of an earlier + # manifest beside it is still ignored. + longer = store.manifest_entries(new(wide_schema(), PATH)) + assert store.read_manifest(longer, PATH) == new(wide_schema()) + + +@pytest.mark.parametrize("version", [1, -1, "0", 0.0, None, True]) +def test_a_manifest_header_of_another_version_is_refused(version: Any) -> None: + """The header's version is checked as the payload's is: an exact integer.""" + entries_ = store.manifest_entries(new(schema_of(BASE))) + changed = _header_changed(entries_, version=version) + with pytest.raises(store.ManifestError, match="header version"): + _ = store.read_manifest(changed, PATH) + without = json.loads(entries_[store.MANIFEST_KEY]) + del without["version"] + missing = {**entries_, store.MANIFEST_KEY: json.dumps(without).encode()} + with pytest.raises(store.ManifestError, match="header version"): + _ = store.read_manifest(missing, PATH) + + +@pytest.mark.parametrize("annotated", [False, True]) +def test_a_dictionary_of_a_logical_types_values_is_refused_as_unstorable( + annotated: bool, +) -> None: + """A dictionary whose values are a logical type, live or annotated, raises the + codec's ``UnstorableInSpiralError`` naming the column (it raised AttributeError).""" + live = Labelled(pa.large_string(), "test.dictionary", b"") + value_type: Any = pa.large_string() if annotated else live + values: Any = pa.dictionary(pa.int32(), value_type) + metadata = {NAME_KEY: b"test.dictionary", METADATA_KEY: b""} if annotated else None + field = pa.field("bad", values, True, cast(Any, metadata)) + schema = schema_of([("a", pa.int64()), field, (KEY, pa.large_binary())]) + for call in (store.physical_schema, store.logical_schema, entries): + with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): + _ = call(schema) diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_store_identity.py new file mode 100644 index 000000000..b63217fe4 --- /dev/null +++ b/tests/test_databases/test_spiral_store_identity.py @@ -0,0 +1,281 @@ +"""SpiralDB store table names and their identity record (ITL-1837; spec ITL-1446 round 2). + +The name rule itself, digest and hint, is main's shared one (``test_store_table_names.py``); +these tests cover SpiralDB's budget of it and the record in a table's metadata. +""" + +from __future__ import annotations + +import hashlib +import json +import random +import re + +import pytest + +from orcapod.databases import spiral_store_identity as names +from orcapod.databases import store_table_names + +H = "0123456789abcdef" * 4 +RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +PIPELINE = ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") +NAME = re.compile(r"^o1_[a-z0-9_]{1,96}_[0-9a-f]{64}$") + + +def test_the_digest_is_sha256_of_the_canonical_json_of_the_components() -> None: + """The digest is SHA-256 of the canonical JSON array of the components, ending the name.""" + expected = hashlib.sha256( + json.dumps(list(RESULT), ensure_ascii=False, separators=(",", ":")).encode() + ).hexdigest() + assert store_table_names.store_table_digest(RESULT) == expected + assert names.spiral_store_table_name(RESULT).endswith("_" + expected) + + +@pytest.mark.parametrize("path", [RESULT, PIPELINE, ("a",), ("É" * 300, "x" * 500)]) +def test_a_name_is_short_and_plain(path: tuple[str, ...]) -> None: + """A name is ``o1__<64 hex>``, within 164 characters, for short and long paths.""" + name = names.spiral_store_table_name(path) + assert NAME.match(name), name + assert len(name) <= 3 + 96 + 1 + 64 <= 255 + + +def test_the_hint_keeps_lower_case_letters_and_digits() -> None: + """The hint maps one character to one and is cut to 96 characters.""" + assert ( + store_table_names.table_name_hint(("My-Fn", "v0", "schema:AB"), hint_length=96) + == "my_fn_v0_schema_ab" + ) + # one character to one: each other character, the separator included, is one '_' + assert store_table_names.table_name_hint(("é", "a/b"), hint_length=96) == "__a_b" + assert store_table_names.table_name_hint(("é", "z"), hint_length=96) == "__z" + assert len(names.spiral_store_table_name(("x" * 200,))) - len("o1__") - 64 == 96 + + +def test_the_name_is_deterministic_and_depends_on_every_component_and_its_order() -> ( + None +): + """A name follows every component and their order, and nothing else.""" + assert names.spiral_store_table_name(RESULT) == names.spiral_store_table_name( + list(RESULT) + ) + assert names.spiral_store_table_name(RESULT) != names.spiral_store_table_name( + RESULT[::-1] + ) + for i in range(len(RESULT)): + changed = RESULT[:i] + (RESULT[i] + "x",) + RESULT[i + 1 :] + assert names.spiral_store_table_name(changed) != names.spiral_store_table_name( + RESULT + ) + + +def test_components_are_kept_apart() -> None: + # Paths whose joined text or hint agree still get different names. + """Paths whose joined text or hint agree still get different names.""" + pairs = [ + (("a", "b"), ("a/b",)), + (("a_b",), ("a-b",)), + (("ab", "c"), ("a", "bc")), + (("A",), ("a",)), + (("x",), ("x", "")), + ] + for left, right in pairs: + assert names.spiral_store_table_name(left) != names.spiral_store_table_name( + right + ) + + +def test_no_two_of_many_adversarial_paths_share_a_name() -> None: + """No two of 20,000 adversarial paths share a name.""" + rng = random.Random(1495) + alphabet = "aA0_-./:é \x00 " + seen: dict[str, tuple[str, ...]] = {} + for _ in range(20_000): + path = tuple( + "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 4))) + for _ in range(rng.randint(1, 3)) + ) + name = names.spiral_store_table_name(path) + assert seen.setdefault(name, path) == path + + +@pytest.mark.parametrize( + ("path", "prefix"), + [ + (RESULT, ()), + (RESULT, ("my_fn",)), + (RESULT, RESULT[:3]), + (RESULT, RESULT), + (("side_effects", "My Pod", H, "tdb_v1"), ("side_effects", "My Pod")), + (("f" * 120, H, "rdb_v1"), ("f" * 120,)), + (("f" * 60, "g" * 60, "rdb_v1"), ("f" * 60,)), + ], +) +def test_a_table_under_a_prefix_has_the_prefix_s_name_prefix( + path: tuple[str, ...], prefix: tuple[str, ...] +) -> None: + """Every table under a path prefix has the prefix's name prefix, also past 96 characters.""" + assert names.spiral_store_table_name(path).startswith( + names.spiral_store_table_name_prefix(prefix) + ) + + +def test_the_name_prefix_of_nothing_is_every_store_table() -> None: + """The name prefix of the empty path prefix is the one every store table has.""" + assert names.spiral_store_table_name_prefix(()) == "o1_" + + +@pytest.mark.parametrize("path", [(), ("a", 1), ("\ud800",)]) +def test_a_path_that_cannot_be_named_is_refused(path: tuple[object, ...]) -> None: + """An empty path, a component that is not text and one that is not UTF-8 are refused.""" + with pytest.raises(ValueError, match="path"): + _ = names.spiral_store_table_name(path) # pyright: ignore[reportArgumentType] # refused on purpose + + +def test_the_metadata_record() -> None: + """A table's record holds its format, path, layout and data context, and reads back.""" + record = names.store_table_metadata(PIPELINE, "std:v1:default") + assert record == { + "orcapod.store": b"orcapod.spiral_store.draft", + "orcapod.path": json.dumps( + list(PIPELINE), ensure_ascii=False, separators=(",", ":") + ).encode(), + "orcapod.layout": b"pdb_v2", + "orcapod.data_context": b"std:v1:default", + } + found = names.read_store_table_metadata(record) + assert found == names.StoreTableRecord(PIPELINE, "pdb_v2", "std:v1:default") + assert found is not None + names.require_store_table_path(found, PIPELINE) + + +def test_every_entry_fits_the_service_s_entry_limit() -> None: + """Every entry of a record fits SpiralDB's entry limit; a longer path is refused.""" + # The JSON of a one-component path is the component and 4 bytes: ``["..."]``. + longest = ("x" * (8192 - len("orcapod.path") - 4),) + record = names.store_table_metadata(longest, "std:v1:default") + assert all(len(k.encode()) + len(v) <= 8192 for k, v in record.items()) + with pytest.raises(ValueError, match="8192"): + _ = names.store_table_metadata((longest[0] + "x",), "std:v1:default") + + +def test_a_table_without_orcapod_metadata_is_unmarked() -> None: + """A table with none of the record's entries is unmarked.""" + assert names.read_store_table_metadata({}) is None + assert names.read_store_table_metadata({"someone.else": b"1"}) is None + + +@pytest.mark.parametrize( + "change", + [ + {"orcapod.store": b"orcapod.spiral_store.v1"}, + {"orcapod.path": b"not json"}, + {"orcapod.path": b'{"a": 1}'}, + {"orcapod.path": b"[]"}, + {"orcapod.path": b'["a", 1]'}, + {"orcapod.layout": b"odb_v1"}, + {"orcapod.data_context": b""}, + {"orcapod.path": b"\xff"}, + ], +) +def test_a_record_that_is_not_this_store_s_is_refused(change: dict[str, bytes]) -> None: + """A record of another format, or with an unreadable or inconsistent entry, is refused.""" + record = {**names.store_table_metadata(PIPELINE, "std:v1:default"), **change} + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +@pytest.mark.parametrize( + "missing", + ["orcapod.store", "orcapod.path", "orcapod.layout", "orcapod.data_context"], +) +def test_a_partial_record_is_refused(missing: str) -> None: + """A record lacking one of its entries is refused.""" + record = names.store_table_metadata(PIPELINE, "std:v1:default") + del record[missing] + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +def test_a_table_of_another_path_under_the_name_is_refused() -> None: + """A record of another path than the one looked up is refused, naming it.""" + found = names.read_store_table_metadata( + names.store_table_metadata(RESULT, "std:v1:default") + ) + assert found is not None + with pytest.raises(names.SpiralStoreTableCollisionError, match="rdb_v1"): + names.require_store_table_path(found, PIPELINE) + + +def test_a_record_with_an_entry_over_the_service_s_limit_is_refused() -> None: + # Review of PR 589, finding 2: the data context key is the caller's text too. + """A record entry over SpiralDB's limit is refused before any table is created.""" + with pytest.raises(ValueError, match="8192"): + _ = names.store_table_metadata(PIPELINE, "x" * 8192) + + +def test_a_recorded_path_that_writers_refuse_is_refused_on_read() -> None: + # Review of PR 589, finding 3: JSON can spell a lone surrogate, which no writer writes. + """A recorded path no writer writes (a lone surrogate) is refused on read.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": b'["\\ud800","rdb_v1"]', + } + with pytest.raises(names.SpiralStoreTableCollisionError, match="UTF-8"): + _ = names.read_store_table_metadata(record) + + +def test_the_collision_message_keeps_components_apart() -> None: + # Review of PR 589, finding 4: ("a/b", ...) and ("a", "b", ...) must read differently. + """The collision message shows component lists, so different paths read differently.""" + found = names.read_store_table_metadata( + names.store_table_metadata(("a/b", "rdb_v1"), "std:v1:default") + ) + assert found is not None + with pytest.raises(names.SpiralStoreTableCollisionError) as raised: + names.require_store_table_path(found, ("a", "b", "rdb_v1")) + assert "['a/b', 'rdb_v1']" in str(raised.value) + assert "['a', 'b', 'rdb_v1']" in str(raised.value) + + +@pytest.mark.parametrize( + "path_json", + [b"[" + b"1" * 5000 + b"]", b"[" * 2000 + b"0" + b"]" * 2000], + ids=["a 5,000-digit integer", "2,000 nested arrays"], +) +def test_a_path_the_json_parser_refuses_is_a_collision(path_json: bytes) -> None: + """CodeRabbit on PR 589: every unreadable record raises the collision error.""" + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": path_json, + } + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + + +def test_the_spiraldb_name_is_the_shared_rule_with_spiraldb_s_budget() -> None: + """The name is main's shared store rule at hint 96 and the whole digest: the vector + ``test_store_table_names.py`` pins for SpiralDB, and no rule of its own.""" + path = ("función", "数据", "rdb_v1") + assert names.spiral_store_table_name(path) == ( + "o1_funci_n____rdb_v1_" + "4c0b0f48110dc57f910431847088e2e11d05b6bf2b26c3e8dfb8dd9dabf2c43b" + ) + assert names.spiral_store_table_name(path) == store_table_names.store_table_name( + path, hint_length=96, digest_length=64 + ) + + +def test_the_store_format_is_marked_provisional() -> None: + """Tables are written in a draft format until the store is switched on, so a table + of this format is told apart from one of the format eventually fixed.""" + assert names.STORE_FORMAT.endswith(".draft") + + +def test_the_collision_error_names_the_table_its_caller_gives() -> None: + """The caller that knows the table adds it; the reason stays readable on its own.""" + plain = names.SpiralStoreTableCollisionError("its record lacks ['orcapod.path']") + assert str(plain) == "not this store's table: its record lacks ['orcapod.path']" + assert plain.table is None + placed = names.SpiralStoreTableCollisionError("x", table="p/d/o1_t") + assert str(placed) == "table p/d/o1_t: not this store's table: x" + assert (placed.reason, placed.table) == ("x", "p/d/o1_t") diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 29b8ac231..12c9a773b 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -15,14 +15,17 @@ from __future__ import annotations import datetime as dt +import decimal import math import operator import os import struct +import uuid from collections.abc import Iterator from dataclasses import dataclass from pathlib import Path from typing import Any +from unittest.mock import patch import pyarrow as pa import pyarrow.compute as pc @@ -481,3 +484,452 @@ def test_a_source_reads_a_window_with_an_equality_and_a_limit(place: _Place) -> assert limited.as_table()["k"].to_pylist() == expected[:2] with pytest.raises(TypeError, match="integer, timestamp or date"): place.source("ranges").where(col("x") > 0.0) + + +def _client(place: _Place) -> Any: + """Return an SDK client on the place, for the test's own reads and writes.""" + if place.overrides is None: + return fake.FakeClient() + return place.connector()._client # pyright: ignore[reportPrivateUsage] # the SDK's client, for the test's own writes + + +def test_table_metadata(place: _Place) -> None: + """Table metadata as measured with spiral-sdk 0.16.78 (the fake's ``table-metadata``). + + Fixed keys only, so a live table does not grow from run to run. + """ + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "table_metadata", key, exist_ok=True + ) + token = uuid.uuid4().hex.encode() + table.set_metadata({"conformance.a": token, "conformance.b": b"before"}) + table.set_metadata({"conformance.b": token, "conformance.empty": b""}) + found = table.get_metadata() + assert found["conformance.a"] == token # an upsert keeps the other keys + assert found["conformance.b"] == token + assert found["conformance.empty"] == b"" # stored as empty, not deleted + + # Not versioned: a snapshot taken before a write sees metadata set after it, and a + # metadata write makes no snapshot. + before = client.keyed_table(place.project, place.dataset, "table_metadata") + after = before.append( + pa.table({"k": pa.array(["r"], pa.large_string()), "v": pa.array([token])}) + ) + after.set_metadata({"conformance.after": token}) + assert before.get_metadata()["conformance.after"] == token + pinned = client.keyed_table_by_id(before.resource_id, asof=int(before.version_id)) + assert pinned.get_metadata()["conformance.after"] == token + again = client.keyed_table(place.project, place.dataset, "table_metadata") + assert again.version_id == after.version_id + + # Limits: a key up to 255 UTF-8 bytes, a key and its value together up to 8,192. + table.set_metadata( + {"m" * 255: b"x" * (8192 - 255), "conformance.max": b"x" * (8192 - 15)} + ) + for refused in ( + {"m" * 256: token}, + {"conformance.big": b"x" * (8192 - 15 + 1)}, + {"m" * 255: b"x" * (8192 - 255 + 1)}, + ): + with pytest.raises(Exception, match=r"status 400"): # noqa: PT011 # the SDK's error type differs from the fake's + table.set_metadata(refused) + found = table.get_metadata() + assert found["m" * 255] == b"x" * (8192 - 255) + assert "m" * 256 not in found + assert "conformance.big" not in found + + +def test_the_fake_keeps_concurrent_upserts_of_different_keys(tmp_path: Path) -> None: + """Two clients upserting different keys at once keep both (measured live, 0.16.78). + + Review of PR 589, finding 1: each read waits for the other writer's read, so an + upsert that is not atomic would lose one key. + """ + import threading + + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + made = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + both_read = threading.Barrier(2, timeout=0.5) + original = fake._Store.metadata # pyright: ignore[reportPrivateUsage] # the read an upsert starts from + + def metadata_after_the_other_read(self: Any, table_id: str) -> dict[str, bytes]: + found = original(self, table_id) + try: + _ = both_read.wait() + except threading.BrokenBarrierError: + pass # an atomic upsert holds the other writer back: no meeting + return found + + def upsert(name: str) -> None: + fake.FakeClient().keyed_table_by_id(made.resource_id).set_metadata( + {name: b"1"} + ) + + with patch.object(fake._Store, "metadata", metadata_after_the_other_read): # pyright: ignore[reportPrivateUsage] + writers = [threading.Thread(target=upsert, args=(n,)) for n in "ab"] + for w in writers: + w.start() + for w in writers: + w.join() + assert made.get_metadata() == {"a": b"1", "b": b"1"} + + +# ------------------------------------------------ the store codec (ITL-1497) + + +map_of: Any = pa.map_ # the stubs lack keys_sorted + + +def _codec_rows() -> pa.Table: + """Rows of a store table: names the codec escapes, and every kept kind of value.""" + from orcapod.databases import spiral_store + + utc = dt.timezone.utc + inner = pa.struct([pa.field("a.b", pa.int8(), False), pa.field("__c", pa.int8())]) + keys = [b"r0", b"r1", b"r2"] + columns: dict[str, Any] = { # pyarrow arrays of several types + spiral_store.KEY_COLUMN: pa.array(keys, pa.large_binary()), + "__data_context": pa.array(["std:v1:default"] * 3, pa.large_string()), + "a.b": pa.array([1, 2, None], pa.int64()), + "$x": pa.array([True, None, False]), + "*": pa.array([b"", b"\x00", None], pa.large_binary()), + "ok$*;": pa.array([0, 2**64 - 1, None], pa.uint64()), + "ts_utc": pa.array( + [ + dt.datetime.max.replace(tzinfo=utc), + dt.datetime.min.replace(tzinfo=utc), + None, + ], + pa.timestamp("us", tz="UTC"), + ), + "ts_ns": pa.array([2**63 - 1, -(2**63), 0], pa.int64()).view( + pa.timestamp("ns", tz="-03:30") + ), + "time": pa.array([-1, 86_400_000_000, None], pa.int64()).view(pa.time64("us")), + "f32": pa.array([0x7FC00001, 0x80000000, 0xFF800001], pa.uint32()).view( + pa.float32() + ), + "d32": pa.array( + [decimal.Decimal("1.23"), None, decimal.Decimal("-0.01")], + pa.decimal32(5, 2), + ), + "d64": pa.array([86_400_000 + 1, 0, None], pa.int64()).view(pa.date64()), + "s": pa.array([{"a.b": 1, "__c": None}] * 3, inner), + "ls": pa.array( + [[{"a.b": 1, "__c": 2}, {"a.b": 2, "__c": None}], None, []], + pa.large_list(inner), + ), + "fl": pa.array( + [[{"a.b": 1, "__c": 2}], None, [{"a.b": 3, "__c": None}]], + pa.list_(inner, 1), + ), + "m": pa.array( + [[("b", 1), ("a", 2)], None, []], + map_of(pa.large_string(), pa.int64(), keys_sorted=True), + ), + "n": pa.array([None, None, None], pa.null()), + } + return pa.table(columns) + + +def test_the_store_codec_round_trips(place: _Place) -> None: + """Encoded rows written through spiral-sdk and decoded back are the rows, exactly. + + A fixed table and fixed rows, so a live run writes the same rows each time. + """ + from orcapod.databases import spiral_store + + rows = _codec_rows() + manifest = spiral_store.new_manifest(("conformance", "rdb_v1"), "test", rows.schema) + encoded = spiral_store.encode_rows(rows) + key = pa.schema([pa.field(spiral_store.KEY_COLUMN, pa.large_binary(), False)]) + client = _client(place) + table = client.project(place.project).create_keyed_table( + place.dataset, "store_codec", key, exist_ok=True + ) + table = table.append(encoded) + read_back = client.keyed_table_by_id(table.resource_id).scan().to_table() + decoded = spiral_store.decode_rows(read_back, manifest) + order = pa.array( + sorted( + range(decoded.num_rows), + key=lambda i: decoded[spiral_store.KEY_COLUMN][i].as_py(), + ), + pa.int64(), + ) + got = decoded.take(order) + want = rows.cast(spiral_store.logical_schema(rows.schema)) + assert got.schema.equals(want.schema, check_metadata=True) + for name in want.column_names: + a, b = got.column(name).combine_chunks(), want.column(name).combine_chunks() + if pa.types.is_floating(a.type): + assert a.view(pa.uint32()).equals(b.view(pa.uint32())), name + else: + assert a.equals(b), name + + +@pytest.mark.parametrize( + "column", + [ + pa.table({"*": pa.array([1])}), + pa.table({"": pa.array([1])}), + pa.table({"__x": pa.array([1])}), + pa.table({"$x": pa.array([1])}), + pa.table({"a.b": pa.array([1])}), + pa.table({"s": pa.array([{"a.b": 1}], pa.struct([("a.b", pa.int8())]))}), + pa.table({"t": pa.array([86_400], pa.int32()).view(pa.time32("s"))}), + pa.table({"t": pa.array([-1], pa.int64()).view(pa.time64("ns"))}), + pa.table({"b": pa.array([b"ab"], pa.binary(2))}), + pa.table({"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 + + +def _written_and_read(place: _Place, name: str, column: pa.Table) -> pa.Table: + """Write ``column`` under keys r0... to a fixed table and read those rows back.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, name, key, exist_ok=True + ) + keys = pa.array([f"r{i}" for i in range(column.num_rows)], pa.large_string()) + table = table.append(column.add_column(0, "k", keys)) + read = client.keyed_table_by_id(table.resource_id).scan().to_table() + return read.filter(pc.is_in(read.column("k"), keys)).sort_by("k") + + +def test_a_zero_width_fixed_size_list_of_strings_round_trips(place: _Place) -> None: + """Review of PR 590, finding 3 (the fake's rebuild of a zero-width list).""" + value = [[], None, []] + column = pa.table({"z": pa.array(value, pa.list_(pa.large_string(), 0))}) + got = _written_and_read(place, "zero_width_lists", column) + assert got.column("z").to_pylist() == value + + +def test_nul_is_cut_in_nested_field_names(place: _Place) -> None: + """Review of PR 590, finding 4: the service cuts a name at NUL at every depth + (measured live with spiral-sdk 0.16.78).""" + inner = pa.struct([("x\0y", pa.int8()), ("z", pa.int8())]) + column = pa.table( + { + "s": pa.array([{"x\0y": 1, "z": 2}], inner), + "l": pa.array([[{"x\0y": 3, "z": 4}]], pa.large_list(inner)), + } + ) + got = _written_and_read(place, "nul_in_field_names", column) + assert got.column("s").to_pylist() == [{"x": 1, "z": 2}] + assert got.column("l").to_pylist() == [[{"x": 3, "z": 4}]] + + +def test_the_fake_never_shows_a_half_written_metadata_file( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """CodeRabbit on PR 589: a reader during a metadata write sees a whole mapping. + + Every file write is made to call a reader after it has truncated its file and before + it has written anything. + """ + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + table.set_metadata({"a": b"1"}) + seen: list[dict[str, bytes]] = [] + original = Path.write_text + + def write_text_with_a_reader( + self: Path, data: str, *args: Any, **kw: Any + ) -> int: + with self.open("w") as handle: + handle.flush() + seen.append( + fake.FakeClient() + .keyed_table_by_id(table.resource_id) + .get_metadata() + ) + return original(self, data, *args, **kw) + + monkeypatch.setattr(Path, "write_text", write_text_with_a_reader) + table.set_metadata({"b": b"2"}) + monkeypatch.undo() + assert seen == [{"a": b"1"}] + assert table.get_metadata() == {"a": b"1", "b": b"2"} + + +@pytest.mark.parametrize("child", ["x", "x\0y"]) +def test_a_null_under_a_non_null_column_is_refused_whatever_its_names( + place: _Place, child: str +) -> None: + """Review of PR 590 (round 2): cutting a nested name at NUL keeps the column's flag.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "nul_names_non_null", key, exist_ok=True + ) + item = pa.struct([(child, pa.int8())]) + schema = pa.schema( + [ + pa.field("k", pa.large_string(), False), + pa.field("l", pa.large_list(item), nullable=False), + ] + ) + rows = pa.Table.from_arrays( + [ + pa.array(["r0", "r1"], pa.large_string()), + pa.array([[{child: 1}], None], pa.large_list(item)), + ], + schema=schema, + ) + with pytest.raises(Exception): # noqa: B017, PT011 # the SDK's error type differs from the fake's + _ = table.append(rows) + + +def _encoded(array: Any, how: str) -> Any: + """``array`` (of two equal values) dictionary-encoded or run-end encoded, built + from parts, as pyarrow encodes no struct itself.""" + one = array.slice(0, 1) + if how == "dictionary": + return pa.DictionaryArray.from_arrays(pa.array([0, 0], pa.int32()), one) + return pa.RunEndEncodedArray.from_arrays(pa.array([2], pa.int32()), one) + + +@pytest.mark.parametrize("how", ["dictionary"]) +def test_the_fake_refuses_an_encoded_time_outside_a_day( + tmp_path: Path, how: str +) -> None: + """CodeRabbit on PR 590: the time rule holds inside encoded arrays too. (pyarrow + refuses to build a run-end-encoded array of such a time, so only a dictionary can + carry one.)""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + times = pa.array([-1, -1], pa.int64()).view(pa.time64("ns")) + rows = pa.table( + {"k": pa.array(["a", "b"], pa.large_string()), "t": _encoded(times, how)} + ) + with pytest.raises(fake.SpiralError, match="time"): + _ = table.append(rows) + + +@pytest.mark.parametrize("how", ["dictionary", "run_end"]) +def test_the_fake_cuts_nul_in_names_inside_encoded_arrays( + tmp_path: Path, how: str +) -> None: + """CodeRabbit on PR 590: the NUL rule holds inside encoded arrays too.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + values = pa.array([{"x\0y": 1}, {"x\0y": 1}], pa.struct([("x\0y", pa.int8())])) + rows = pa.table( + {"k": pa.array(["a", "b"], pa.large_string()), "s": _encoded(values, how)} + ) + stored = table.append(rows).scan().to_table() + assert stored.column("s").to_pylist() == [{"x": 1}, {"x": 1}] + + +def test_the_fake_cuts_nul_in_names_inside_nested_encoded_arrays( + tmp_path: Path, +) -> None: + """CodeRabbit on PR 590 (round 2): an encoded struct inside a list is cut too.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + one = pa.array([{"x\0y": 1}], pa.struct([("x\0y", pa.int8())])) + encoded = pa.DictionaryArray.from_arrays(pa.array([0, 0], pa.int32()), one) + lists = pa.LargeListArray.from_arrays(pa.array([0, 1, 2], pa.int64()), encoded) + rows = pa.table({"k": pa.array(["a", "b"], pa.large_string()), "l": lists}) + stored = table.append(rows).scan().to_table() + assert stored.column("l").to_pylist() == [[{"x": 1}], [{"x": 1}]] + + +# ---------------------------------- verification r3 of PR 590 (0dc34c95) + + +class _ProbeExtension(pa.ExtensionType): + """An extension type of the tests' own, over any storage.""" + + def __init__(self, storage: Any) -> None: + super().__init__(storage, "orcapod.test.probe") + + def __arrow_ext_serialize__(self) -> bytes: + return b"" + + @classmethod + def __arrow_ext_deserialize__(cls, storage_type: Any, serialized: bytes) -> Any: + return cls(storage_type) + + +def _struct_one(name: str) -> Any: + return pa.array([{name: 1}], pa.struct([(name, pa.int8())])) + + +def _dictionary_of(values: Any, n: int) -> Any: + return pa.DictionaryArray.from_arrays(pa.array([0] * n, pa.int32()), values) + + +def test_a_sliced_nullable_list_of_encoded_structs_round_trips(place: _Place) -> None: + """A null row of a sliced list over dictionary-encoded structs is kept (measured + live with spiral-sdk 0.16.78: such a list is stored as its decoded values).""" + lists = pa.LargeListArray.from_arrays( + pa.array([0, 1, 2, 3], pa.int64()), + _dictionary_of(_struct_one("x"), 3), + mask=pa.array([False, True, False]), + ) + got = _written_and_read( + place, "sliced_encoded_lists", pa.table({"l": lists.slice(1, 2)}) + ) + assert got.column("l").to_pylist() == [None, [{"x": 1}]] + + +@pytest.mark.parametrize("encoded", [False, True], ids=["plain", "dictionary"]) +def test_nul_is_cut_in_names_inside_an_extension(place: _Place, encoded: bool) -> None: + """An extension column is stored as its storage, its struct names cut at NUL (measured + live with spiral-sdk 0.16.78 for a plain struct).""" + storage = _struct_one("x\0y") + if encoded: + storage = _dictionary_of(storage, 1) + column = pa.ExtensionArray.from_storage(_ProbeExtension(storage.type), storage) + got = _written_and_read( + place, f"nul_in_extension_{encoded}", pa.table({"e": column}) + ) + assert got.column("e").to_pylist() == [{"x": 1}] + + +def test_a_reserved_name_inside_an_encoded_struct_is_refused(place: _Place) -> None: + """Measured live with spiral-sdk 0.16.78: a struct field named ``$a`` is refused, also + when the struct is dictionary-encoded.""" + client = _client(place) + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = client.project(place.project).create_keyed_table( + place.dataset, "reserved_in_encoded", key, exist_ok=True + ) + rows = pa.table( + { + "k": pa.array(["r0", "r1"], pa.large_string()), + "s": _dictionary_of(_struct_one("$a"), 2), + } + ) + with pytest.raises(Exception, match="reserved"): # noqa: B017, PT011 # the SDK's error type differs from the fake's + _ = table.append(rows) From 76ac9fe695b198665c21a906f033d8650d2b39e8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:40:29 -0800 Subject: [PATCH 05/50] fix(spiraldb): type leases without the optional SDK --- src/orcapod/databases/spiraldb_lease.py | 92 ++++++++++++++++++----- tests/test_databases/test_spiral_lease.py | 43 +++++------ 2 files changed, 89 insertions(+), 46 deletions(-) diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 1a9cf345a..eb9214f8f 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -6,7 +6,7 @@ import re from dataclasses import dataclass from datetime import datetime, timezone -from typing import TYPE_CHECKING, cast +from typing import Protocol, cast from uuid import uuid4 import pyarrow as pa @@ -15,10 +15,6 @@ from orcapod.databases.store_table_names import spiral_lease_table_name from orcapod.errors import OrcapodDatabaseError -if TYPE_CHECKING: - from spiral import Client - from spiral.keyed_tables import KeyedTable - _KEY_PREFIX = "orcapod_lease_v1_" _KEY_PATTERN = re.compile(rf"{_KEY_PREFIX}[0-9a-f]{{32}}") _CLAIM = "claim" @@ -26,6 +22,62 @@ _CONFLICT = "remote service returned an unknown error (status 409)" +class _Scan(Protocol): + """The SDK scan interface used to read lease rows.""" + + def to_table(self) -> pa.Table: + """Read the scan as Arrow.""" + ... + + +class _KeyedTable(Protocol): + """The SDK snapshot operations used by the lease.""" + + @property + def resource_id(self) -> str: + """Return the immutable table ID.""" + ... + + @property + def key_columns(self) -> tuple[str, ...]: + """Return the ordered primary-key names.""" + ... + + def scan(self, *, limit: int) -> _Scan: + """Plan a scan of the lease rows.""" + ... + + def append(self, data: pa.Table, /) -> _KeyedTable: + """Publish a keyed row and return a new snapshot.""" + ... + + +class _Project(Protocol): + """The SDK project operation used to claim a generation.""" + + def create_keyed_table( + self, dataset: str, name: str, key_schema: pa.Schema, /, *, exist_ok: bool + ) -> _KeyedTable: + """Create a keyed table.""" + ... + + +class _Client(Protocol): + """The SDK client operations used by the lease.""" + + def project(self, id: str, /) -> _Project: + """Select a project.""" + ... + + def keyed_table(self, project: str, dataset: str, name: str, /) -> _KeyedTable: + """Open the latest table snapshot by name.""" + ... + + def keyed_table_by_id(self, table_id: str, /) -> _KeyedTable: + """Open the latest table snapshot by immutable ID.""" + ... + + class LeaseError(OrcapodDatabaseError): """A writer lease operation could not be completed or verified.""" @@ -67,11 +119,11 @@ class _State: def _open( - client: Client, project_id: str, dataset: str, generation: int -) -> KeyedTable | None: + client: _Client, project_id: str, dataset: str, generation: int +) -> _KeyedTable | None: """Open the latest snapshot of a generation by name.""" return cast( - "KeyedTable | None", + "_KeyedTable | None", sdk._open_keyed_table( # pyright: ignore[reportPrivateUsage] client, project_id, dataset, spiral_lease_table_name(generation) ), @@ -79,8 +131,8 @@ def _open( def _newest( - client: Client, project_id: str, dataset: str -) -> tuple[int, KeyedTable | None]: + client: _Client, project_id: str, dataset: str +) -> tuple[int, _KeyedTable | None]: """Bracket the end of the contiguous generation sequence, then bisect.""" low, high = 0, 1 newest = None @@ -97,7 +149,7 @@ def _newest( return low, newest -def _key(table: KeyedTable) -> str: +def _key(table: _KeyedTable) -> str: """Validate the reserved primary key before reading or mutating a lease.""" keys = table.key_columns if len(keys) != 1 or _KEY_PATTERN.fullmatch(keys[0]) is None: @@ -107,7 +159,7 @@ def _key(table: KeyedTable) -> str: return keys[0] -def _state(table: KeyedTable, key: str) -> _State: +def _state(table: _KeyedTable, key: str) -> _State: """Read the two possible states from a snapshot, including a bare claim.""" owner = None released = False @@ -142,8 +194,8 @@ def _row( def _claim_generation( - client: Client, project_id: str, dataset: str, generation: int, key: str -) -> KeyedTable: + client: _Client, project_id: str, dataset: str, generation: int, key: str +) -> _KeyedTable: """Make one exclusive create attempt and reconcile a lost reply by token.""" name = spiral_lease_table_name(generation) key_schema = pa.schema([pa.field(key, pa.large_string(), nullable=False)]) @@ -173,7 +225,7 @@ def _claim_generation( ) from exc -def acquire(client: Client, project_id: str, dataset: str, *, owner: str) -> Lease: +def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Lease: """Claim a dataset for one writer or raise before any store data can be written.""" generation, latest = _newest(client, project_id, dataset) if latest is not None: @@ -204,7 +256,7 @@ def acquire(client: Client, project_id: str, dataset: str, *, owner: str) -> Lea return lease -def _held_table(client: Client, lease: Lease) -> KeyedTable: +def _held_table(client: _Client, lease: Lease) -> _KeyedTable: """Reopen the lease by ID and verify that it belongs to this process and token.""" sdk.require_same_process(lease.pid) table = client.keyed_table_by_id(lease.table_id) @@ -213,7 +265,7 @@ def _held_table(client: Client, lease: Lease) -> KeyedTable: return table -def check(client: Client, lease: Lease) -> None: +def check(client: _Client, lease: Lease) -> None: """Raise if a claim cannot be verified immediately before use.""" table = _held_table(client, lease) state = _state(table, lease.key) @@ -225,7 +277,7 @@ def check(client: Client, lease: Lease) -> None: ) -def _mark_released(client: Client, table: KeyedTable, key: str) -> None: +def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: """Write the release marker once, settling ambiguous replies by the exact ID.""" if _state(table, key).released: return @@ -248,12 +300,12 @@ def _mark_released(client: Client, table: KeyedTable, key: str) -> None: ) from exc -def release(client: Client, lease: Lease) -> None: +def release(client: _Client, lease: Lease) -> None: """Release exactly this claim after the writer and all pending writes have stopped.""" _mark_released(client, _held_table(client, lease), lease.key) -def clear(client: Client, table_id: str, *, confirm_writer_stopped: bool) -> None: +def clear(client: _Client, table_id: str, *, confirm_writer_stopped: bool) -> None: """Manually release a stale generation by immutable table ID.""" if confirm_writer_stopped is not True: raise ValueError( diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 60d615eae..47b4cfc51 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -4,7 +4,6 @@ from collections.abc import Iterator from pathlib import Path -from typing import TYPE_CHECKING, cast import pyarrow as pa import pytest @@ -25,26 +24,18 @@ ) from tests.test_databases import fake_spiral_sdk as fake -if TYPE_CHECKING: - from spiral import Client - _PROJECT = "project" _DATASET = "dataset" -def _fake_client() -> Client: - """Treat the fake's SDK subset as a client for the lease module.""" - return cast("Client", cast("object", fake.FakeClient())) - - @pytest.fixture -def client(tmp_path: Path) -> Iterator[Client]: +def client(tmp_path: Path) -> Iterator[fake.FakeClient]: """Install the fake for one test and return its SDK-shaped client.""" with fake.install(tmp_path): - yield _fake_client() + yield fake.FakeClient() -def test_take_check_release_and_retake(client: Client) -> None: +def test_take_check_release_and_retake(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="first run") check(client, first) release(client, first) @@ -57,9 +48,9 @@ def test_take_check_release_and_retake(client: Client) -> None: check(client, first) -def test_crashed_holder_refuses_until_manually_cleared(client: Client) -> None: +def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="same owner") - other = _fake_client() + other = fake.FakeClient() for _ in range(2): with pytest.raises(LeaseBusyError) as refused: _ = acquire(other, _PROJECT, _DATASET, owner="same owner") @@ -81,7 +72,7 @@ def test_crashed_holder_refuses_until_manually_cleared(client: Client) -> None: @pytest.mark.parametrize("winner_releases", [False, True]) def test_two_writers_that_observed_the_same_generation( - client: Client, monkeypatch: pytest.MonkeyPatch, winner_releases: bool + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, winner_releases: bool ) -> None: create = fake.FakeProject.create_keyed_table attempted: list[str] = [] @@ -96,7 +87,7 @@ def racing_create( ) -> fake.FakeKeyedTable: attempted.append(name) if len(attempted) == 1: - other = _fake_client() + other = fake.FakeClient() winner = acquire(other, _PROJECT, _DATASET, owner="winner") check(other, winner) if winner_releases: @@ -109,7 +100,7 @@ def racing_create( assert attempted == [spiral_lease_table_name(1)] * 2 -def test_crash_between_create_and_owner_record(client: Client) -> None: +def test_crash_between_create_and_owner_record(client: fake.FakeClient) -> None: with pytest.MonkeyPatch.context() as patch: def crash(_table: fake.FakeKeyedTable, _rows: pa.Table) -> fake.FakeKeyedTable: @@ -125,7 +116,7 @@ def crash(_table: fake.FakeKeyedTable, _rows: pa.Table) -> fake.FakeKeyedTable: def test_stale_clear_cannot_be_overwritten_by_late_owner_record( - client: Client, monkeypatch: pytest.MonkeyPatch + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: append = fake.FakeKeyedTable.append ids: list[str] = [] @@ -149,7 +140,7 @@ def clear_before_append( def test_create_reply_lost_after_exclusive_creation( - client: Client, monkeypatch: pytest.MonkeyPatch + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: create = fake.FakeProject.create_keyed_table @@ -171,7 +162,7 @@ def lose_reply( @pytest.mark.parametrize("landed", [True, False]) def test_release_reply_lost( - client: Client, monkeypatch: pytest.MonkeyPatch, landed: bool + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, landed: bool ) -> None: holder = acquire(client, _PROJECT, _DATASET, owner="holder") append = fake.FakeKeyedTable.append @@ -196,7 +187,7 @@ def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTabl def test_manual_clear_refuses_store_data_and_listing_keeps_store_data( - client: Client, + client: fake.FakeClient, ) -> None: holder = acquire(client, _PROJECT, _DATASET, owner="holder") lease_name = spiral_lease_table_name(1) @@ -213,7 +204,7 @@ def test_manual_clear_refuses_store_data_and_listing_keeps_store_data( check(client, holder) -def test_other_datasets_have_independent_leases(client: Client) -> None: +def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="first") second = acquire(client, _PROJECT, "other", owner="second") assert first.table_id != second.table_id @@ -223,7 +214,7 @@ def test_other_datasets_have_independent_leases(client: Client) -> None: @pytest.mark.parametrize("late_create_wins", [False, True]) def test_create_that_arrives_after_timeout_never_grants_a_second_lease( - client: Client, monkeypatch: pytest.MonkeyPatch, late_create_wins: bool + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, late_create_wins: bool ) -> None: create = fake.FakeProject.create_keyed_table pending: list[tuple[fake.FakeProject, str, str, pa.Schema]] = [] @@ -245,7 +236,7 @@ def delay_create( with pytest.raises(LeaseError, match="Could not confirm"): _ = acquire(client, _PROJECT, _DATASET, owner="delayed") - other = _fake_client() + other = fake.FakeClient() if late_create_wins: table = create(*pending[0]) with pytest.raises(LeaseBusyError, match=table.resource_id): @@ -258,7 +249,7 @@ def delay_create( def test_generation_search_uses_logarithmic_probes( - client: Client, monkeypatch: pytest.MonkeyPatch + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: for _ in range(19): release(client, acquire(client, _PROJECT, _DATASET, owner="past")) @@ -286,7 +277,7 @@ def count_open( def test_lookup_error_never_licenses_creation( - client: Client, monkeypatch: pytest.MonkeyPatch + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: def unavailable(*_args: object) -> fake.FakeKeyedTable: raise fake.SpiralError("remote service returned an unknown error (status 404)") From faa21c348af69d4862f096f8f83e1c6e490b9120 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:43:23 -0800 Subject: [PATCH 06/50] fix(spiraldb): reserve numbered lease generations consistently --- docs/dev/plans/itl-1838-spiraldb-lease.md | 6 ++- src/orcapod/databases/spiraldb_connector.py | 24 ++++++---- src/orcapod/databases/store_table_names.py | 6 ++- tests/test_databases/test_spiral_lease.py | 51 +++++++++++++++++---- 4 files changed, 63 insertions(+), 24 deletions(-) diff --git a/docs/dev/plans/itl-1838-spiraldb-lease.md b/docs/dev/plans/itl-1838-spiraldb-lease.md index 801989f8b..c11b3f545 100644 --- a/docs/dev/plans/itl-1838-spiraldb-lease.md +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -27,8 +27,10 @@ basedpyright, then open a PR against main and address CodeRabbit findings. Use `spiraldb_lease.acquire(client, project_id, dataset, owner=...)` before issuing any store writes. Pass the returned lease to `check(client, lease)` before writes and to `release(client, lease)` after all writes have finished. -The generation namespace is separate from record table names and the connector -omits it from listings. +Canonical numbered generation names are separate from record table names. The +connector skips generations as it reads listing pages and reserves those names +at direct lookup. The listing endpoint still returns generation entries in its +pages, so the service listing cost grows with the number of acquisitions. A refusal identifies the blocking table ID. To clear a stale lease, first stop the previous writer and ensure all outstanding writes have settled. Then call diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 9a59f17ae..2d9fbe17f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -431,7 +431,7 @@ def _http_get_json(url: str, token: str | None) -> dict[str, Any]: def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: - """Return a dataset's keyed tables: their names by table id. + """Return keyed table names by ID, omitting writer lease generations. spiral-sdk offers no listing of keyed tables, so this is the documented endpoint (docs.spiraldb.com, "List Keyed tables"), called with the client's address and @@ -459,7 +459,9 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, ) # A page can be empty before the last one. names.update( - (t["id"], t["table"]) for t in page["items"] if t["dataset"] == dataset + (t["id"], t["table"]) + for t in page["items"] + if t["dataset"] == dataset and not is_spiral_lease_table_name(t["table"]) ) following = page.get("nextPageToken") if following is None: @@ -933,12 +935,14 @@ def _service_call(self, doing: str, table_name: str) -> Any: return _service_call(f"{doing} {self._qualified(table_name)}", self._health) def _require_user_table(self, table_name: str) -> None: - """Refuse the reserved name of the dataset's schema table.""" + """Refuse names reserved for the dataset's internal tables.""" if table_name == SCHEMA_TABLE: raise ValueError( f"{SCHEMA_TABLE!r} is reserved: it is where Orcapod keeps the schemas of " f"the tables of dataset {self._dataset!r}" ) + if is_spiral_lease_table_name(table_name): + raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. @@ -959,18 +963,18 @@ def get_table_names(self) -> list[str]: recorded = ( (self._schemas.rows() or {}) if SCHEMA_TABLE in listed.values() else {} ) - gone = sorted(row.table_name for i, row in recorded.items() if i not in listed) + gone = sorted( + row.table_name + for i, row in recorded.items() + if i not in listed and not is_spiral_lease_table_name(row.table_name) + ) if gone: _warn_once( (f"{self._project_id}/{self._dataset}", str(gone)), f"the {SCHEMA_TABLE} of SpiralDB dataset {self._project_id}/" f"{self._dataset} records tables that the dataset no longer holds: {gone}", ) - return sorted( - name - for name in listed.values() - if name != SCHEMA_TABLE and not is_spiral_lease_table_name(name) - ) + return sorted(name for name in listed.values() if name != SCHEMA_TABLE) def lookup_table(self, table_name: str) -> SpiralDBTable: """Look the table up once, for several items of its metadata (ITL-1350). @@ -983,7 +987,7 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. - ValueError: If the name is the schema table's. + ValueError: If the name is reserved for an internal table. """ self._require_open() self._require_user_table(table_name) diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index fea894bf3..36ba4f30a 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -4,6 +4,7 @@ import hashlib import json +import re from collections.abc import Sequence SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1" @@ -11,6 +12,7 @@ STORE_TABLE_NAME_PREFIX = "o1_" _SPIRAL_LEASE_TABLE_PREFIX = "orcapod_lease_v1_g" +_SPIRAL_LEASE_TABLE_PATTERN = re.compile(rf"{_SPIRAL_LEASE_TABLE_PREFIX}[1-9][0-9]*") def spiral_lease_table_name(generation: int) -> str: @@ -19,8 +21,8 @@ def spiral_lease_table_name(generation: int) -> str: def is_spiral_lease_table_name(name: str) -> bool: - """Return whether the name belongs to the reserved lease namespace.""" - return name.startswith(_SPIRAL_LEASE_TABLE_PREFIX) + """Return whether the name is reserved for a numbered lease generation.""" + return _SPIRAL_LEASE_TABLE_PATTERN.fullmatch(name) is not None def store_table_path_json(path: Sequence[str]) -> bytes: diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 47b4cfc51..1a3cee624 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -186,24 +186,55 @@ def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTabl _ = acquire(client, _PROJECT, _DATASET, owner="next") -def test_manual_clear_refuses_store_data_and_listing_keeps_store_data( - client: fake.FakeClient, +@pytest.mark.parametrize("reverse", [False, True]) +def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reverse: bool ) -> None: holder = acquire(client, _PROJECT, _DATASET, owner="holder") lease_name = spiral_lease_table_name(1) - data_name = store_table_name([lease_name], hint_length=96, digest_length=64) + full_path = [lease_name, "records"] + names = [ + store_table_name(path, hint_length=96, digest_length=64) + for path in (full_path, full_path[::-1]) + ] + assert names[0] != names[1] + lookalike = f"{lease_name}report" assert is_spiral_lease_table_name(lease_name) - assert not is_spiral_lease_table_name(data_name) - data = client.project(_PROJECT).create_keyed_table( - _DATASET, data_name, pa.schema([pa.field("id", pa.int64())]) - ) - with pytest.raises(LeaseError, match=data.resource_id): - clear(client, data.resource_id, confirm_writer_stopped=True) + assert not is_spiral_lease_table_name(lookalike) + key_schema = pa.schema([pa.field("id", pa.int64())]) + for name in reversed(names) if reverse else names: + assert not is_spiral_lease_table_name(name) + data = client.project(_PROJECT).create_keyed_table(_DATASET, name, key_schema) + with pytest.raises(LeaseError, match=data.resource_id): + clear(client, data.resource_id, confirm_writer_stopped=True) + _ = client.project(_PROJECT).create_keyed_table(_DATASET, lookalike, key_schema) + + monkeypatch.setattr(fake, "list_page_size", 1) with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - assert connector.get_table_names() == [data_name] + assert connector.get_table_names() == sorted([*names, lookalike]) + for name in [*names, lookalike]: + assert connector.lookup_table(name).key_columns == ["id"] + with pytest.raises(ValueError, match="reserved"): + _ = connector.lookup_table(lease_name) check(client, holder) +def test_release_and_clear_keep_the_generation_sequence_contiguous( + client: fake.FakeClient, +) -> None: + first = acquire(client, _PROJECT, _DATASET, owner="first") + release(client, first) + second = acquire(client, _PROJECT, _DATASET, owner="second") + clear(client, second.table_id, confirm_writer_stopped=True) + third = acquire(client, _PROJECT, _DATASET, owner="third") + assert [ + client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(i)).resource_id + for i in range(1, 4) + ] == [first.table_id, second.table_id, third.table_id] + with pytest.raises(LeaseBusyError, match=third.table_id): + _ = acquire(client, _PROJECT, _DATASET, owner="fourth") + + def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="first") second = acquire(client, _PROJECT, "other", owner="second") From 2745f9a4b480cd33c8496cf9f8b6c9499c39036f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 10:40:53 -0800 Subject: [PATCH 07/50] fix(spiraldb): preserve tables with colliding lease names --- docs/dev/plans/itl-1838-spiraldb-lease.md | 11 +++--- src/orcapod/databases/spiraldb_connector.py | 38 +++++++++++++++------ src/orcapod/databases/spiraldb_lease.py | 19 ++++++----- src/orcapod/databases/store_table_names.py | 9 +++++ tests/test_databases/test_spiral_lease.py | 17 +++++++++ 5 files changed, 70 insertions(+), 24 deletions(-) diff --git a/docs/dev/plans/itl-1838-spiraldb-lease.md b/docs/dev/plans/itl-1838-spiraldb-lease.md index c11b3f545..eeb9ec3e8 100644 --- a/docs/dev/plans/itl-1838-spiraldb-lease.md +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -27,10 +27,13 @@ basedpyright, then open a PR against main and address CodeRabbit findings. Use `spiraldb_lease.acquire(client, project_id, dataset, owner=...)` before issuing any store writes. Pass the returned lease to `check(client, lease)` before writes and to `release(client, lease)` after all writes have finished. -Canonical numbered generation names are separate from record table names. The -connector skips generations as it reads listing pages and reserves those names -at direct lookup. The listing endpoint still returns generation entries in its -pages, so the service listing cost grows with the number of acquisitions. +Canonical numbered generation names are separate from record table names. If +an older table occupies a generation name without the lease key, acquisition +reports its table ID and leaves the table untouched. Listing and direct lookup +use the key signature to hide lease tables and preserve those older tables. +The listing endpoint still returns generations in its pages. The connector +opens each numbered candidate to verify its key and drops confirmed leases +from the page results. A refusal identifies the blocking table ID. To clear a stale lease, first stop the previous writer and ensure all outstanding writes have settled. Then call diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 2d9fbe17f..179206e70 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,7 +49,10 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path -from orcapod.databases.store_table_names import is_spiral_lease_table_name +from orcapod.databases.store_table_names import ( + is_spiral_lease_table_name, + spiral_lease_key_column, +) from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -458,11 +461,17 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, f"{base}?{urllib.parse.urlencode(query)}", native.access_token() ) # A page can be empty before the last one. - names.update( - (t["id"], t["table"]) - for t in page["items"] - if t["dataset"] == dataset and not is_spiral_lease_table_name(t["table"]) - ) + entries = cast("list[dict[str, str]]", page["items"]) + for entry in entries: + if entry["dataset"] != dataset: + continue + name = entry["table"] + table_id = entry["id"] + if is_spiral_lease_table_name(name): + keys: Sequence[str] = client.keyed_table_by_id(table_id).key_columns + if spiral_lease_key_column(keys) is not None: + continue + names[table_id] = name following = page.get("nextPageToken") if following is None: return names @@ -935,14 +944,12 @@ def _service_call(self, doing: str, table_name: str) -> Any: return _service_call(f"{doing} {self._qualified(table_name)}", self._health) def _require_user_table(self, table_name: str) -> None: - """Refuse names reserved for the dataset's internal tables.""" + """Refuse the reserved name of the dataset's schema table.""" if table_name == SCHEMA_TABLE: raise ValueError( f"{SCHEMA_TABLE!r} is reserved: it is where Orcapod keeps the schemas of " f"the tables of dataset {self._dataset!r}" ) - if is_spiral_lease_table_name(table_name): - raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. @@ -966,7 +973,11 @@ def get_table_names(self) -> list[str]: gone = sorted( row.table_name for i, row in recorded.items() - if i not in listed and not is_spiral_lease_table_name(row.table_name) + if i not in listed + and not ( + is_spiral_lease_table_name(row.table_name) + and spiral_lease_key_column(row.key_columns) is not None + ) ) if gone: _warn_once( @@ -987,7 +998,7 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. - ValueError: If the name is reserved for an internal table. + ValueError: If the table is an internal schema or lease table. """ self._require_open() self._require_user_table(table_name) @@ -1004,6 +1015,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: ) if table is None: raise SpiralDBTableNotFoundError(missing) + if ( + is_spiral_lease_table_name(table_name) + and spiral_lease_key_column(table.key_columns) is not None + ): + raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") return SpiralDBTable(self, table, table_name) def _recorded_schema( diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index eb9214f8f..0240aa498 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -3,7 +3,6 @@ from __future__ import annotations import os -import re from dataclasses import dataclass from datetime import datetime, timezone from typing import Protocol, cast @@ -12,11 +11,13 @@ import pyarrow as pa from orcapod.databases import spiraldb_connector as sdk -from orcapod.databases.store_table_names import spiral_lease_table_name +from orcapod.databases.store_table_names import ( + SPIRAL_LEASE_KEY_PREFIX, + spiral_lease_key_column, + spiral_lease_table_name, +) from orcapod.errors import OrcapodDatabaseError -_KEY_PREFIX = "orcapod_lease_v1_" -_KEY_PATTERN = re.compile(rf"{_KEY_PREFIX}[0-9a-f]{{32}}") _CLAIM = "claim" _RELEASED = "released" _CONFLICT = "remote service returned an unknown error (status 409)" @@ -151,12 +152,12 @@ def _newest( def _key(table: _KeyedTable) -> str: """Validate the reserved primary key before reading or mutating a lease.""" - keys = table.key_columns - if len(keys) != 1 or _KEY_PATTERN.fullmatch(keys[0]) is None: + key = spiral_lease_key_column(table.key_columns) + if key is None: raise LeaseError( - f"SpiralDB table ID {table.resource_id!r} is not a lease table" + f"SpiralDB table ID {table.resource_id!r} lacks the expected lease key" ) - return keys[0] + return key def _state(table: _KeyedTable, key: str) -> _State: @@ -233,7 +234,7 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le if not state.released: raise LeaseBusyError(dataset, latest.resource_id, state.owner) - key = f"{_KEY_PREFIX}{uuid4().hex}" + key = f"{SPIRAL_LEASE_KEY_PREFIX}{uuid4().hex}" row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) claimed = _claim_generation(client, project_id, dataset, generation + 1, key) if _key(claimed) != key: diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 36ba4f30a..bae698b4a 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -11,8 +11,10 @@ """The digest algorithm shared with SpiralDB. The name's grammar carries its version.""" STORE_TABLE_NAME_PREFIX = "o1_" +SPIRAL_LEASE_KEY_PREFIX = "orcapod_lease_v1_" _SPIRAL_LEASE_TABLE_PREFIX = "orcapod_lease_v1_g" _SPIRAL_LEASE_TABLE_PATTERN = re.compile(rf"{_SPIRAL_LEASE_TABLE_PREFIX}[1-9][0-9]*") +_SPIRAL_LEASE_KEY_PATTERN = re.compile(rf"{SPIRAL_LEASE_KEY_PREFIX}[0-9a-f]{{32}}") def spiral_lease_table_name(generation: int) -> str: @@ -25,6 +27,13 @@ def is_spiral_lease_table_name(name: str) -> bool: return _SPIRAL_LEASE_TABLE_PATTERN.fullmatch(name) is not None +def spiral_lease_key_column(keys: Sequence[str]) -> str | None: + """Return the key bearing the lease signature, when present.""" + if len(keys) == 1 and _SPIRAL_LEASE_KEY_PATTERN.fullmatch(keys[0]) is not None: + return keys[0] + return None + + def store_table_path_json(path: Sequence[str]) -> bytes: """Encode the full store path as a compact UTF-8 JSON array. diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 1a3cee624..a72c5e04f 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -235,6 +235,23 @@ def test_release_and_clear_keep_the_generation_sequence_contiguous( _ = acquire(client, _PROJECT, _DATASET, owner="fourth") +def test_preexisting_table_with_generation_name_remains_accessible( + client: fake.FakeClient, +) -> None: + name = spiral_lease_table_name(1) + table = client.project(_PROJECT).create_keyed_table( + _DATASET, name, pa.schema([pa.field("id", pa.int64())]) + ) + with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + assert connector.get_table_names() == [name] + assert connector.lookup_table(name).key_columns == ["id"] + with pytest.raises(LeaseError, match=table.resource_id): + _ = acquire(client, _PROJECT, _DATASET, owner="writer") + with pytest.raises(LeaseError, match=table.resource_id): + clear(client, table.resource_id, confirm_writer_stopped=True) + assert client.keyed_table_by_id(table.resource_id).version_id == table.version_id + + def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="first") second = acquire(client, _PROJECT, "other", owner="second") From cdfa2e64004a1c123933edea2085b58136245649 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 10:51:30 -0800 Subject: [PATCH 08/50] fix(spiraldb): keep plain-field extension metadata; one store path domain (ITL-1837) Independent review of #691, round 1: - A plain field's ARROW:extension:metadata (no extension name) was dropped by the codec; it names no type, so it is now kept exactly. The manifest already records it behind its mark. - The identity record and the manifest accepted and refused different full paths. store_table_names.require_store_path_domain states the domain once (at least one component; each a non-empty UTF-8 string without '/' or NUL, as every Orcapod database requires), and both writers and both readers apply it. - The plan's spiral-sdk pin rationale is corrected: get_metadata appears in 0.16.76, set_metadata in 0.16.77; 0.16.78 is kept as the measured release before the 0.16.79 keyed-table deprecation. - The 8,000-byte chunk boundary is pinned by a test. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1837.md | 4 +- ...026-12-01-itl-1837-spiral-store-stage-a.md | 13 ++- src/orcapod/databases/spiral_store.py | 39 ++++++--- .../databases/spiral_store_identity.py | 12 ++- src/orcapod/databases/store_table_names.py | 38 +++++++++ tests/test_databases/test_spiral_store.py | 77 ++++++++++++++++- .../test_spiral_store_identity.py | 84 ++++++++++++++++++- 7 files changed, 240 insertions(+), 27 deletions(-) diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md index c883c9105..0079b1198 100644 --- a/changelog.d/ITL-1837.md +++ b/changelog.d/ITL-1837.md @@ -1,7 +1,7 @@ ### Changed -- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), the release that reads - and writes a SpiralDB table's own metadata. 0.16.79 is not used: it deprecates the keyed +- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), a release that reads + and writes a SpiralDB table's own metadata (the one it was measured with). 0.16.79 is not used: it deprecates the keyed tables Orcapod reads, with a warning on every open. Orcapod still only reads SpiralDB. (ITL-1837) diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md index 6bffdec0f..b94966b44 100644 --- a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -19,10 +19,15 @@ and what to do with draft tables is decided then. No golden value pins any of it ## 1. spiral-sdk 0.16.78 -Table metadata (`KeyedTable.get_metadata` / `set_metadata`) exists from 0.16.78. Compared -with `main`'s 0.16.74, the Python layer of 0.16.78 changes only those two methods (and the -generated service schemas); the snapshot pinning (`keyed_table_by_id(..., asof=)`), -projection (`scan(columns=)`) and key ranges `main` uses are untouched there. +Table metadata arrives in two steps: `KeyedTable.get_metadata` first appears in 0.16.76, +and `set_metadata` in 0.16.77 (neither is in 0.16.74 or 0.16.75). The Python files of +0.16.77 and 0.16.78 are identical; only their native libraries differ. 0.16.78 is kept +because it is the release the table metadata, the type rules and the entry limits were +measured with (live, 2026-11-26), and it is the last release before the keyed-table +deprecation of 0.16.79. Compared with `main`'s 0.16.74, the Python layer of 0.16.78 changes +only those two methods (and the generated service schemas); the snapshot pinning +(`keyed_table_by_id(..., asof=)`), projection (`scan(columns=)`) and key ranges `main` uses +are untouched there. 0.16.79 (2026-11-27) is newer but not chosen: it marks keyed tables deprecated, and `Client.keyed_table`, `keyed_table_by_id` and `Project.create_keyed_table` each issue a diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index c43c7855a..c6e91e5e5 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -46,6 +46,7 @@ import pyarrow as pa import pyarrow.compute as pc +from orcapod.databases.store_table_names import require_store_path_domain from orcapod.databases.utils import identity_node from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, @@ -219,11 +220,20 @@ def error(self) -> UnstorableInSpiralError: # -------------------------------------------------------------- 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.""" +def _recorded_metadata( + field: pa.Field[Any], identifier: tuple[bytes, bytes] | None +) -> dict[bytes, bytes]: + """The field's metadata as the manifest records it. + + A logical type's identifier replaces the two keys that hold one. A plain field (no + identifier) keeps its metadata exactly, an ``ARROW:extension:metadata`` entry with + no extension name included: that entry names no type, so it is the user's. + """ metadata = dict(field.metadata or {}) - _ = metadata.pop(EXTENSION_NAME_KEY, None) - _ = metadata.pop(EXTENSION_METADATA_KEY, None) + if identifier is not None: + _ = metadata.pop(EXTENSION_NAME_KEY, None) + _ = metadata.pop(EXTENSION_METADATA_KEY, None) + metadata[EXTENSION_NAME_KEY], metadata[EXTENSION_METADATA_KEY] = identifier return metadata @@ -249,9 +259,7 @@ def _logical_field(field: pa.Field[Any]) -> pa.Field[Any]: 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 + metadata = _recorded_metadata(field, node.identifier) return pa.field( field.name, arrow_utils.normalize_to_large_types(arrow_type, keep_null=True), @@ -830,13 +838,14 @@ def new_manifest( The manifest. Raises: - UnstorableInSpiralError: If the schema cannot be stored, or a path component is - not UTF-8 or holds ``/`` or NUL. + UnstorableInSpiralError: If the schema cannot be stored, or the path is outside + the store path domain (``store_table_names.require_store_path_domain``, + which the table's identity record applies too). """ - for part in record_path: - _require_utf8(part) - if "/" in part or "\0" in part: - raise UnstorableInSpiralError(f"the path component {part!r}") + try: + _ = require_store_path_domain(record_path) + except ValueError as exc: + raise UnstorableInSpiralError(str(exc)) from exc _require_utf8(kind) return StoreManifest( record_path, kind, logical_schema(schema), physical_schema(schema) @@ -926,6 +935,10 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM raise ManifestError("the record path is not a list of strings") if not isinstance(kind, str): raise ManifestError("the kind is not text") + try: + _ = require_store_path_domain(cast("list[str]", path)) + except ValueError as exc: + raise ManifestError(f"the recorded path is not a store path: {exc}") from exc if tuple(cast("list[str]", path)) != record_path: raise ManifestError( f"the table is recorded as {path}, not as {list(record_path)}" diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py index ba4510410..a70a4f3b2 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_store_identity.py @@ -25,6 +25,7 @@ from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, + require_store_path_domain, store_table_name, store_table_path_json, table_name_hint, @@ -132,10 +133,12 @@ def store_table_metadata( data_context_key: The data context of the writer creating the table. Raises: - ValueError: If the path cannot be named, the data context key is empty, or an - entry is over SpiralDB's entry limit (``MAX_METADATA_ENTRY_BYTES``). + ValueError: If the path is outside the store path domain + (``store_table_names.require_store_path_domain``), the data context key is + empty, or an entry is over SpiralDB's entry limit + (``MAX_METADATA_ENTRY_BYTES``). """ - path_json = store_table_path_json(path) + path_json = store_table_path_json(require_store_path_domain(path)) if not data_context_key: raise ValueError("a store table records the data context that created it") record = { @@ -192,7 +195,8 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord ) components = tuple(cast("list[str]", items)) try: - _ = store_table_path_json(components) # what a writer refuses, a reader refuses + # What a writer refuses, a reader refuses. + _ = require_store_path_domain(components) except ValueError as exc: raise SpiralStoreTableCollisionError( f"its path cannot be named: {exc}" diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 96f05453e..8b5fe00fb 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -12,6 +12,44 @@ STORE_TABLE_NAME_PREFIX = "o1_" +def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: + """Refuse a full path that no store keeps; the one statement of the path domain. + + A store table's full path is at least one component, and every component is a + non-empty string with a UTF-8 form that holds neither ``/`` nor NUL: the rule + every Orcapod database applies to a record path (the connector, in-memory and + Delta stores split a key at ``/``). Every writer and reader of a SpiralDB store + table's identity record and manifest applies it, so they accept and refuse the same + paths. Naming (``store_table_path_json``) encodes any path of strings. + + Args: + path: The store's base path followed by its record path. + + Returns: + The path, as a tuple. + + Raises: + ValueError: If the path is outside the domain, naming the component. + """ + components = tuple(path) + if not components: + raise ValueError("a store table path has at least one component") + for component in components: + if type(component) is not str or not component: + raise ValueError(f"a store table path component is {component!r}") + if "/" in component or "\0" in component: + raise ValueError( + f"a store table path component holds '/' or NUL: {component!r}" + ) + try: + _ = component.encode() + except UnicodeEncodeError as exc: + raise ValueError( + f"a store table path component is not UTF-8 text: {component!r}" + ) from exc + return components + + def store_table_path_json(path: Sequence[str]) -> bytes: """Encode the full store path as a compact UTF-8 JSON array. diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py index 1ee252c49..733d4a842 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_store.py @@ -1157,7 +1157,7 @@ def wide_schema(columns: int = 200) -> pa.Schema: def test_a_manifest_of_200_columns_with_metadata() -> None: schema = wide_schema() assert len(schema) == 200 - path = ("run", "a", "b", "", "é", '"', "\u2028") + path = ("run", "a", "b", " ", "é", '"', "\u2028") recorded = entries(schema, path) assert recorded.isascii() manifest = read(recorded, path) @@ -1594,3 +1594,78 @@ def test_a_dictionary_of_a_logical_types_values_is_refused_as_unstorable( for call in (store.physical_schema, store.logical_schema, entries): with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): _ = call(schema) + + +# ------------------------------- independent review of PR 691 (10ac3d07d), round 1 + + +def test_extension_metadata_without_a_name_round_trips_through_chunks() -> None: + """Finding 1: ``ARROW:extension:metadata`` on a plain field (no extension name) names + no type; it is kept exactly, at the top of a column and nested, through the chunked + manifest and the rows.""" + plain = {b"ARROW:extension:metadata": b"preserve"} + inner = pa.field("a", pa.int64(), True, {b"ARROW:extension:metadata": b"inner"}) + schema = schema_of( + [ + (KEY, pa.large_binary()), + pa.field("x", pa.int64(), True, plain), + pa.field("y", pa.large_string(), True, {**plain, b"note": b"n"}), + pa.field("s", pa.struct([inner]), True), + ] + ) + rows = pa.Table.from_arrays( + [ + pa.array([b"k", b"j"], pa.large_binary()), + pa.array([1, None]), + pa.array(["a", "b"], pa.large_string()), + pa.array([{"a": 1}, {"a": None}], schema.field("s").type), + ], + schema=schema, + ) + loaded = store.read_manifest(store.manifest_entries(new(schema)), PATH) + assert loaded is not None + assert loaded.schema.equals(schema, check_metadata=True) + got = store.decode_rows(store.encode_rows(rows), loaded) + assert got.schema.equals(schema, check_metadata=True) + assert got.schema.field("x").metadata == plain + assert got.to_pylist() == rows.to_pylist() + # The entry counts in a comparison: a schema without it is another schema. + without = schema.set(1, pa.field("x", pa.int64())) + assert store.schema_difference(loaded.schema, without) is not None + + +@pytest.mark.parametrize("target", [7_999, 8_000, 8_001, 15_999, 16_000, 16_001]) +def test_the_manifest_is_cut_every_8000_bytes(target: int) -> None: + """Finding 4: the chunk boundary is part of the format. A payload of exactly + ``target`` bytes (the free-text kind pads it) is cut into 8,000-byte chunks, the + header's digest is the SHA-256 of the whole payload, it reads back whatever order + the metadata comes in, and a missing or modified last chunk is refused.""" + import hashlib + + schema = schema_of(BASE) + base = len(store.manifest_bytes(store.new_manifest(PATH, "", schema))) + manifest = store.new_manifest(PATH, "k" * (target - base), schema) + payload = store.manifest_bytes(manifest) + assert len(payload) == target + entries_ = store.manifest_entries(manifest) + count = -(-target // 8_000) + chunks = [entries_[f"{store.MANIFEST_KEY}/{i}"] for i in range(count)] + assert [len(c) for c in chunks] == [8_000] * (count - 1) + [ + target - 8_000 * (count - 1) + ] + assert set(entries_) == { + store.MANIFEST_KEY, + *(f"{store.MANIFEST_KEY}/{i}" for i in range(count)), + } + header = json.loads(entries_[store.MANIFEST_KEY]) + assert header["chunks"] == count + assert header["payload_digest"] == hashlib.sha256(payload).hexdigest() + assert b"".join(chunks) == payload + backwards = dict(reversed(list(entries_.items()))) + assert store.read_manifest(backwards, PATH) == manifest + last = f"{store.MANIFEST_KEY}/{count - 1}" + missing = {k: v for k, v in entries_.items() if k != last} + modified = {**entries_, last: entries_[last][:-1] + b"#"} + for broken in (missing, modified): + with pytest.raises(store.ManifestError): + _ = store.read_manifest(broken, PATH) diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_store_identity.py index b63217fe4..f051033c2 100644 --- a/tests/test_databases/test_spiral_store_identity.py +++ b/tests/test_databases/test_spiral_store_identity.py @@ -11,8 +11,10 @@ import random import re +import pyarrow as pa import pytest +from orcapod.databases import spiral_store from orcapod.databases import spiral_store_identity as names from orcapod.databases import store_table_names @@ -225,15 +227,15 @@ def test_a_recorded_path_that_writers_refuse_is_refused_on_read() -> None: def test_the_collision_message_keeps_components_apart() -> None: - # Review of PR 589, finding 4: ("a/b", ...) and ("a", "b", ...) must read differently. + # 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") + names.store_table_metadata(("a b", "rdb_v1"), "std:v1:default") ) assert found is not None with pytest.raises(names.SpiralStoreTableCollisionError) as raised: names.require_store_table_path(found, ("a", "b", "rdb_v1")) - assert "['a/b', 'rdb_v1']" in str(raised.value) + assert "['a b', 'rdb_v1']" in str(raised.value) assert "['a', 'b', 'rdb_v1']" in str(raised.value) @@ -279,3 +281,79 @@ def test_the_collision_error_names_the_table_its_caller_gives() -> None: placed = names.SpiralStoreTableCollisionError("x", table="p/d/o1_t") assert str(placed) == "table p/d/o1_t: not this store's table: x" assert (placed.reason, placed.table) == ("x", "p/d/o1_t") + + +# ------------------------------- independent review of PR 691 (10ac3d07d), round 1 + +_OUTSIDE = [ + (), + ("",), + ("base", "", "rdb_v1"), + ("base/part", "rdb_v1"), + ("base", "a\0b", "rdb_v1"), + ("\udc00", "rdb_v1"), + ("base", 1, "rdb_v1"), +] +_INSIDE = [ + ("rdb_v1",), + ("base", "part", "rdb_v1"), + ("run", " ", "é", '"', "\u2028", "a.b:c", "pdb_v2"), +] + + +def _schema() -> pa.Schema: + return pa.schema( + [ + pa.field(spiral_store.KEY_COLUMN, pa.large_binary(), False), + pa.field("x", pa.int64()), + ] + ) + + +def _manifest_payload(path: object) -> bytes: + """A manifest payload recording ``path``, as a writer outside the domain would.""" + body = json.loads( + spiral_store.manifest_bytes( + spiral_store.new_manifest(("ok", "rdb_v1"), "k", _schema()) + ) + ) + body["record_path"] = path + return json.dumps(body).encode() + + +@pytest.mark.parametrize("path", _OUTSIDE) +def test_the_record_and_the_manifest_refuse_the_same_paths( + path: tuple[object, ...], +) -> None: + """Finding 2: the identity record and the manifest refuse one path domain + (``store_table_names.require_store_path_domain``), on write and on read.""" + with pytest.raises(ValueError, match="path"): + _ = store_table_names.require_store_path_domain(path) # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(ValueError, match="path"): + _ = names.store_table_metadata(path, "std:v1:default") # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(spiral_store.UnstorableInSpiralError): + _ = spiral_store.new_manifest(path, "k", _schema()) # pyright: ignore[reportArgumentType] # refused on purpose + record = { + **names.store_table_metadata(RESULT, "std:v1:default"), + "orcapod.path": json.dumps(list(path)).encode(), + "orcapod.layout": (str(path[-1]) if path else "").encode("utf-8", "replace"), + } + with pytest.raises(names.SpiralStoreTableCollisionError): + _ = names.read_store_table_metadata(record) + with pytest.raises(spiral_store.ManifestError): + _ = spiral_store.read_manifest_bytes(_manifest_payload(list(path)), path) # pyright: ignore[reportArgumentType] # refused on purpose + + +@pytest.mark.parametrize("path", _INSIDE) +def test_the_record_and_the_manifest_accept_the_same_paths( + path: tuple[str, ...], +) -> None: + """Finding 2: a path inside the domain is written and read back by both.""" + assert store_table_names.require_store_path_domain(path) == path + found = names.read_store_table_metadata( + names.store_table_metadata(path, "std:v1:default") + ) + assert found is not None and found.path == path + manifest = spiral_store.new_manifest(path, "k", _schema()) + entries = spiral_store.manifest_entries(manifest) + assert spiral_store.read_manifest(entries, path) == manifest From 384426d1eeaea03fa89e1b97e385eaca59818873 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 10:51:45 -0800 Subject: [PATCH 09/50] feat(spiraldb): internal store mode under ConnectorArrowDatabase (ITL-1840) Stage B of the SpiralDB store (ITL-1446), carried from PR 595 onto current main's database structure: - spiraldb_store_tables: a store's tables, named from their full paths, identity and manifest in table metadata, rows through the codec; tables that are not the store's refused; data-context checks before rows are buffered and again at flush; listing by recorded paths for the stale-layout check; existing_record_ids by one key-range read. - SpiralDBConnector(_store=True), private: raw reads are refused in store mode, writes on the connector itself still raise, and it is not saved. - ConnectorArrowDatabase gets an internal store branch beside _sql_store (no new protocol methods). Main's rules of ITL-1386 hold: a stored or pending id raises unless skip_duplicates, and a flush never overwrites a stored row. A plain SpiralDBConnector behaves as on main. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1840.md | 7 + .../databases/connector_arrow_database.py | 146 ++- src/orcapod/databases/spiraldb_connector.py | 62 +- .../databases/spiraldb_store_tables.py | 723 +++++++++++ .../test_spiraldb_store_mode.py | 1056 +++++++++++++++++ 5 files changed, 1984 insertions(+), 10 deletions(-) create mode 100644 changelog.d/ITL-1840.md create mode 100644 src/orcapod/databases/spiraldb_store_tables.py create mode 100644 tests/test_databases/test_spiraldb_store_mode.py diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md new file mode 100644 index 000000000..ff7af217c --- /dev/null +++ b/changelog.d/ITL-1840.md @@ -0,0 +1,7 @@ +### Known limitations + +- Orcapod still cannot use SpiralDB as a job's database: a `SpiralDBConnector` refuses + every write. An internal store mode now writes and reads every stored table kind + through `ConnectorArrowDatabase` (one table per path, its identity and manifest in the + table's metadata), but nothing opens it publicly, it is not saved with a job, and its + format stays provisional, outside the 0.4.0 freeze. (ITL-1840) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 87d259f7d..e79334266 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -23,7 +23,7 @@ from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext from threading import Lock -from typing import Any, cast +from typing import TYPE_CHECKING, Any, cast from weakref import WeakKeyDictionary, WeakValueDictionary import pyarrow as pa @@ -42,6 +42,8 @@ stored_path, ) from orcapod.databases.postgresql_connector import PostgreSQLConnector +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, store_table_name, @@ -69,6 +71,11 @@ normalize_to_large_types, ) +if TYPE_CHECKING: + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverterProtocol, + ) + #: The ``type`` of a connector database's saved configuration. CONNECTOR_DATABASE_TYPE = "connector_arrow_database" @@ -107,6 +114,54 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] +def _with_live_logical_types(records: pa.Table) -> pa.Table: + """Return ``records`` with every registered logical type given in storage form live. + + For a SpiralDB store only (ITL-1840): its manifest records one form of each column. + A column in storage form carries its identifier as ``ARROW:extension:*`` field + metadata. When the default data context's type converter has the type registered, + the column is wrapped as that live type, the form the store reads back, so one + column is compared in one form. Any other column, an identifier no type is + registered for included, is kept exactly as given: nothing is registered here. + """ + from orcapod.contexts import get_default_context + + # The context's converter implements the logical-type side of + # ``logical_types.protocols.TypeConverterProtocol`` (as Delta's read uses it). + converter = cast( + "LogicalTypeConverterProtocol", + cast(object, get_default_context().type_converter), + ) + + def registered(name: bytes) -> bool: + try: + text = name.decode() + except UnicodeDecodeError: + return False # no type is registered under bytes: kept as given + return converter.get_logical_type_by_arrow_extension_name(text) is not None + + known = [ + i + for i, field in enumerate(records.schema) + if (name := (field.metadata or {}).get(b"ARROW:extension:name")) is not None + and registered(name) + ] + if not known: + return records + wrapped = converter.apply_logical_types(records.select(known)) + for i, position in enumerate(known): + field = wrapped.schema.field(i) + metadata = dict(field.metadata or {}) + if isinstance(field.type, pa.BaseExtensionType): + # A wrapped column states its identifier in its type: not in metadata too. + _ = metadata.pop(b"ARROW:extension:name", None) + _ = metadata.pop(b"ARROW:extension:metadata", None) + records = records.set_column( + position, field.with_metadata(cast(Any, metadata)), wrapped.column(i) + ) + return records + + def _alike(parts: list[pa.Table]) -> list[pa.Table]: """Stored and queued rows under one schema when they differ only in a column's nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary @@ -144,6 +199,11 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. + A ``SpiralDBConnector`` opened in store mode (private, ITL-1840) is read and + written through its store tables (``spiraldb_store_tables``): names computed from + the full path, identity and manifest in each table's metadata, rows through the + store codec. A plain ``SpiralDBConnector`` refuses every write, as before. + Args: connector: A ``DBConnectorProtocol`` implementation providing the underlying DB access (connection, type mapping, queries, writes). @@ -174,6 +234,13 @@ def __init__( self._sql_store: SQLStoreConnector | None = ( connector if isinstance(connector, SQLStoreConnector) else None ) + # A SpiralDB connector in store mode; ``None`` for any other (ITL-1840). + self._spiral_connector: SpiralDBConnector | None = ( + connector + if isinstance(connector, SpiralDBConnector) + and connector._store_tables() is not None # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + else None + ) self.max_hierarchy_depth = max_hierarchy_depth self._path_prefix = _path_prefix self._root = _root @@ -225,6 +292,17 @@ def __init__( connector, self._pending_commits ) + @property + def _spiral(self) -> StoreTables | None: + """The SpiralDB store's tables, or ``None`` for any other connector. + + Raises: + RuntimeError: If the store's connector has been closed. + """ + if self._spiral_connector is None: + return None + return self._spiral_connector._store_tables() # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + def _discard_pending_state(self, key: str) -> None: """Forget indexes when an entire queued batch is discarded.""" self._pending_skip_existing.pop(key, None) @@ -237,6 +315,8 @@ def _discard_pending_state(self, key: str) -> None: def _get_record_key(self, record_path: tuple[str, ...]) -> str: full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: + if self._spiral_connector is not None: + self._validate_path_components(full_path) return "/".join(full_path) self._validate_path_components(full_path) return f"{self._sql_store.get_current_store_schema()}\0{'/'.join(full_path)}" @@ -261,6 +341,8 @@ def _schema_from_record_key(self, record_key: str) -> str | None: def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: """Map a full record path to a name the connector can store.""" + if (store := self._spiral) is not None: + return store.table_name(self._plain_path(record_path)) if self._sql_store is not None and record_path: return store_table_name( self._plain_path(record_path), @@ -351,6 +433,8 @@ def _find_committed_table( self, table_name: str, full_path: tuple[str, ...], *, schema: str | None ) -> tuple[str | None, str] | None: """Return the verified schema and name of a committed table.""" + if (store := self._spiral) is not None: + return (None, table_name) if store.has_table(table_name) else None if self._sql_store is None: if table_name in self._connector.get_table_names(): return None, table_name @@ -377,6 +461,9 @@ def _get_committed_table( if table is None: return None schema, name = table + if (store := self._spiral) is not None: + batches = list(store.scan(name)) + return pa.Table.from_batches(batches) if batches else None batches = list( self._connector.iter_batches( f"SELECT * FROM {sql_table_identifier(name, schema)}" @@ -392,6 +479,8 @@ def _stored_conflicts( """Return input IDs found in the committed table.""" schema, name = table column = self.RECORD_ID_COLUMN + if (store := self._spiral) is not None: + return store.existing_record_ids(name, input_ids) if self._sql_store is not None: assert schema is not None return self._sql_store.existing_record_ids( @@ -413,6 +502,15 @@ 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 + if (store := self._spiral) is not None: + full_prefix = self._plain_path(full_prefix) + pending = [self._record_path_from_key(key) for key in self._pending_batches] + return sorted( + { + path[len(self._path_prefix) :] + for path in store.table_paths(full_prefix, pending) + } + ) if self._sql_store is not None: full_prefix = self._plain_path(full_prefix) stem = STORE_TABLE_NAME_PREFIX + table_name_hint( @@ -531,12 +629,17 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column the connector cannot store, naming the connector, the column, its Arrow type and why. """ + store = self._spiral for field in schema: - reason = self._connector.unstorable_column_reason( - field.name, - field.type, - primary_key=field.name == self.RECORD_ID_COLUMN, - ) + primary_key = field.name == self.RECORD_ID_COLUMN + if store is not None: + reason = store.unstorable_column_reason( + field.name, field.type, primary_key + ) + else: + reason = self._connector.unstorable_column_reason( + field.name, field.type, primary_key=primary_key + ) if reason is not None: raise UnstorableColumnError( database_kind=type(self._connector).__name__, @@ -601,6 +704,9 @@ def validate_records(self, records: pa.Table) -> None: Args: records: The rows (any number, none included) to check. """ + if (store := self._spiral) is not None: + store.validate(records, None) + return self._connector.validate_records(records) def add_records( @@ -652,7 +758,14 @@ def add_records( table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) records = normalize_table_to_large_types(records, keep_null=True) - self._connector.validate_records(records) + if (store := self._spiral) is not None: + # A logical type given in its storage form is the same column as one given + # live: compared, buffered and stored in one form. The rows' data context + # is checked against the one the table records, before they are buffered. + records = _with_live_logical_types(records) + store.validate(records, table_name) + else: + self._connector.validate_records(records) record_key = self._get_record_key(record_path) committed_table = None @@ -770,6 +883,8 @@ def _held_column_order( def _column_info(self, table_name: str, schema: str | None) -> list[ColumnInfo]: """Inspect the relation selected by the catalog when a schema was verified.""" + if (store := self._spiral) is not None: + return store.column_info(table_name) if self._sql_store is not None: return self._sql_store.get_column_info(table_name, schema=schema) return self._connector.get_column_info(table_name) @@ -859,6 +974,8 @@ def _read_stored_schema( Read without rows from a connector that offers ``get_arrow_schema`` (``SpiralDBConnector``); from any other, the schema of its first batch. """ + if (store := self._spiral) is not None: + return store.arrow_schema(table_name) get_arrow_schema = getattr(self._connector, "get_arrow_schema", None) if callable(get_arrow_schema): return cast("pa.Schema", get_arrow_schema(table_name)) @@ -983,7 +1100,9 @@ def _flush_by_key(self, record_key: str) -> None: record_path = self._record_path_from_key(record_key) table_name = self._path_to_table_name(record_path) self._require_table_name(table_name) - if self._sql_store is None: + if (store := self._spiral) is not None: + transaction = nullcontext((None, store.has_table(table_name))) + elif self._sql_store is None: transaction = nullcontext( (None, table_name in self._connector.get_table_names()) ) @@ -1033,6 +1152,11 @@ def _write_ready_batch( schema: str | None, ) -> None: """Check the current schema and write the ready rows.""" + store = self._spiral + if store is not None: + # The rows against the table as it is now: it may have been made since + # they were buffered, recording another data context. + store.validate(pending, table_name) columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). existing = self._stored_columns(table_name, schema) if table_exists else None @@ -1074,7 +1198,11 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # Another writer can commit an ID after it was checked at add time. # Use the connector's atomic insert-if-missing for both modes. - if self._sql_store is None: + if store is not None: + # Writes only the keys the table does not hold: a stored row is never + # overwritten (SpiralDB's append replaces a row of the same key). + store.write(table_name, pending) + elif self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 61e695bd9..1bb717132 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,6 +49,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -881,6 +882,11 @@ 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``), for + ``ConnectorArrowDatabase``: tables named from their paths, rows through the + store codec. Private until the store is switched on (ITL-1446): such a + connector is not saved, and its tables are read and written only through + ``ConnectorArrowDatabase``. """ def __init__( @@ -888,6 +894,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 @@ -911,6 +919,24 @@ def __init__( lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), _kept_rows_for(_api_url(overrides), project_id, dataset), ) + # Kept after ``close`` releases the store's tables, so a closed store connector + # never acts as a plain one. + self._store_mode = _store + self._store: StoreTables | None = None + if _store: + self._store = StoreTables( + client, + sp, + project_id, + dataset, + lambda name: _open_keyed_table( + client, project_id, dataset, name, health + ), + lambda: _list_keyed_tables(client, project_id, dataset), + lambda doing: _service_call( + f"{doing} of {project_id}/{dataset}", health + ), + ) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" @@ -918,6 +944,27 @@ def _require_open(self) -> None: raise RuntimeError("SpiralDBConnector is closed") require_same_process(self._pid) + def _store_tables(self) -> StoreTables | None: + """The store's tables, or ``None`` on a plain connector. + + For ``ConnectorArrowDatabase``, the only reader and writer of a store's tables. + + Raises: + RuntimeError: If this is a store-mode connector and it has been closed. + """ + if not self._store_mode: + return None + self._require_open() + return self._store + + def _refuse_in_store_mode(self) -> None: + """Refuse an operation on raw tables of a store-mode connector.""" + if self._store_mode: + raise ValueError( + "a store-mode SpiralDB connector reads and writes its tables through " + "ConnectorArrowDatabase only, never as raw tables" + ) + def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope.""" self._require_open() @@ -952,6 +999,7 @@ def get_table_names(self) -> list[str]: Sorted list of plain table name strings (no ``dataset.`` prefix). """ self._require_open() + self._refuse_in_store_mode() with self._service_call("list the tables of", "*"): listed = _list_keyed_tables(self._client, self._project_id, self._dataset) with _about_table(f"{self._project_id}/{self._dataset}"): @@ -978,9 +1026,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. - ValueError: If the name is the schema table's. + ValueError: If the name is the schema table's, or this connector is in store + mode. """ self._require_open() + self._refuse_in_store_mode() self._require_user_table(table_name) missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}" if ( @@ -1119,6 +1169,7 @@ def iter_batches( non-nullable column (naming the table and the column). """ self._require_open() + self._refuse_in_store_mode() if params is not None: logger.warning( "SpiralDBConnector does not support query parameters; " @@ -1329,6 +1380,9 @@ def close(self) -> None: del self._client del self._shared del self._schemas + # The store's tables hold the client too; a connector from + # ``share_client`` keeps its own reference to them. + self._store = None def __enter__(self) -> SpiralDBConnector: return self @@ -1345,7 +1399,13 @@ def to_config(self) -> dict[str, Any]: Raises: RuntimeError: If this connector has been closed. + ValueError: If this connector is in store mode, which is not saved yet. """ + if self._store_mode: + raise ValueError( + "a store-mode SpiralDB connector is not saved: the store is not " + "switched on yet (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..dc25ad86e --- /dev/null +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -0,0 +1,723 @@ +"""The tables of a SpiralDB pipeline store, one dataset's (ITL-1840). + +What ``ConnectorArrowDatabase`` does with the tables of a ``SpiralDBConnector`` opened in +store mode (a private constructor argument: nothing about the store is public yet). The +design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried +from PR 595 onto ``main``'s database structure. + +- A table's name is computed from its full record path (``spiral_store_identity``); 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 rows (a + creation that stopped before its first rows) is new to any first writer. +- Rows are encoded on write and decoded on read by the codec; a read gives the logical + columns, logical types live. +- Which of a set of record ids a table holds is answered by key: one read of the key + column over the range of the asked ids (``existing_record_ids``). +- 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). + +One writer at a time, and no lease yet (ITL-1452): a first write re-reads the table just +before recording it and never overwrites what that read shows, but without a +compare-and-set two concurrent writers can still race in between. +""" + +from __future__ import annotations + +from collections.abc import Callable, Collection, Iterator, Mapping +from contextlib import AbstractContextManager +from dataclasses import dataclass +from typing import Any, Protocol, cast + +import pyarrow as pa +import pyarrow.compute as pc + +import orcapod.databases.spiral_store as codec +import orcapod.databases.spiral_store_identity as identity +from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +from orcapod.errors import InputValidationError +from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.system_constants import constants +from orcapod.types import ColumnInfo + +DATA_CONTEXT_COLUMN = constants.DATA_CONTEXT_COL +"""The column every stored row's data context is in.""" + + +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 schema(self) -> pa.Schema: ... + + def get_metadata(self) -> dict[str, bytes]: ... + + def set_metadata(self, metadata: dict[str, bytes]) -> None: ... + + def scan( + self, + columns: list[str] | None = None, + *, + filter: Any = None, # pyright: ignore[reportExplicitAny] # an SDK expression + 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 holds rows, with what its metadata records.""" + + table_id: str + record: identity.StoreTableRecord + manifest: codec.StoreManifest + + +class StoreTables: + """The store tables of one SpiralDB dataset. + + Args: + client: A spiral-sdk client. + sdk: The spiral-sdk module (its error class and scan expressions). + 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, + sdk: Any, # pyright: ignore[reportExplicitAny] # the optional spiral-sdk module + 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._sdk: Any = sdk # pyright: ignore[reportExplicitAny] + 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, identity.StoreTableRecord] = {} + # What each table recorded when it was last judged new (``_seen_manifest``): a + # first write may record a table only as it was then. + self._judged: dict[str, _Seen] = {} + # Tables last judged to exist with no rows: new to a writer, and read as no rows. + self._empty: set[str] = set() + + key_column: str = codec.KEY_COLUMN + """The key column of every store table.""" + + 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, table_name: str | None) -> None: + """Check rows to buffer: their one data context, the one the table at + ``table_name`` records when it holds rows (``None``: no table in particular), + and the codec on the last row of each key, as kept. + + Raises: + ValueError: If the rows hold no data context column, a null or several + values in it. + InputValidationError: If the data context is not one this Orcapod has, + or not the table's. + UnstorableInSpiralError: If the codec refuses the rows. + """ + if records.num_rows == 0: + return + context = _one_data_context(records) + if table_name is not None: + found = self._judge(table_name) + if found is not None: + _require_data_context(found, context) + _ = 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. + + Raises: + ValueError: If the path cannot be named. + """ + name = identity.spiral_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 new: no rows yet, with or without a record (spec 2.5: any first + writer records it again). Only a found table is kept. + + Raises: + SpiralStoreTableCollisionError: If the table's key is not the store's, it + records another path or format, or it 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: + self._judged[table_name] = ("none", None) + self._empty.discard(table_name) + return None + self._require_key(table, table_name) + with self._service_call(f"read the metadata of {table_name}"): + metadata = table.get_metadata() + try: + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + except SpiralStoreTableCollisionError as exc: + raise SpiralStoreTableCollisionError( + exc.reason, table=self._qualified(table_name) + ) from exc + if not self._holds_rows(table): + # New: its first write records it, unless what it saw here changed. + self._judged[table_name] = _seen_manifest(metadata, path) + self._empty.add(table_name) + return None + try: + manifest = None if record is None else codec.read_manifest(metadata, path) + except codec.ManifestError as exc: + raise SpiralStoreTableCollisionError( + str(exc), table=self._qualified(table_name) + ) from exc + if record is None or manifest is None: + raise SpiralStoreTableCollisionError( + "it holds rows but no store manifest", + table=self._qualified(table_name), + ) + found = _Found(str(table.resource_id), record, manifest) + self._found[table_name] = found + self._empty.discard(table_name) + return found + + def has_table(self, table_name: str) -> bool: + """Whether the store table at a computed name holds rows (and 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 whose key is not the store's: ``__record_id``, binary.""" + key_type = None + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + with self._service_call(f"read the schema of {table_name}"): + key_type = table.schema().field(codec.KEY_COLUMN).type + if key_type is not None and ( + pa.types.is_binary(key_type) or pa.types.is_large_binary(key_type) + ): + return + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + raise SpiralStoreTableCollisionError( + f"its key {codec.KEY_COLUMN!r} is {key_type}, not binary", + table=self._qualified(table_name), + ) + 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 = identity.spiral_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 + ) -> identity.StoreTableRecord | None: + """The record of a listed table, read once per id; ``None`` without one. + + The name it is listed under now is checked against its record on every call, + the cached one included: a table renamed keeps its id.""" + record = self._records_by_id.get(table_id) + if record is None: + with self._service_call(f"read the metadata of {table_name}"): + metadata = self._client.keyed_table_by_id(table_id).get_metadata() + try: + record = identity.read_store_table_metadata(metadata) + except SpiralStoreTableCollisionError as exc: + raise SpiralStoreTableCollisionError( + exc.reason, table=self._qualified(table_name) + ) from exc + if record is None: + return None # never kept: its record may be written later + self._records_by_id[table_id] = record + if identity.spiral_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), + ) + return record + + # ── 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.""" + found = self._require(table_name) + return _live(found.manifest.schema, found.record.data_context_key) + + 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. + + Raises: + KeyError: If there is no table at the name. + """ + found = self._judge(table_name) + if found is None: + if table_name in self._empty: + return # it exists, with no rows + raise KeyError(f"no store table {self._qualified(table_name)}") + schema = _live(found.manifest.schema, found.record.data_context_key) + 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() + + def existing_record_ids( + self, table_name: str, ids: Collection[bytes] + ) -> set[bytes]: + """Return the ids among ``ids`` the table at ``table_name`` holds. + + One read of the key column over the range from the smallest to the largest id + asked, filtered here; nothing else of the table is read. Nothing for a table + that is absent or holds no rows. + + Args: + table_name: A name ``table_name`` returned. + ids: Record ids. + """ + found = self._judge(table_name) + if found is None or not ids: + return set() + asked = sorted(set(ids)) + sdk = self._sdk + key = sdk.column(codec.KEY_COLUMN) + # The key is stored as ``binary`` (spiral-sdk reads it in its small variant). + low = sdk.gte(key, sdk.literal(asked[0], pa.binary())) + high = sdk.lte(key, sdk.literal(asked[-1], pa.binary())) + with self._service_call(f"read the keys of {table_name}"): + stored = ( + self._client.keyed_table_by_id(found.table_id) + .scan([codec.KEY_COLUMN], filter=sdk.and_(low, high)) + .to_table() + ) + held = cast( + "list[bytes]", + stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), + ) + return set(asked).intersection(held) + + # ── writing ────────────────────────────────────────────────────────────── + + def _create_or_open(self, table_name: str) -> _KeyedTable: + """The table at a computed name, created now if absent.""" + table = self._open_table(table_name) + if table is not None: + return table + 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 self._sdk.SpiralError as exc: # pyright: ignore[reportAny] + if "status 409" not in str(exc): # pyright: ignore[reportAny] + raise + # Made meanwhile: the caller compares it with what it judged. + table = self._open_table(table_name) + if table is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + return table + + def _unchanged_since_judged( + self, table: _KeyedTable, table_name: str, path: tuple[str, ...], seen: _Seen + ) -> bool: + """Whether a table opened to be recorded is still as it was judged new: an + equivalent manifest (or none; compared by name, never by order or bytes) and no + rows. + + Read immediately before the manifest is written, so a record that read shows is + never overwritten. It narrows, and cannot close, the window in which two + writers race: spiral-sdk has no compare-and-set, so another writer can still + record the table between this read and the write. Concurrent writers are not + supported until the lease (ITL-1452). + + Raises: + SpiralStoreTableCollisionError: If the table's identity record, read with + the manifest, is of another path or cannot be read: an identity is + never recorded over. + """ + with self._service_call(f"read the metadata of {table_name}"): + metadata = table.get_metadata() + try: + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + except SpiralStoreTableCollisionError as exc: + raise SpiralStoreTableCollisionError( + exc.reason, table=self._qualified(table_name) + ) from exc + now = _seen_manifest(metadata, path) + return _same_seen(now, seen) and not self._holds_rows(table) + + def _require_same_manifest( + self, + table: _KeyedTable, + table_name: str, + path: tuple[str, ...], + manifest: codec.StoreManifest, + ) -> _Found: + """Refuse a table another writer recorded since it was judged, unless it records + the same manifest: another writer's record is never overwritten. + + Returns: + The table as it is recorded: its record and manifest stay, not this + writer's equivalent ones. + + Raises: + SpiralStoreTableCollisionError: If it records another path or manifest, or + holds rows without one. + """ + with self._service_call(f"read the metadata of {table_name}"): + metadata = table.get_metadata() + try: + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + current = None if record is None else codec.read_manifest(metadata, path) + except (SpiralStoreTableCollisionError, codec.ManifestError) as exc: + reason = ( + exc.reason if isinstance(exc, SpiralStoreTableCollisionError) else exc + ) + raise SpiralStoreTableCollisionError( + str(reason), table=self._qualified(table_name) + ) from exc + if record is None or current is None or not _same_manifest(current, manifest): + raise SpiralStoreTableCollisionError( + "another writer recorded it since it was judged, with another manifest", + table=self._qualified(table_name), + ) + return _Found(str(table.resource_id), record, current) + + def write(self, table_name: str, records: pa.Table) -> None: + """Write rows whose keys the table does not hold yet; the first write creates the + table and records its identity and manifest. Every check runs before anything is + created or written. A stored row is never overwritten: ``ConnectorArrowDatabase`` + refuses a stored id when the rows are added (unless asked to skip it), and a key + another writer stored since is left as that writer stored it. + + Raises: + ValueError: If the rows hold no ``__data_context`` column, or several data + contexts, their path cannot be recorded, or their columns are not the + table's. + UnstorableInSpiralError: If the codec refuses the rows. + InputValidationError: If their data context is not one this Orcapod has, + or not the one the table records (checked when they are buffered too). + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. + """ + path = self._path_of(table_name) + context = _one_data_context(records) + found = self._judge(table_name) + if found is None: + manifest = codec.new_manifest(path, path[-1], records.schema) + metadata = { + **identity.store_table_metadata(path, context), + **codec.manifest_entries(manifest), + } + encoded = _encoded(records) + if encoded.num_rows == 0: + return # nothing to write, so nothing is created + seen = self._judged.pop(table_name, ("none", None)) + table = self._create_or_open(table_name) + self._require_key(table, table_name) + if self._unchanged_since_judged(table, table_name, path, seen): + with self._service_call(f"record {table_name}"): + table.set_metadata(metadata) + recorded = _Found( + str(table.resource_id), + identity.StoreTableRecord(path, path[-1], context), + manifest, + ) + self._found[table_name] = recorded + self._empty.discard(table_name) + else: + recorded = self._require_same_manifest( + table, table_name, path, manifest + ) + _require_data_context(recorded, context) + self._found[table_name] = recorded + self._empty.discard(table_name) + # Another writer may have written these keys meanwhile. + encoded = _encoded(self._without_stored_keys(table_name, records)) + if encoded.num_rows > 0: + with self._service_call(f"write {table_name}"): + _ = table.append(encoded) + return + _require_data_context(found, context) + 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" + ) + encoded = _encoded(self._without_stored_keys(table_name, records)) + if encoded.num_rows == 0: + return # a write of no rows is never sent + table = self._client.keyed_table_by_id(found.table_id) + with self._service_call(f"write {table_name}"): + _ = table.append(encoded) + + def _without_stored_keys(self, table_name: str, records: pa.Table) -> pa.Table: + """The rows whose key the table does not hold yet (``existing_record_ids``).""" + ids = cast("list[bytes]", records.column(codec.KEY_COLUMN).to_pylist()) + held = self.existing_record_ids(table_name, ids) + if not held: + return records + return records.filter( + pc.invert( + pc.is_in( + records.column(codec.KEY_COLUMN), + pa.array(sorted(held), pa.large_binary()), + ) + ) + ) + + +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 (one per datagram, ITL-1359), a key this + Orcapod resolves: a table recording another could never be read back (its logical + types are made live with that context's converter, ``_live``). + + Raises: + ValueError: If there is no data context column, a null in it, or two values. + InputValidationError: If the key is not one of a data context this Orcapod + has (an unknown, a short or an empty key), naming it. + """ + 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 = cast( + "list[object]", pc.unique(records.column(DATA_CONTEXT_COLUMN)).to_pylist() + ) + if values == [""]: + raise InputValidationError( + "the rows' data context '' is not one this Orcapod has: a table recording " + "it could not be read" + ) + if len(values) != 1 or not isinstance(values[0], str): + raise ValueError( + f"rows of one write to a SpiralDB store hold one data context, not {values}" + ) + key = values[0] + from orcapod.contexts import resolve_context + from orcapod.contexts.core import ContextResolutionError + + try: + resolved = resolve_context(key).context_key + except ContextResolutionError as exc: + raise InputValidationError( + f"the rows' data context {key!r} is not one this Orcapod has: a table " + "recording it could not be read" + ) from exc + if resolved != key: + raise InputValidationError( + f"the rows' data context {key!r} is not a full data context key " + f"({resolved!r} is)" + ) + return key + + +def _require_data_context(found: _Found, context: str) -> None: + """Refuse rows of another data context than the table records: a table's logical + types are read back with its data context's type converter (``_live``). + + Raises: + InputValidationError: If ``context`` is not the table's, naming both keys + (``contexts.stored.require_same_data_context``). + """ + from orcapod.contexts.stored import require_same_data_context + + require_same_data_context(context, found.record.data_context_key) + + +def _live(schema: pa.Schema, data_context: str) -> pa.Schema: + """A manifest's schema with its logical types live, as the rows were given: by the + type converter of the data context the table records.""" + from orcapod.contexts import resolve_context + + return declaration_form_schema(schema, resolve_context(data_context).type_converter) + + +def _same_manifest(one: codec.StoreManifest, other: codec.StoreManifest) -> bool: + """Whether two manifests record one table: the same path and kind, equivalent + logical schemas (``schema_difference``) and the same stored schema. Never by their + bytes, which differ for equivalent schemas represented differently.""" + return ( + one.record_path == other.record_path + and one.kind == other.kind + and codec.schema_difference(one.schema, other.schema) is None + and _by_name(one.physical) == _by_name(other.physical) + ) + + +def _by_name(schema: pa.Schema) -> dict[str, pa.Field[Any]]: + """A stored schema's fields by name: their order never counts.""" + return {field.name: field for field in schema} + + +_Seen = tuple[str, object] +"""What a table recorded when judged: ``("none", None)``, ``("manifest", manifest)``, or +``("unreadable", header bytes)`` for a manifest that cannot be decoded (never equal to +anything: ``_same_seen``).""" + + +def _seen_manifest(metadata: Mapping[str, bytes], path: tuple[str, ...]) -> _Seen: + """What a table's metadata records, to compare later (``_same_seen``).""" + try: + manifest = codec.read_manifest(metadata, path) + except codec.ManifestError: + return ("unreadable", metadata.get(codec.MANIFEST_KEY)) + return ("none", None) if manifest is None else ("manifest", manifest) + + +def _same_seen(one: _Seen, other: _Seen) -> bool: + """Whether two readings record the same: equivalent manifests compared by name. + + A manifest that cannot be decoded never equals anything, itself included (when in + doubt, refuse): the write then goes through ``_require_same_manifest``, which + refuses it.""" + if one[0] == "unreadable" or other[0] == "unreadable": + return False + if one[0] != other[0]: + return False + if one[0] == "manifest": + return _same_manifest( + cast(codec.StoreManifest, one[1]), cast(codec.StoreManifest, other[1]) + ) + return one[1] == other[1] 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..8c74b4220 --- /dev/null +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -0,0 +1,1056 @@ +"""A SpiralDB connector in store mode, under ``ConnectorArrowDatabase`` (ITL-1840). + +On the fake (``fake_spiral_sdk``); no live SpiralDB. Store mode is private: a +``SpiralDBConnector`` built with ``_store=True``. The tests cover each table kind's +layout written and read back, the write rules of ITL-1386, refusals of tables that are +not the store's, the data-context checks and the listing the stale-layout check uses. +""" + +from __future__ import annotations + +import datetime as dt +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts.stored import tables_of_another_layout +from orcapod.core.operators import SelectDataColumns +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import spiral_store as codec +from orcapod.databases import spiral_store_identity as identity +from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.errors import InputValidationError, SpiralDBWriteNotSupportedError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectPod, sink_pod +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +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 tables_of(connector: SpiralDBConnector) -> StoreTables: + tables = connector._store_tables() # pyright: ignore[reportPrivateUsage] + assert tables is not None + return tables + + +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) + + +def _tables() -> list[dict[str, Any]]: + return fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + + +# ------------------------------------------------------------------ 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] + some = db.get_records_by_ids(RESULT, [b"r2", b"r0"], record_id_column="__record_id") + assert some is not None and set(some["a.b"].to_pylist()) == {1, 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(identity.spiral_store_table_name(full)) + metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + assert record == identity.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_v2") + db = ConnectorArrowDatabase(store()) + db.add_records(long_path, rows(["r0"]), record_id_column="__record_id") + db.flush() + assert len(identity.spiral_store_table_name(long_path)) <= 164 + assert db.list_table_paths(("f" * 300,)) == [long_path] + + +@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 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["as_written", "reversed"]) +def test_rows_with_the_columns_in_another_order_append(order: str) -> None: + """Columns match by name: an append with the columns in any order is one table.""" + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + second = rows(["r1"], offset=10) + if order == "reversed": + second = second.select(list(reversed(second.column_names))) + db.add_records(RESULT, second, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 10, + } + assert got.schema.names == rows(["x"]).schema.names + + +# ------------------------------------------------- the write rules of ITL-1386 + + +@pytest.mark.usefixtures("root") +def test_a_stored_id_is_refused_without_buffering_other_rows() -> None: + """A write to a stored id raises unless ``skip_duplicates``; nothing of the add is + buffered.""" + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0", "r1"]), record_id_column="__record_id") + db.flush() + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records( + RESULT, rows(["r9", "r1"], offset=100), record_id_column="__record_id" + ) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(RESULT, b"r0", rows(["r0"]).drop_columns(["__record_id"])) + db.flush() + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 1, + } + + +@pytest.mark.usefixtures("root") +def test_a_pending_id_is_refused_unless_skipped() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(ValueError, match="already exist in the pending batch"): + db.add_records(RESULT, rows(["r0"], offset=5), record_id_column="__record_id") + db.add_records( + RESULT, + rows(["r0", "r1"], offset=5), + 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 + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 6, + } + + +@pytest.mark.usefixtures("root") +def test_skip_duplicates_keeps_stored_rows_and_writes_the_rest() -> 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") +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_an_id_another_writer_stored_since_the_add_keeps_its_first_commit( + skip_duplicates: bool, +) -> None: + """Accepted when added, stored by another writer before this flush: the stored row + is kept (a SpiralDB append would replace it), the other keys are written.""" + a = ConnectorArrowDatabase(store()) + b = ConnectorArrowDatabase(store()) + b.add_records(RESULT, rows(["seed"]), record_id_column="__record_id", flush=True) + a.add_records( + RESULT, + rows(["x", "y"], offset=100), + record_id_column="__record_id", + skip_duplicates=skip_duplicates, + ) + b.add_records(RESULT, rows(["x"]), record_id_column="__record_id", flush=True) + a.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"seed": 0, + b"x": 0, + b"y": 101, + } + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "asked", + [[b"r1", b"r3"], [b"r3", b"r1"], [b"a", b"r2", b"zz"], [b"q"], []], + ids=["two", "two reversed", "around the stored", "none stored", "empty"], +) +def test_stored_ids_are_answered_by_one_key_range_read(asked: list[bytes]) -> None: + """``existing_record_ids``: one scan of the key column over the asked range, never + the whole table.""" + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records( + RESULT, rows(["r0", "r1", "r2", "r3"]), record_id_column="__record_id" + ) + db.flush() + tables = tables_of(connector) + name = tables.table_name(RESULT) + fake.scan_log.clear() + fake.count_log.clear() + held = tables.existing_record_ids(name, set(asked)) + scans = [*fake.scan_log, *fake.count_log] + assert held == set(asked) & {b"r0", b"r1", b"r2", b"r3"} + keyed = [s for s in scans if s.columns == ["__record_id"] and s.filter is not None] + if asked: + assert len(keyed) == 1 + (bounds,) = [s.filter.terms for s in keyed] + assert [(n, op) for n, _, op in bounds] == [ + ("__record_id", ">="), + ("__record_id", "<="), + ] + assert [v.value for _, v, _ in bounds] == [min(asked), max(asked)] + assert all(s.columns == ["__record_id"] for s in scans), scans + + +@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, InputValidationError), match="(?i)schema|column"): + fresh.add_records(RESULT, other, record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_column_of_other_field_metadata_is_refused_on_append() -> None: + """Storage metadata must match on append (ITL-1334, ITL-1386).""" + db = ConnectorArrowDatabase(store()) + first = rows(["r0"]) + field = first.schema.field("a.b").with_metadata({"unit": "m"}) + first = first.set_column(2, field, first.column("a.b")) + db.add_records(RESULT, first, record_id_column="__record_id", flush=True) + second = rows(["r1"]) + other = second.schema.field("a.b").with_metadata({"unit": "s"}) + second = second.set_column(2, other, second.column("a.b")) + with pytest.raises(InputValidationError, match="a.b"): + ConnectorArrowDatabase(store()).add_records( + RESULT, second, record_id_column="__record_id" + ) + + +# ---------------------------------------------------------------- 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 _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_column_the_codec_cannot_keep_is_named_by_require_storable() -> None: + """A job attaching the database is refused before it runs, naming the column.""" + from orcapod.errors import UnstorableColumnError + + db = ConnectorArrowDatabase(store()) + with pytest.raises(UnstorableColumnError, match="d"): + db.require_storable(pa.schema([pa.field("d", pa.duration("s"))])) + db.require_storable(rows(["r0"]).schema) + + +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( + identity.spiral_store_table_name(RESULT), + identity.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_foreign_table_with_rows_and_no_record_is_refused() -> None: + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="no store manifest"): + _ = db.table_exists(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + _ = db.get_all_records(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_without_a_record_is_adopted() -> None: + """A creation that stopped before the first write.""" + _make_table(identity.spiral_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") +@pytest.mark.parametrize( + "key", + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("__record_id", pa.large_string(), nullable=False), + ], + ids=["another name", "another type"], +) +def test_an_empty_table_with_another_key_is_refused_untouched( + key: "pa.Field[Any]", +) -> None: + name = identity.spiral_store_table_name(RESULT) + _ = _client().project("p").create_keyed_table("d", name, pa.schema([key])) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="key"): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert _table(name).get_metadata() == {} + + +@pytest.mark.usefixtures("root") +def test_a_path_too_long_to_record_is_refused_before_any_table_is_made() -> None: + path = ("x" * 9000, "rdb_v1") + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="path|entry"): + db.add_records(path, rows(["r0"]), record_id_column="__record_id", flush=True) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_recorded_table_with_no_rows_is_new_to_any_first_writer() -> None: + """A first write that failed after its metadata leaves a table any first writer may + record again, with another schema too.""" + other = rows(["r0"]).drop_columns(["s"]) + manifest = codec.new_manifest(RESULT, "rdb_v1", other.schema) + _make_table( + identity.spiral_store_table_name(RESULT), + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(manifest), + }, + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + assert not db.table_exists(RESULT) + written = rows(["r0", "r1"]) + db.add_records(RESULT, written, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and by_id(got).equals(by_id(written)) + + +@pytest.mark.usefixtures("root") +def test_a_recorded_empty_table_with_a_corrupt_manifest_is_refused() -> None: + """Metadata that cannot be decoded never equals anything, so a table whose manifest + chunk is corrupt is never recorded over.""" + manifest = codec.new_manifest(RESULT, "rdb_v1", rows(["x"]).schema) + entries = codec.manifest_entries(manifest) + corrupt = { + **entries, + f"{codec.MANIFEST_KEY}/0": entries[f"{codec.MANIFEST_KEY}/0"] + b" ", + } + name = identity.spiral_store_table_name(RESULT) + _make_table( + name, + {**identity.store_table_metadata(RESULT, CONTEXT), **corrupt}, + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id", flush=True) + assert ( + _table(name).get_metadata()[f"{codec.MANIFEST_KEY}/0"] + == corrupt[f"{codec.MANIFEST_KEY}/0"] + ) + + +# ------------------------------------------------------------- data contexts + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("context", ["std:v999:default", "v1", "not a key", ""]) +def test_a_data_context_this_orcapod_cannot_resolve_is_refused_before_anything( + context: str, +) -> None: + """A table recording a data context key no reader can resolve would be unreadable: + such rows (an unknown key, or a short one) are refused when they are added, before + they are buffered, and by a write that reaches the store directly, before any table + is created.""" + db = ConnectorArrowDatabase(store()) + with pytest.raises(InputValidationError, match="data context"): + db.add_records( + RESULT, rows(["r0"], context=context), record_id_column="__record_id" + ) + assert not db.table_exists(RESULT) + assert db.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") is None + db.flush() + tables = tables_of(store()) + name = tables.table_name(RESULT) + with pytest.raises(InputValidationError, match="data context"): + tables.write(name, rows(["r0"], context=context)) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_two_data_contexts_buffered_for_one_table_are_refused_before_it_is_made() -> ( + None +): + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(InputValidationError, match="data context"): + db.add_records( + RESULT, rows(["r1"], context="std:v2:other"), record_id_column="__record_id" + ) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> None: + """Rows of another data context than the table records are refused when they are + added (naming both keys), before they are buffered: a flush asked for with them + writes nothing, not even another table's pending batch.""" + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["old"]), record_id_column="__record_id", flush=True + ) + recorded = "std:v0:legacy" + _table(identity.spiral_store_table_name(RESULT)).set_metadata( + identity.store_table_metadata(RESULT, recorded) + ) + other = (*RESULT[:-1], "rdb_v9") + db = ConnectorArrowDatabase(store()) + db.add_records(other, rows(["valid"]), record_id_column="__record_id") + with pytest.raises(InputValidationError) as raised: + db.add_records( + RESULT, rows(["bad"]), record_id_column="__record_id", flush=True + ) + assert recorded in str(raised.value) and CONTEXT in str(raised.value) + assert not ConnectorArrowDatabase(store()).table_exists(other) + assert db.table_exists(other) + db.flush() + assert ConnectorArrowDatabase(store()).table_exists(other) + stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() + assert keys == [b"old"] + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_data_context_made_after_buffering_is_refused_at_flush() -> ( + None +): + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["mine"]), record_id_column="__record_id") + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["old"]), record_id_column="__record_id", flush=True + ) + recorded = "std:v0:legacy" + _table(identity.spiral_store_table_name(RESULT)).set_metadata( + identity.store_table_metadata(RESULT, recorded) + ) + with pytest.raises(InputValidationError) as raised: + db.flush() + assert recorded in str(raised.value) and CONTEXT in str(raised.value) + stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() + assert keys == [b"old"] + + +@pytest.mark.usefixtures("root") +def test_logical_types_are_read_with_the_data_context_the_table_records( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import orcapod.contexts as contexts + + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + asked: list[object] = [] + real = contexts.resolve_context + + def resolve(context_info: Any = None) -> Any: + asked.append(context_info) + return real(context_info) + + monkeypatch.setattr(contexts, "resolve_context", resolve) + fresh = ConnectorArrowDatabase(store()) + assert fresh.get_all_records(RESULT, record_id_column="__record_id") is not None + assert CONTEXT in asked + + +# ------------------------------------------------------------- logical types + + +def _with_path_column(table: pa.Table, *, live: bool) -> pa.Table: + from pathlib import Path as PathValue + + from orcapod.contexts import get_default_context + from orcapod.logical_types.canonical_form import storage_form_schema + + converter = get_default_context().type_converter + paths = converter.python_dicts_to_arrow_table( + [{"p": PathValue(f"a/{i}")} for i in range(table.num_rows)], + python_schema={"p": PathValue}, + ) + if not live: + schema = storage_form_schema(paths.schema) + column: Any = paths.column("p").combine_chunks() # an extension array + paths = pa.Table.from_arrays([column.storage], schema=schema) + return table.append_column(paths.schema.field("p"), paths.column("p")) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_live", [True, False]) +def test_a_logical_type_live_or_in_storage_form_is_one_column(first_live: bool) -> None: + db = ConnectorArrowDatabase(store()) + first = _with_path_column(rows(["r0"]), live=first_live) + second = _with_path_column(rows(["r1"]), live=not first_live) + db.add_records(RESULT, first, record_id_column="__record_id", flush=True) + db.add_records(RESULT, second, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and got.num_rows == 2 + assert isinstance(got.schema.field("p").type, pa.BaseExtensionType) + + +@pytest.mark.usefixtures("root") +def test_a_storage_form_identifier_no_type_is_registered_for_is_kept_as_given() -> None: + field = pa.field( + "u", + pa.large_string(), + metadata={ + b"ARROW:extension:name": b"test.unregistered.kind", + b"ARROW:extension:metadata": b'{"version":1}', + }, + ) + table = rows(["r0"]).append_column(field, pa.array(["x"], pa.large_string())) + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, table, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert got.schema.field("u").type == pa.large_string() + assert got.schema.field("u").metadata == field.metadata + assert got["u"].to_pylist() == ["x"] + + +# ---------------------------------------------------------------- listing + + +PATHS = [ + RESULT, + ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v0"), + ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2"), + ("my_fnx", H, "rdb_v1"), + ("side_effects", "Notify Pod", f"schema:{H}", "tdb_v2"), + ("my_op", H, "odb_v3"), + ("my", "cache", "sdb_v2"), +] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +def test_tables_are_listed_by_their_recorded_paths(order: str) -> None: + db = ConnectorArrowDatabase(store()) + for path in PATHS if order == "forward" else list(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[4]] + 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: + _make_table( + "o1_my_fn_" + "0" * 64, + identity.store_table_metadata(RESULT, CONTEXT), + with_rows=True, + ) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +@pytest.mark.usefixtures("root") +def test_a_table_listed_before_its_record_is_listed_after_it() -> None: + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(store()) + assert db.list_table_paths(("my_fn",)) == [] + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths(("my_fn",)) == [RESULT] + + +def _rename(table_name: str, new_name: str) -> None: + """Rename a table in the fake, keeping its id (as the service does).""" + found = fake._store().find("p", "d", table_name) # pyright: ignore[reportPrivateUsage] + assert found is not None + found["name"] = new_name + root = fake._store().root # pyright: ignore[reportPrivateUsage] + (root / found["id"] / "table.json").write_text(json.dumps(found)) + + +@pytest.mark.usefixtures("root") +def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths(("my_fn",)) == [RESULT] + other = (*RESULT[:-1], "rdb_v9") + _rename( + identity.spiral_store_table_name(RESULT), + identity.spiral_store_table_name(other), + ) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = db.list_table_paths(("my_fn",)) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +# ------------------------------------------------------ concurrent first writers + + +def _made_meanwhile(connector: SpiralDBConnector, make: Any) -> None: + """Run ``make`` (another party's act) just before ``connector`` creates or opens a + table for its first write.""" + tables = tables_of(connector) + create_or_open = tables._create_or_open # pyright: ignore[reportPrivateUsage] + + def other_first(table_name: str) -> Any: + make(table_name) + return create_or_open(table_name) + + tables._create_or_open = other_first # pyright: ignore[reportPrivateUsage] + + +def _interleaved(first_rows: pa.Table, second_rows: pa.Table) -> Any: + """Writer 1 judges the table absent; writer 2 then creates and fills it; then + writer 1 goes on. Returns writer 1's database.""" + first = store() + db1 = ConnectorArrowDatabase(first) + db1.add_records(RESULT, first_rows, record_id_column="__record_id") + + def the_other_writer(_: str) -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, second_rows, record_id_column="__record_id", flush=True + ) + + _made_meanwhile(first, the_other_writer) + return db1 + + +def _reordered(table: pa.Table) -> pa.Table: + return table.select(list(reversed(table.column_names))) + + +@pytest.mark.usefixtures("root") +def test_a_writer_never_overwrites_another_writers_manifest() -> None: + other_schema = rows(["b0"]).drop_columns(["s"]) + db1 = _interleaved(rows(["a0"]), other_schema) + with pytest.raises(SpiralStoreTableCollisionError): + db1.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and by_id(got).equals(by_id(other_schema)) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("second", ["same", "metadata order", "column order"]) +def test_a_writer_of_an_equivalent_manifest_appends_beside_another( + second: str, +) -> None: + first = rows(["a0"]).replace_schema_metadata({"x": "1", "y": "2"}) + other = rows(["b0"]).replace_schema_metadata({"x": "1", "y": "2"}) + if second == "metadata order": + other = rows(["b0"]).replace_schema_metadata({"y": "2", "x": "1"}) + elif second == "column order": + other = _reordered(other) + db1 = _interleaved(first, other) + db1.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert set(got["__record_id"].to_pylist()) == {b"a0", b"b0"} + # The writer's own connector reads the columns as the table records them. + mine = db1.get_table_schema(RESULT) + fresh = ConnectorArrowDatabase(store()).get_table_schema(RESULT) + assert mine is not None and fresh is not None and mine.names == fresh.names + + +@pytest.mark.usefixtures("root") +def test_an_identity_of_another_path_made_meanwhile_is_never_recorded_over() -> None: + other = identity.store_table_metadata(("another", "rdb_v1"), CONTEXT) + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id") + _made_meanwhile(connector, lambda name: _make_table(name, other, with_rows=False)) + with pytest.raises(SpiralStoreTableCollisionError, match="another"): + db.flush() + metadata = _table(identity.spiral_store_table_name(RESULT)).get_metadata() + assert identity.read_store_table_metadata( + metadata + ) == identity.read_store_table_metadata(other) + assert codec.MANIFEST_KEY not in metadata + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_a_first_writer_keeps_the_rows_another_writer_stored_meanwhile( + skip_duplicates: bool, +) -> None: + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records( + RESULT, + rows(["r1", "r9"], offset=100), + record_id_column="__record_id", + skip_duplicates=skip_duplicates, + ) + + def the_other_writer(_: str) -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["r1"]), record_id_column="__record_id", flush=True + ) + + _made_meanwhile(connector, the_other_writer) + db.flush() + got = ConnectorArrowDatabase(store()).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"r1": 0, b"r9": 101} + + +# ------------------------------------------------------ private, plain, closed + + +@pytest.mark.usefixtures("root") +def test_a_store_mode_connector_is_not_saved() -> None: + with pytest.raises(ValueError, match="not saved"): + _ = store().to_config() + with pytest.raises(ValueError, match="not saved"): + _ = ConnectorArrowDatabase(store()).to_config() + + +@pytest.mark.usefixtures("root") +def test_raw_access_is_refused_in_store_mode() -> None: + connector = store() + for call in ( + lambda: connector.lookup_table("x"), + lambda: list(connector.scan_batches("x")), + lambda: list(connector.iter_batches('SELECT * FROM "x"')), + lambda: connector.get_table_names(), + lambda: connector.get_column_info("x"), + lambda: connector.get_arrow_schema("x"), + ): + with pytest.raises(ValueError, match="store-mode"): + _ = call() + for write in ( + lambda: connector.create_table_if_not_exists("x", [], "__record_id"), + lambda: connector.upsert_records("x", rows(["r0"]), "__record_id"), + lambda: connector.existing_record_ids("x", "__record_id", {b"r0"}), + lambda: connector.validate_records(rows(["r0"])), + ): + with pytest.raises(SpiralDBWriteNotSupportedError): + write() + + +@pytest.mark.usefixtures("root") +def test_a_plain_connector_still_writes_nothing() -> None: + """Main's behaviour: a database on a plain connector refuses every write.""" + db = ConnectorArrowDatabase(SpiralDBConnector("p", "d")) + with pytest.raises(SpiralDBWriteNotSupportedError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(SpiralDBWriteNotSupportedError): + db.require_storable(rows(["r0"]).schema) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() -> None: + connector = store() + db = ConnectorArrowDatabase(connector) + shared = connector.share_client() + connector.close() + assert connector._store is None # pyright: ignore[reportPrivateUsage] + for call in ( + lambda: db.table_exists(RESULT), + lambda: db.list_table_paths(), + lambda: db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id"), + lambda: db.require_storable(rows(["r0"]).schema), + ): + with pytest.raises(RuntimeError, match="closed"): + _ = call() + # the connector sharing its client keeps its own reference + other = ConnectorArrowDatabase(shared) + other.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert other.table_exists(RESULT) + + +@pytest.mark.usefixtures("root") +def test_an_existing_empty_table_is_read_as_no_rows() -> None: + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + with pytest.raises(KeyError): + _ = list(tables.scan(name)) + _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) + fresh = tables_of(store()) + assert fresh.table_name(RESULT) == name + assert not fresh.has_table(name) + assert list(fresh.scan(name)) == [] + assert ConnectorArrowDatabase(store()).get_all_records(RESULT) is None + + +# ------------------------------------------------- every table kind, end to end + +JOB = "itl1840" +SOURCE_ROWS = [{"k": "a", "x": 1}, {"k": "b", "x": 2}, {"k": "c", "x": 3}] +LAYOUTS = ("pdb_v2", "rdb_v1", "odb_v3", "sdb_v2", "tdb_v2") + +calls: list[int] = [] +delivered: list[int] = [] + + +@function_pod(output_keys="double") +def double(x: int) -> int: + calls.append(x) + return 2 * x + + +def _deliver(double: int, ctx: Any) -> None: + delivered.append(double) + + +def _job(database: ConnectorArrowDatabase, rows_given: list[dict[str, Any]]) -> Any: + """A function node, a logged operator node and a sink: four table kinds.""" + job = PipelineJob(name=JOB, database=database) + with job: + source = DictSource( + data=rows_given, tag_columns=["k"], tag_only_columns=True, source_id="src" + ) + out = double.pod(source, label="dbl") + SelectDataColumns(["double"])(out, label="sel") + sink = sink_pod(_deliver) + assert isinstance(sink, SideEffectPod) + sink.process(out, label="sink") + job.nodes["sel"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG + ) + return job + + +def _cached(database: ConnectorArrowDatabase) -> CachedSource: + table = pa.table({"k": ["a", "b"], "x": [1, 2]}) + return CachedSource( + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="fixed" + ), + cache_database=database, + ) + + +@pytest.fixture +def _cleared() -> Iterator[None]: + calls.clear() + delivered.clear() + yield + calls.clear() + delivered.clear() + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + database = ConnectorArrowDatabase(store()) + _ = _job(database, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) + cached = _cached(database).as_table() + assert sorted(calls) == [1, 2, 3] and sorted(delivered) == [2, 4, 6] + + fresh = ConnectorArrowDatabase(store()) + paths = fresh.list_table_paths() + assert sorted(p[-1] for p in paths) == sorted(LAYOUTS) + for path in paths: + stored = fresh.get_all_records(path) + assert stored is not None and stored.num_rows > 0, path + assert set(stored.column("__data_context").to_pylist()) == {CONTEXT}, path + + # A second run in a fresh process reads what the first stored: no call, no delivery. + calls.clear() + delivered.clear() + again = _job(fresh, SOURCE_ROWS) + _ = again.run(orchestrator=run[orchestrator]()) + assert calls == [] and delivered == [] + assert sorted(again.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] + assert sorted(again.nodes["sel"].as_table()["double"].to_pylist()) == [2, 4, 6] + assert _cached(fresh).as_table().equals(cached) + + +@pytest.mark.usefixtures("root", "_cleared") +def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others() -> None: + database = ConnectorArrowDatabase(store()) + _ = _job(database, SOURCE_ROWS[:2]).run() + before = { + p: database.get_all_records(p, record_id_column="__rid") + for p in database.list_table_paths() + } + calls.clear() + delivered.clear() + fresh = ConnectorArrowDatabase(store()) + _ = _job(fresh, SOURCE_ROWS).run() + assert calls == [3] and delivered == [6] + for path, earlier in before.items(): + assert earlier is not None + now = fresh.get_all_records(path, record_id_column="__rid") + assert now is not None + kept = {r["__rid"]: r for r in now.to_pylist()} + for row in earlier.to_pylist(): + assert kept[row["__rid"]] == row, path + assert now.num_rows > earlier.num_rows, path From 36ba2a9ed5921648bdef4e1e2d70264802354d57 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 10:55:40 -0800 Subject: [PATCH 10/50] refactor(spiraldb): store mode uses the shared store path domain; stage B plan (ITL-1840) The store's naming and ConnectorArrowDatabase's store key apply store_table_names.require_store_path_domain, the rule the identity record and the manifest apply (merged from stage A), instead of a rule of their own. A regression test covers each component the domain refuses, in the record path and the base path. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 92 +++++++++++++++++++ .../databases/connector_arrow_database.py | 5 +- .../databases/spiraldb_store_tables.py | 10 +- .../test_spiraldb_store_mode.py | 29 ++++++ 4 files changed, 132 insertions(+), 4 deletions(-) create mode 100644 docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md new file mode 100644 index 000000000..d7bdb1077 --- /dev/null +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -0,0 +1,92 @@ +# ITL-1840: SpiralDB store, stage B (store mode under ConnectorArrowDatabase) + +Stage B of using SpiralDB as a job's pipeline and result database (ITL-1446), on top of +stage A (ITL-1837: the spiral-sdk pin, the identity record, the codec). It carries PR 595's +store mode (ITL-1498) onto current `main`. PR 595 is not merged: its refactor of the +connector protocol (`table_name`, `has_table`, `table_paths`, `validate_records(table_name=)`) +collides with `main`'s SQL store catalog (`_sql_store.py`, ITL-1552) and is not carried. +Its `spiraldb_store_tables.py` and its tests are. + +Nothing is public. The store mode is a private constructor argument, +`SpiralDBConnector(project, dataset, _store=True)`, read and written only through +`ConnectorArrowDatabase`. A plain `SpiralDBConnector` behaves as on `main`: it reads and +refuses every write (`SpiralDBWriteNotSupportedError`). + +## Structure + +- `databases/spiraldb_store_tables.py` (`StoreTables`): the tables of one dataset in store + mode. Names come from the full path (`spiral_store_identity.spiral_store_table_name`, after + `store_table_names.require_store_path_domain`, the one path domain the identity record and + the manifest apply). Each table's metadata holds its identity record and manifest, written + in one upsert before its first rows. Rows go through the codec (`spiral_store`). +- `SpiralDBConnector` builds a `StoreTables` when `_store=True`, hands it out through the + private `_store_tables()`, and in store mode refuses raw access (`lookup_table`, + `iter_batches`, `get_table_names` and every read built on them) with a `ValueError`. Its + protocol write methods still raise `SpiralDBWriteNotSupportedError`. `to_config` refuses + a store-mode connector, so a job on one is not saved. `close` releases the store's tables. +- `ConnectorArrowDatabase` gets an internal store branch beside `_sql_store`: naming, + finding, reading, the stored-id check, listing, column info, the stored schema, the + storable-column check, validation and the write go to `StoreTables` when the connector + is a store-mode `SpiralDBConnector`. `DBConnectorProtocol` is unchanged. + +The branch is taken only for a store-mode connector. For every other connector, the +plain `SpiralDBConnector` included, the code paths are `main`'s. + +## Rules carried over + +- A table under the computed name that is not this path's store table is refused + (`SpiralStoreTableCollisionError`): another path or format in its record, a key other + than `__record_id` binary, or rows without a manifest. A table with no rows is new to any + first writer (a creation that stopped before its first rows). +- A first write re-reads the table just before recording it and never records over what + that read shows: an equivalent manifest (compared by name and decoded, never by bytes or + order) is appended beside; anything else is refused. Without a compare-and-set and a lease + (ITL-1452) two writers can still race in between. +- Rows hold one `__data_context`, a key this Orcapod resolves, and the one the table records. + Checked when rows are added (before they are buffered) and again at flush (the table may + have been made since). +- A logical type given in storage form is made live before it is compared and buffered + (store mode only), so one column has one form in the manifest. +- Listing (`list_table_paths`, hence the stale-layout check of ITL-954): one listing of the + dataset narrowed by the name prefix, then each candidate's recorded path, cached by table + id; a listed table whose record is of a path with another name is refused. + +## The write rules of ITL-1386 + +- A stored or pending id raises unless `skip_duplicates`, as for every connector + (`ConnectorArrowDatabase.add_records`). +- `existing_record_ids` is answered by key: one scan of the key column, filtered by SpiralDB + to the range from the smallest to the largest id asked, intersected here. No other column + is read. +- A flush never overwrites a stored row. A SpiralDB append replaces a row of the same key, + so the store writes only the keys the table does not hold (the same key-range read): a + key another writer stored after this one's add keeps its first commit, as with every + other connector. +- Storage metadata must match on append: the stored schema (the manifest's, logical types + live) is held as for any connector that keeps field metadata (`_refuse_changed_columns`), + and the store compares the rows with the manifest again when it writes. + +## Open question + +The key-range read assumes SpiralDB orders a binary key column by its bytes, as the fake +does. The service's equality on binary literals is measured; its order on them is not. +A live check needs throwaway tables, and how to drop them is a pending developer decision. +Until it is measured, a wrong order would let a stored key go unseen: the add check would +miss a duplicate, and a flush could overwrite that row. + +## Tests + +`tests/test_databases/test_spiraldb_store_mode.py`, on the fake only: + +- each table kind (`pdb_v2`, `rdb_v1`, `odb_v3`, `sdb_v2`, `tdb_v2`) written by a job (a + function node, a logged operator node, a sink) and a `CachedSource`, listed and read back + by a fresh connector, and a second run that calls and delivers nothing; sync and async; +- a new input adds rows to every table and leaves the stored rows unchanged; +- the ITL-1386 rules, the key-range read (several ids, in both orders), refusals of + foreign tables, the data-context checks, the path domain, listing, concurrent first + writers, and that a plain connector still writes nothing. + +## What is left (later stages of ITL-1446) + +The one-writer lease (ITL-1452), the public switch-on with save and load, the live run, +and fewer service calls per run (keyed reads, one existence answer per run). diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index e79334266..3b1ebd4e1 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -46,6 +46,7 @@ from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, + require_store_path_domain, store_table_name, store_table_path_json, table_name_hint, @@ -316,7 +317,9 @@ def _get_record_key(self, record_path: tuple[str, ...]) -> str: full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: if self._spiral_connector is not None: - self._validate_path_components(full_path) + # The one path domain of a SpiralDB store (its identity record and + # manifest apply it too). + _ = require_store_path_domain(full_path) return "/".join(full_path) self._validate_path_components(full_path) return f"{self._sql_store.get_current_store_schema()}\0{'/'.join(full_path)}" diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index dc25ad86e..c1057c12c 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -39,6 +39,7 @@ import orcapod.databases.spiral_store as codec import orcapod.databases.spiral_store_identity as identity from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +from orcapod.databases.store_table_names import require_store_path_domain from orcapod.errors import InputValidationError from orcapod.logical_types.canonical_form import declaration_form_schema from orcapod.system_constants import constants @@ -189,10 +190,13 @@ def table_name(self, path: tuple[str, ...]) -> str: """Return the table name of a full record path, and remember the path. Raises: - ValueError: If the path cannot be named. + ValueError: If the path is outside the store path domain + (``store_table_names.require_store_path_domain``), which the table's + identity record and manifest apply too. """ - name = identity.spiral_store_table_name(path) - self._paths[name] = tuple(path) + components = require_store_path_domain(path) + name = identity.spiral_store_table_name(components) + self._paths[name] = components return name def _path_of(self, table_name: str) -> tuple[str, ...]: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 8c74b4220..795b52495 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1054,3 +1054,32 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others() -> None: for row in earlier.to_pylist(): assert kept[row["__rid"]] == row, path assert now.num_rows > earlier.num_rows, path + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "component", + ["", "a/b", "a\0b", "\ud800"], + ids=["empty", "slash", "nul", "not utf-8"], +) +@pytest.mark.parametrize("where", ["record path", "base path"]) +def test_a_path_outside_the_store_path_domain_is_refused_before_anything( + component: str, where: str +) -> None: + """The store applies the one path domain its identity record and manifest apply + (``require_store_path_domain``), in the record path and in the base path alike.""" + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="component"): + if where == "record path": + db.add_records( + ("ok", component, "rdb_v1"), + rows(["r0"]), + record_id_column="__record_id", + ) + else: + db.at("base", component).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id" + ) + db.flush() + assert _tables() == [] + assert db.list_table_paths() == [] From 216f1982da53eb19a184ac697c08009aa04e6748 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 10:59:02 -0800 Subject: [PATCH 11/50] docs(spiraldb): the store path rule is SpiralDB's component syntax; pin the entry cap (ITL-1837) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/store_table_names.py | 24 ++++++++++++------- .../test_spiral_store_identity.py | 14 +++++++++++ 2 files changed, 30 insertions(+), 8 deletions(-) diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 8b5fe00fb..79cec7cab 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -13,14 +13,22 @@ def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: - """Refuse a full path that no store keeps; the one statement of the path domain. - - A store table's full path is at least one component, and every component is a - non-empty string with a UTF-8 form that holds neither ``/`` nor NUL: the rule - every Orcapod database applies to a record path (the connector, in-memory and - Delta stores split a key at ``/``). Every writer and reader of a SpiralDB store - table's identity record and manifest applies it, so they accept and refuse the same - paths. Naming (``store_table_path_json``) encodes any path of strings. + """Refuse a path outside the SpiralDB store's component syntax. + + A SpiralDB store table's full path is at least one component, and every component + is a non-empty ``str`` (not a subclass) with a UTF-8 form that holds neither ``/`` + nor NUL. Every writer and reader of a SpiralDB store table's identity record and + manifest applies it, so they accept and refuse the same component syntax. It is + the SpiralDB store's rule only: the other databases keep their own path rules (the + in-memory store accepts a lone surrogate or a ``str`` subclass, the Delta store + refuses a quoted component). Naming (``store_table_path_json``) encodes any path of + strings. + + A path inside this syntax can still be refused for its size: each entry of the + identity record is capped at SpiralDB's entry limit + (``spiral_store_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an + 8,192-character component is valid here, round-trips through the chunked manifest, + and is refused by ``spiral_store_identity.store_table_metadata``. Args: path: The store's base path followed by its record path. diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_store_identity.py index f051033c2..e86003669 100644 --- a/tests/test_databases/test_spiral_store_identity.py +++ b/tests/test_databases/test_spiral_store_identity.py @@ -160,6 +160,20 @@ def test_every_entry_fits_the_service_s_entry_limit() -> None: _ = names.store_table_metadata((longest[0] + "x",), "std:v1:default") +def test_a_valid_component_can_still_be_too_long_for_the_identity_record() -> None: + """A component inside the path syntax is refused by the identity record's entry + limit, not by the syntax: the manifest, which is chunked, still keeps it.""" + path = ("x" * 8192, "rdb_v1") + assert store_table_names.require_store_path_domain(path) == path + manifest = spiral_store.new_manifest(path, "k", _schema()) + entries = spiral_store.manifest_entries(manifest) + assert spiral_store.read_manifest(entries, path) == manifest + with pytest.raises( + ValueError, match="'orcapod.path' is 8217 bytes, over SpiralDB's 8192" + ): + _ = names.store_table_metadata(path, "std:v1:default") + + def test_a_table_without_orcapod_metadata_is_unmarked() -> None: """A table with none of the record's entries is unmarked.""" assert names.read_store_table_metadata({}) is None From c8e15d06711798fec13c37e02f11fd984e67dd16 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 11:15:22 -0800 Subject: [PATCH 12/50] fix(spiraldb): store mode review round 1: order-free key check, name resolved per call (ITL-1840) - existing_record_ids reads the key column alone and intersects: no range of binary ids, so the service's binary order is never relied on. - What a table records is kept by table id, and only after a successful append (or a read that found its rows); a failed append forgets it. - The table name is opened on every call: a renamed or replaced table is never read or written through an earlier answer. - Logical type identifier bytes are compared as given, against the pending batch and the manifest as recorded, before a storage-form column is made live; a column is made live under the rows' own data context, only when the bytes match. - get_table_schema of a stored table is the manifest's, metadata included. - Helpers no longer take a table name only for messages; full docstrings. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 41 +- .../databases/connector_arrow_database.py | 172 +++-- .../databases/spiraldb_store_tables.py | 614 ++++++++++++------ .../test_spiraldb_store_mode.py | 380 ++++++++++- 4 files changed, 932 insertions(+), 275 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index d7bdb1077..19c28c45e 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -55,24 +55,36 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. - A stored or pending id raises unless `skip_duplicates`, as for every connector (`ConnectorArrowDatabase.add_records`). -- `existing_record_ids` is answered by key: one scan of the key column, filtered by SpiralDB - to the range from the smallest to the largest id asked, intersected here. No other column - is read. +- `existing_record_ids` is answered by one scan of the key column alone, with no filter, + intersected here with the ids asked. No other column is read. It never reads a range of + ids: how the service orders binary values is not measured, and a range taken in another + order than the service's would hide a stored id (review round 1). spiral-sdk 0.16.78 has + no membership expression; one equality per id would be a request per id, or an `or_` + chain as long as the ids, whose cost on the service is not measured either. The key + column alone is the cheapest order-independent read available; a keyed lookup can + replace it when the SDK offers one. - A flush never overwrites a stored row. A SpiralDB append replaces a row of the same key, - so the store writes only the keys the table does not hold (the same key-range read): a + so the store writes only the keys the table does not hold (the same key-column read): a key another writer stored after this one's add keeps its first commit, as with every other connector. - Storage metadata must match on append: the stored schema (the manifest's, logical types live) is held as for any connector that keeps field metadata (`_refuse_changed_columns`), and the store compares the rows with the manifest again when it writes. -## Open question - -The key-range read assumes SpiralDB orders a binary key column by its bytes, as the fake -does. The service's equality on binary literals is measured; its order on them is not. -A live check needs throwaway tables, and how to drop them is a pending developer decision. -Until it is measured, a wrong order would let a stored key go unseen: the add check would -miss a duplicate, and a flush could overwrite that row. +## Finding a table, and what is kept + +- A table's name is opened on every call: a table can be renamed and another made under + its name, so nothing is read or written through an earlier answer. What a table that + holds rows records (key, identity record, manifest) is kept by its table id. +- What a first write records is kept only once its append succeeded. A failed append + (also one the service stored before the error reached the client) forgets it, and the + next call judges the table again. +- A logical type's identifier bytes are compared as given, before a storage-form column is + made live, against the pending batch and the manifest as recorded (ITL-1371). A column + is made live, under the rows' own data context, only when the live type states exactly + the bytes given. +- `get_table_schema` of a stored table is the manifest's schema, field and schema metadata + included, as a read gives it. ## Tests @@ -81,8 +93,11 @@ miss a duplicate, and a flush could overwrite that row. - each table kind (`pdb_v2`, `rdb_v1`, `odb_v3`, `sdb_v2`, `tdb_v2`) written by a job (a function node, a logged operator node, a sink) and a `CachedSource`, listed and read back by a fresh connector, and a second run that calls and delivers nothing; sync and async; -- a new input adds rows to every table and leaves the stored rows unchanged; -- the ITL-1386 rules, the key-range read (several ids, in both orders), refusals of +- a new input adds rows to every table and leaves the stored rows unchanged, sync and + async; `job.run()` and `job.run_async()` with an observer, and a rerun that holds rows; +- the ITL-1386 rules, the key-column read (several ids, in both orders, under a service + that orders binary values otherwise), failed appends, renamed and replaced tables, + identifier bytes on both sides, refusals of foreign tables, the data-context checks, the path domain, listing, concurrent first writers, and that a plain connector still writes nothing. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 3b1ebd4e1..9088c9d14 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -44,6 +44,12 @@ from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, + declaration_form_field, + storage_form_schema, +) from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, require_store_path_domain, @@ -115,51 +121,49 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] -def _with_live_logical_types(records: pa.Table) -> pa.Table: - """Return ``records`` with every registered logical type given in storage form live. +def _with_live_logical_types( + records: pa.Table, converter: "LogicalTypeConverterProtocol" +) -> pa.Table: + """Return ``records`` with each column given in a logical type's storage form live, + when that changes nothing about its identifier. - For a SpiralDB store only (ITL-1840): its manifest records one form of each column. - A column in storage form carries its identifier as ``ARROW:extension:*`` field - metadata. When the default data context's type converter has the type registered, - the column is wrapped as that live type, the form the store reads back, so one - column is compared in one form. Any other column, an identifier no type is - registered for included, is kept exactly as given: nothing is registered here. - """ - from orcapod.contexts import get_default_context + For a SpiralDB store only (ITL-1840): rows are buffered and recorded in one form, so + a column given in storage form (its identifier as ``ARROW:extension:*`` field + metadata) is wrapped as the live type the rows' data context resolves for it, the + rule a read applies (``declaration_form_field``: a registered type, or one a factory + rebuilds from the identifier). A column is wrapped only when the live type states + exactly the identifier bytes given: one the reader also reads under other bytes (an + older identifier) is kept as given, so the bytes are never replaced + (ITL-1371). Any other column, an identifier nothing resolves included, is kept + exactly as given. - # The context's converter implements the logical-type side of - # ``logical_types.protocols.TypeConverterProtocol`` (as Delta's read uses it). - converter = cast( - "LogicalTypeConverterProtocol", - cast(object, get_default_context().type_converter), - ) + Args: + records: The rows, in their large variants. + converter: The type converter of the rows' data context. - def registered(name: bytes) -> bool: - try: - text = name.decode() - except UnicodeDecodeError: - return False # no type is registered under bytes: kept as given - return converter.get_logical_type_by_arrow_extension_name(text) is not None - - known = [ - i - for i, field in enumerate(records.schema) - if (name := (field.metadata or {}).get(b"ARROW:extension:name")) is not None - and registered(name) - ] - if not known: - return records - wrapped = converter.apply_logical_types(records.select(known)) - for i, position in enumerate(known): - field = wrapped.schema.field(i) - metadata = dict(field.metadata or {}) + Returns: + The rows, with the columns wrapped. + + Raises: + LogicalTypeIdentifierError: If a column names a known logical type with + metadata or storage that type does not read, naming the column. + """ + for position, field in enumerate(records.schema): if isinstance(field.type, pa.BaseExtensionType): - # A wrapped column states its identifier in its type: not in metadata too. - _ = metadata.pop(b"ARROW:extension:name", None) - _ = metadata.pop(b"ARROW:extension:metadata", None) - records = records.set_column( - position, field.with_metadata(cast(Any, metadata)), wrapped.column(i) - ) + continue + metadata = field.metadata or {} + name = metadata.get(EXTENSION_NAME_KEY) + if name is None: + continue + declared = declaration_form_field(field, converter) + live = declared.type + if not isinstance(live, pa.ExtensionType) or live.storage_type != field.type: + continue + given = (name, metadata.get(EXTENSION_METADATA_KEY, b"")) + if (live.extension_name.encode(), live.__arrow_ext_serialize__()) != given: + continue # another identifier the reader reads: kept as given + column = live.wrap_array(records.column(position)) + records = records.set_column(position, declared, column) return records @@ -606,6 +610,9 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: pending = self._pending_batches.get(record_key) return None if pending is None else pending.schema schema, name = table + if (store := self._spiral) is not None: + # As recorded: field and schema metadata included, as a read gives. + return store.arrow_schema(name) return pa.schema( pa.field(column.name, column.arrow_type, nullable=column.nullable) for column in self._column_info(name, schema) @@ -761,11 +768,29 @@ def add_records( table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) records = normalize_table_to_large_types(records, keep_null=True) + # The schemas a SpiralDB store holds for the table, as recorded. + recorded: list[pa.Schema] = [] if (store := self._spiral) is not None: + from orcapod.contexts import resolve_context + + # The identifier bytes as given, against those held as recorded, before + # any form is converted (ITL-1371). + recorded = self._recorded_schemas(record_path) + self._refuse_changed_columns( + record_path, + storage_form_schema(records.schema), + recorded, + identity_only=True, + ) # A logical type given in its storage form is the same column as one given - # live: compared, buffered and stored in one form. The rows' data context - # is checked against the one the table records, before they are buffered. - records = _with_live_logical_types(records) + # live: buffered and stored in one form, resolved under the rows' own data + # context. That context is checked against the one the table records, + # before the rows are buffered. + converter = resolve_context(store.data_context(records)).type_converter + records = _with_live_logical_types( + records, + cast("LogicalTypeConverterProtocol", cast(object, converter)), + ) store.validate(records, table_name) else: self._connector.validate_records(records) @@ -791,10 +816,21 @@ def add_records( # A column of another logical type is refused first, on the raw identifier # bytes, before the reorder compares types (ITL-1371). # The held schemas are gathered once for both checks (one table listing). - held = self._held_schemas(record_path) - self._refuse_changed_columns(record_path, records, held, identity_only=True) - records = in_held_column_order(records, self._held_column_order(record_path)) - self._refuse_changed_columns(record_path, records, held) + if store is not None: + # Compared as recorded: every logical type in its storage form. + records = in_held_column_order( + records, self._held_column_order(record_path) + ) + self._refuse_changed_columns( + record_path, storage_form_schema(records.schema), recorded + ) + else: + held = self._held_schemas(record_path) + self._refuse_changed_columns(record_path, records, held, identity_only=True) + records = in_held_column_order( + records, self._held_column_order(record_path) + ) + self._refuse_changed_columns(record_path, records, held) records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) @@ -933,10 +969,34 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: held.append(stored) return held + def _recorded_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema]: + """The schemas a SpiralDB store holds for a table, as recorded: the pending + batch's and the stored manifest's, every logical type in its storage form with + the identifier bytes it was given with (``_with_live_logical_types`` never + replaces them). For the identifier check, before any form is converted. + + Args: + record_path: The table's path, relative to ``base_path``. + + Returns: + The schemas, pending first. + """ + store = self._spiral + assert store is not None + held: list[pa.Schema] = [] + record_key = self._get_record_key(record_path) + pending = self._pending_batches.get(record_key) + if pending is not None: + held.append(storage_form_schema(pending.schema)) + table_name = self._path_to_table_name(self._path_prefix + record_path) + if store.has_table(table_name): + held.append(store.recorded_schema(table_name)) + return held + def _refuse_changed_columns( self, record_path: tuple[str, ...], - records: pa.Table, + records: pa.Table | pa.Schema, held: list[pa.Schema] | None, *, identity_only: bool = False, @@ -962,7 +1022,8 @@ def _refuse_changed_columns( # A column of another logical type would read back as the held one (ITL-1371). changed = first_logical_identity_change(held, records) if changed is None and not identity_only: - changed = first_changed_column(held, records.schema) + schema = records if isinstance(records, pa.Schema) else records.schema + changed = first_changed_column(held, schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " @@ -1158,8 +1219,15 @@ def _write_ready_batch( store = self._spiral if store is not None: # The rows against the table as it is now: it may have been made since - # they were buffered, recording another data context. + # they were buffered, recording another data context or other identifiers + # (compared as recorded, before any form is converted: ITL-1371). store.validate(pending, table_name) + if table_exists: + self._refuse_changed_columns( + self._record_path_from_key(record_key), + storage_form_schema(pending.schema), + [store.recorded_schema(table_name)], + ) columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). existing = self._stored_columns(table_name, schema) if table_exists else None @@ -1167,7 +1235,7 @@ def _write_ready_batch( if check is not None: check(pending.schema if existing is None else pa.schema(existing)) if existing is not None: - if self.keeps_field_metadata: + if self.keeps_field_metadata and store is None: # A different handle may have created the table after this batch # was queued. The connector's ColumnInfo omits field metadata. held = self._read_stored_schema(table_name, schema) diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index c1057c12c..febbe5c33 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -15,8 +15,12 @@ creation that stopped before its first rows) is new to any first writer. - Rows are encoded on write and decoded on read by the codec; a read gives the logical columns, logical types live. -- Which of a set of record ids a table holds is answered by key: one read of the key - column over the range of the asked ids (``existing_record_ids``). +- Which of a set of record ids a table holds is answered by one read of the key column + alone and a set intersection (``existing_record_ids``): never by a range of ids, which + would rely on how the service orders binary values. +- A table's name is opened on every call (a table can be renamed and another made under + its name); what a table holding rows records is kept by its table id, and only once an + append to it succeeded or a read found its rows. - 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). @@ -29,7 +33,7 @@ from __future__ import annotations from collections.abc import Callable, Collection, Iterator, Mapping -from contextlib import AbstractContextManager +from contextlib import AbstractContextManager, contextmanager from dataclasses import dataclass from typing import Any, Protocol, cast @@ -99,19 +103,39 @@ def keyed_table_by_id(self, table_id: str) -> _KeyedTable: ... @dataclass(frozen=True) class _Found: - """A store table that holds rows, with what its metadata records.""" + """A store table that holds rows, with what its metadata records. + + Attributes: + table_id: SpiralDB's id of the table. + record: Its identity record. + manifest: Its manifest. + """ table_id: str record: identity.StoreTableRecord manifest: codec.StoreManifest +@dataclass(frozen=True) +class _Opened: + """A store table found under its name now: what it records, and the snapshot it + was opened as (every read and write of the call goes through that snapshot). + + Attributes: + found: What the table records. + table: The snapshot opened under the name. + """ + + found: _Found + table: _KeyedTable + + class StoreTables: """The store tables of one SpiralDB dataset. Args: client: A spiral-sdk client. - sdk: The spiral-sdk module (its error class and scan expressions). + sdk: The spiral-sdk module (its error class). project_id: The project. dataset: The dataset. open_table: Opens a keyed table by name; ``None`` when there is none. @@ -137,7 +161,10 @@ def __init__( 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] = {} + # What a table that holds rows records, by its id: a table's key, record and + # manifest never change once it holds rows. Which table a name opens is asked + # on every call (a table can be renamed, and another made under its name). + self._found_by_id: dict[str, _Found] = {} self._records_by_id: dict[str, identity.StoreTableRecord] = {} # What each table recorded when it was last judged new (``_seen_manifest``): a # first write may record a table only as it was then. @@ -151,7 +178,16 @@ def __init__( 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``.""" + """Why the codec cannot keep a column. + + Args: + name: The column's name. + arrow_type: Its Arrow type. + primary_key: Whether it is the record id column. + + Returns: + The reason, or ``None`` when the codec keeps it. + """ if primary_key: if name == codec.KEY_COLUMN and pa.types.is_large_binary(arrow_type): return None @@ -163,10 +199,31 @@ def unstorable_column_reason( return str(exc) return None + def data_context(self, records: pa.Table) -> str: + """Return the one data context of rows to store (``_one_data_context``). + + Args: + records: The rows. + + Returns: + Their data context key. + + Raises: + ValueError: If the rows hold no data context column, a null or several + values in it. + InputValidationError: If the data context is not one this Orcapod has. + """ + return _one_data_context(records) + def validate(self, records: pa.Table, table_name: str | None) -> None: """Check rows to buffer: their one data context, the one the table at - ``table_name`` records when it holds rows (``None``: no table in particular), - and the codec on the last row of each key, as kept. + ``table_name`` records when it holds rows, and the codec on the last row of each + key, as kept. + + Args: + records: The rows. + table_name: A name ``table_name`` returned, or ``None`` for no table in + particular. Raises: ValueError: If the rows hold no data context column, a null or several @@ -174,14 +231,16 @@ def validate(self, records: pa.Table, table_name: str | None) -> None: InputValidationError: If the data context is not one this Orcapod has, or not the table's. UnstorableInSpiralError: If the codec refuses the rows. + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. """ if records.num_rows == 0: return context = _one_data_context(records) if table_name is not None: - found = self._judge(table_name) - if found is not None: - _require_data_context(found, context) + opened = self._judge(table_name) + if opened is not None: + _require_data_context(opened.found, context) _ = codec.encode_rows(_last_of_each_key(records)) # ── names ──────────────────────────────────────────────────────────────── @@ -189,6 +248,12 @@ def validate(self, records: pa.Table, table_name: str | None) -> None: def table_name(self, path: tuple[str, ...]) -> str: """Return the table name of a full record path, and remember the path. + Args: + path: The full record path. + + Returns: + The table's name. + Raises: ValueError: If the path is outside the store path domain (``store_table_names.require_store_path_domain``), which the table's @@ -208,38 +273,76 @@ def _path_of(self, table_name: str) -> tuple[str, ...]: ) return path + @contextmanager + def _about(self, table_name: str) -> Iterator[None]: + """Name the table on a refusal raised inside: a collision error is raised again + with the table, any other error gets a note naming it. + + Args: + table_name: The table's name in the dataset. + """ + try: + yield + except SpiralStoreTableCollisionError as exc: + if exc.table is not None: + raise + raise SpiralStoreTableCollisionError( + exc.reason, table=self._qualified(table_name) + ) from exc + except Exception as exc: + exc.add_note(f"SpiralDB store table {self._qualified(table_name)}") + raise + # ── 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 new: no rows yet, with or without a record (spec 2.5: any first - writer records it again). Only a found table is kept. + def _judge(self, table_name: str) -> _Opened | None: + """Return the table under a name now if it holds rows of this path; ``None`` if + it is absent or new: no rows yet, with or without a record (spec 2.5: any first + writer records it again). + + The name is opened on every call, so a table renamed away, or replaced by + another under the name, is never read or written through an earlier answer; + what a table holding rows records is read once per table id. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The table and what it records, or ``None``. Raises: SpiralStoreTableCollisionError: If the table's key is not the store's, it records another path or format, or it holds rows without a manifest. """ - found = self._found.get(table_name) - if found is not None: - return found - path = self._path_of(table_name) + with self._about(table_name): + return self._judge_table(table_name, self._path_of(table_name)) + + def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Opened | None: + """``_judge`` without naming the table on a refusal. + + Args: + table_name: A name ``table_name`` returned. + path: The full record path it was computed from. + + Returns: + The table and what it records, or ``None``. + """ table = self._open_table(table_name) if table is None: self._judged[table_name] = ("none", None) self._empty.discard(table_name) return None - self._require_key(table, table_name) - with self._service_call(f"read the metadata of {table_name}"): + known = self._found_by_id.get(str(table.resource_id)) + if known is not None and known.record.path == path: + self._empty.discard(table_name) + return _Opened(known, table) + _require_key(table, self._service_call) + with self._service_call("read the metadata of a store table"): metadata = table.get_metadata() - try: - record = identity.read_store_table_metadata(metadata) - if record is not None: - identity.require_store_table_path(record, path) - except SpiralStoreTableCollisionError as exc: - raise SpiralStoreTableCollisionError( - exc.reason, table=self._qualified(table_name) - ) from exc - if not self._holds_rows(table): + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + if not _holds_rows(table, self._service_call): # New: its first write records it, unless what it saw here changed. self._judged[table_name] = _seen_manifest(metadata, path) self._empty.add(table_name) @@ -247,51 +350,24 @@ def _judge(self, table_name: str) -> _Found | None: try: manifest = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: - raise SpiralStoreTableCollisionError( - str(exc), table=self._qualified(table_name) - ) from exc + raise SpiralStoreTableCollisionError(str(exc)) from exc if record is None or manifest is None: - raise SpiralStoreTableCollisionError( - "it holds rows but no store manifest", - table=self._qualified(table_name), - ) + raise SpiralStoreTableCollisionError("it holds rows but no store manifest") found = _Found(str(table.resource_id), record, manifest) - self._found[table_name] = found + self._found_by_id[found.table_id] = found self._empty.discard(table_name) - return found + return _Opened(found, table) def has_table(self, table_name: str) -> bool: - """Whether the store table at a computed name holds rows (and a manifest).""" - return self._judge(table_name) is not None + """Whether the store table at a computed name holds rows (and a manifest). - 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 whose key is not the store's: ``__record_id``, binary.""" - key_type = None - if tuple(table.key_columns) == (codec.KEY_COLUMN,): - with self._service_call(f"read the schema of {table_name}"): - key_type = table.schema().field(codec.KEY_COLUMN).type - if key_type is not None and ( - pa.types.is_binary(key_type) or pa.types.is_large_binary(key_type) - ): - return - if tuple(table.key_columns) == (codec.KEY_COLUMN,): - raise SpiralStoreTableCollisionError( - f"its key {codec.KEY_COLUMN!r} is {key_type}, not binary", - table=self._qualified(table_name), - ) - raise SpiralStoreTableCollisionError( - f"its key columns are {list(table.key_columns)}, " - + f"not [{codec.KEY_COLUMN!r}]", - table=self._qualified(table_name), - ) + Args: + table_name: A name ``table_name`` returned. + """ + return self._judge(table_name) is not None def _qualified(self, table_name: str) -> str: + """The table as ``"//
"``.""" return f"{self._project_id}/{self._dataset}/{table_name}" # ── listing ────────────────────────────────────────────────────────────── @@ -305,6 +381,13 @@ def table_paths( 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. + + Args: + prefix: The full path prefix. + pending: The full paths of tables with rows not written yet. + + Returns: + The paths, sorted. """ start = identity.spiral_store_table_name_prefix(prefix) found = {p for p in pending if p[: len(prefix)] == prefix} @@ -313,7 +396,8 @@ def table_paths( for table_id, table_name in listed.items(): if not table_name.startswith(start): continue - record = self._record_of(table_id, table_name) + with self._about(table_name): + 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) @@ -324,42 +408,73 @@ def _record_of( """The record of a listed table, read once per id; ``None`` without one. The name it is listed under now is checked against its record on every call, - the cached one included: a table renamed keeps its id.""" + the cached one included: a table renamed keeps its id. + + Args: + table_id: The listed table's id. + table_name: The name it is listed under. + """ record = self._records_by_id.get(table_id) if record is None: - with self._service_call(f"read the metadata of {table_name}"): + with self._service_call("read the metadata of a store table"): metadata = self._client.keyed_table_by_id(table_id).get_metadata() - try: - record = identity.read_store_table_metadata(metadata) - except SpiralStoreTableCollisionError as exc: - raise SpiralStoreTableCollisionError( - exc.reason, table=self._qualified(table_name) - ) from exc + record = identity.read_store_table_metadata(metadata) if record is None: return None # never kept: its record may be written later self._records_by_id[table_id] = record if identity.spiral_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), + f"it records path {list(record.path)}, whose table has another name" ) return record # ── reading ────────────────────────────────────────────────────────────── def _require(self, table_name: str) -> _Found: - found = self._judge(table_name) - if found is None: + """What the table under a name records. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If no table under the name holds rows. + """ + opened = self._judge(table_name) + if opened is None: raise KeyError(f"no store table {self._qualified(table_name)}") - return found + return opened.found + + def recorded_schema(self, table_name: str) -> pa.Schema: + """The logical schema the table's manifest records, exactly as recorded: a + logical type in its storage form with the identifier bytes it was written with. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If the table holds no rows. + """ + return self._require(table_name).manifest.schema def arrow_schema(self, table_name: str) -> pa.Schema: - """The schema rows of the table are read with: logical types live.""" + """The schema rows of the table are read with: logical types live, field and + schema metadata as recorded. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If the table holds no rows. + """ found = self._require(table_name) return _live(found.manifest.schema, found.record.data_context_key) def column_info(self, table_name: str) -> list[ColumnInfo]: - """The table's columns, as ``arrow_schema`` gives them.""" + """The table's columns, as ``arrow_schema`` gives them. + + Args: + table_name: A name ``table_name`` returned. + """ return [ ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) for f in self.arrow_schema(table_name) @@ -368,17 +483,21 @@ def column_info(self, table_name: str) -> list[ColumnInfo]: def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: """Every row of the table, decoded; nothing for a table with no rows. + Args: + table_name: A name ``table_name`` returned. + Raises: KeyError: If there is no table at the name. """ - found = self._judge(table_name) - if found is None: + opened = self._judge(table_name) + if opened is None: if table_name in self._empty: return # it exists, with no rows raise KeyError(f"no store table {self._qualified(table_name)}") + found = opened.found schema = _live(found.manifest.schema, found.record.data_context_key) - with self._service_call(f"read {table_name}"): - stored = self._client.keyed_table_by_id(found.table_id).scan().to_table() + with self._about(table_name), self._service_call("read a store table"): + stored = opened.table.scan().to_table() if stored.num_rows == 0: return rows = codec.decode_rows(stored, found.manifest, schema) @@ -389,39 +508,60 @@ def existing_record_ids( ) -> set[bytes]: """Return the ids among ``ids`` the table at ``table_name`` holds. - One read of the key column over the range from the smallest to the largest id - asked, filtered here; nothing else of the table is read. Nothing for a table - that is absent or holds no rows. + One read of the key column alone, and the intersection here. Never a range or + an ordering of the ids: how the service orders binary values is not measured, + and a range read in another order than the service's would miss stored ids (a + stored row would then be replaced). spiral-sdk 0.16.78 has no membership + expression, and an equality per id is one request per id or an expression as + long as the ids. Nothing for a table that is absent or holds no rows. Args: table_name: A name ``table_name`` returned. ids: Record ids. + + Returns: + The ids the table holds. """ - found = self._judge(table_name) - if found is None or not ids: + if not ids: return set() - asked = sorted(set(ids)) - sdk = self._sdk - key = sdk.column(codec.KEY_COLUMN) - # The key is stored as ``binary`` (spiral-sdk reads it in its small variant). - low = sdk.gte(key, sdk.literal(asked[0], pa.binary())) - high = sdk.lte(key, sdk.literal(asked[-1], pa.binary())) - with self._service_call(f"read the keys of {table_name}"): - stored = ( - self._client.keyed_table_by_id(found.table_id) - .scan([codec.KEY_COLUMN], filter=sdk.and_(low, high)) - .to_table() - ) + opened = self._judge(table_name) + if opened is None: + return set() + with self._about(table_name): + return self._held_ids(opened.table, ids) + + def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: + """The ids among ``ids`` a snapshot holds (``existing_record_ids``). + + Args: + table: The snapshot opened under the table's name. + ids: Record ids. + + Returns: + The ids it holds. + """ + with self._service_call("read the keys of a store table"): + stored = table.scan([codec.KEY_COLUMN]).to_table() held = cast( "list[bytes]", stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), ) - return set(asked).intersection(held) + return set(ids).intersection(held) # ── writing ────────────────────────────────────────────────────────────── def _create_or_open(self, table_name: str) -> _KeyedTable: - """The table at a computed name, created now if absent.""" + """The table at a computed name, created now if absent. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The table, as opened under the name after any creation. + + Raises: + KeyError: If no table is under the name even after it was created. + """ table = self._open_table(table_name) if table is not None: return table @@ -440,7 +580,7 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: return table def _unchanged_since_judged( - self, table: _KeyedTable, table_name: str, path: tuple[str, ...], seen: _Seen + self, table: _KeyedTable, path: tuple[str, ...], seen: _Seen ) -> bool: """Whether a table opened to be recorded is still as it was judged new: an equivalent manifest (or none; compared by name, never by order or bytes) and no @@ -452,34 +592,38 @@ def _unchanged_since_judged( record the table between this read and the write. Concurrent writers are not supported until the lease (ITL-1452). + Args: + table: The table, opened under its name. + path: The full record path the name was computed from. + seen: What the table recorded when it was judged new. + + Returns: + Whether it is unchanged. + Raises: SpiralStoreTableCollisionError: If the table's identity record, read with the manifest, is of another path or cannot be read: an identity is never recorded over. """ - with self._service_call(f"read the metadata of {table_name}"): + with self._service_call("read the metadata of a store table"): metadata = table.get_metadata() - try: - record = identity.read_store_table_metadata(metadata) - if record is not None: - identity.require_store_table_path(record, path) - except SpiralStoreTableCollisionError as exc: - raise SpiralStoreTableCollisionError( - exc.reason, table=self._qualified(table_name) - ) from exc + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) now = _seen_manifest(metadata, path) - return _same_seen(now, seen) and not self._holds_rows(table) + return _same_seen(now, seen) and not _holds_rows(table, self._service_call) def _require_same_manifest( - self, - table: _KeyedTable, - table_name: str, - path: tuple[str, ...], - manifest: codec.StoreManifest, + self, table: _KeyedTable, path: tuple[str, ...], manifest: codec.StoreManifest ) -> _Found: """Refuse a table another writer recorded since it was judged, unless it records the same manifest: another writer's record is never overwritten. + Args: + table: The table, opened under its name. + path: The full record path the name was computed from. + manifest: The manifest this writer would record. + Returns: The table as it is recorded: its record and manifest stay, not this writer's equivalent ones. @@ -488,24 +632,18 @@ def _require_same_manifest( SpiralStoreTableCollisionError: If it records another path or manifest, or holds rows without one. """ - with self._service_call(f"read the metadata of {table_name}"): + with self._service_call("read the metadata of a store table"): metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) try: - record = identity.read_store_table_metadata(metadata) - if record is not None: - identity.require_store_table_path(record, path) current = None if record is None else codec.read_manifest(metadata, path) - except (SpiralStoreTableCollisionError, codec.ManifestError) as exc: - reason = ( - exc.reason if isinstance(exc, SpiralStoreTableCollisionError) else exc - ) - raise SpiralStoreTableCollisionError( - str(reason), table=self._qualified(table_name) - ) from exc + except codec.ManifestError as exc: + raise SpiralStoreTableCollisionError(str(exc)) from exc if record is None or current is None or not _same_manifest(current, manifest): raise SpiralStoreTableCollisionError( - "another writer recorded it since it was judged, with another manifest", - table=self._qualified(table_name), + "another writer recorded it since it was judged, with another manifest" ) return _Found(str(table.resource_id), record, current) @@ -516,6 +654,14 @@ def write(self, table_name: str, records: pa.Table) -> None: refuses a stored id when the rows are added (unless asked to skip it), and a key another writer stored since is left as that writer stored it. + What a table records is kept only once an append to it succeeded; a write that + fails forgets it, so the next call judges the table again as the service has it + (also when the service stored the rows before the error reached this client). + + Args: + table_name: A name ``table_name`` returned. + records: The rows, record id column included. + Raises: ValueError: If the rows hold no ``__data_context`` column, or several data contexts, their path cannot be recorded, or their columns are not the @@ -528,70 +674,148 @@ def write(self, table_name: str, records: pa.Table) -> None: """ path = self._path_of(table_name) context = _one_data_context(records) - found = self._judge(table_name) - if found is None: - manifest = codec.new_manifest(path, path[-1], records.schema) - metadata = { - **identity.store_table_metadata(path, context), - **codec.manifest_entries(manifest), - } - encoded = _encoded(records) - if encoded.num_rows == 0: - return # nothing to write, so nothing is created - seen = self._judged.pop(table_name, ("none", None)) - table = self._create_or_open(table_name) - self._require_key(table, table_name) - if self._unchanged_since_judged(table, table_name, path, seen): - with self._service_call(f"record {table_name}"): - table.set_metadata(metadata) - recorded = _Found( - str(table.resource_id), - identity.StoreTableRecord(path, path[-1], context), - manifest, - ) - self._found[table_name] = recorded - self._empty.discard(table_name) - else: - recorded = self._require_same_manifest( - table, table_name, path, manifest + opened = self._judge(table_name) + with self._about(table_name): + if opened is None: + self._write_first(table_name, path, context, records) + return + found = opened.found + _require_data_context(found, context) + 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" ) - _require_data_context(recorded, context) - self._found[table_name] = recorded - self._empty.discard(table_name) - # Another writer may have written these keys meanwhile. - encoded = _encoded(self._without_stored_keys(table_name, records)) - if encoded.num_rows > 0: - with self._service_call(f"write {table_name}"): - _ = table.append(encoded) - return - _require_data_context(found, context) - 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" + encoded = _encoded( + _without_ids(records, self._held_ids(opened.table, _ids(records))) ) - encoded = _encoded(self._without_stored_keys(table_name, records)) + if encoded.num_rows == 0: + return # a write of no rows is never sent + self._append(opened.table, found, encoded) + + def _write_first( + self, + table_name: str, + path: tuple[str, ...], + context: str, + records: pa.Table, + ) -> None: + """The first write of a table judged absent or new (``write``). + + Args: + table_name: A name ``table_name`` returned. + path: The full record path it was computed from. + context: The rows' data context. + records: The rows, record id column included. + """ + manifest = codec.new_manifest(path, path[-1], records.schema) + metadata = { + **identity.store_table_metadata(path, context), + **codec.manifest_entries(manifest), + } + encoded = _encoded(records) if encoded.num_rows == 0: - return # a write of no rows is never sent - table = self._client.keyed_table_by_id(found.table_id) - with self._service_call(f"write {table_name}"): - _ = table.append(encoded) - - def _without_stored_keys(self, table_name: str, records: pa.Table) -> pa.Table: - """The rows whose key the table does not hold yet (``existing_record_ids``).""" - ids = cast("list[bytes]", records.column(codec.KEY_COLUMN).to_pylist()) - held = self.existing_record_ids(table_name, ids) - if not held: - return records - return records.filter( - pc.invert( - pc.is_in( - records.column(codec.KEY_COLUMN), - pa.array(sorted(held), pa.large_binary()), - ) + return # nothing to write, so nothing is created + seen = self._judged.pop(table_name, ("none", None)) + table = self._create_or_open(table_name) + _require_key(table, self._service_call) + if self._unchanged_since_judged(table, path, seen): + with self._service_call("record a store table"): + table.set_metadata(metadata) + recorded = _Found( + str(table.resource_id), + identity.StoreTableRecord(path, path[-1], context), + manifest, + ) + else: + recorded = self._require_same_manifest(table, path, manifest) + _require_data_context(recorded, context) + # Another writer may have written these keys meanwhile. + held = self._held_ids(table, _ids(records)) + encoded = _encoded(_without_ids(records, held)) + self._empty.discard(table_name) + if encoded.num_rows > 0: + self._append(table, recorded, encoded) + + def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: + """Append encoded rows; keep what the table records only once that succeeded. + + Args: + table: The table, opened under its name. + found: What it records. + encoded: The rows, encoded. + """ + try: + with self._service_call("write a store table"): + _ = table.append(encoded) + except BaseException: + # The service may hold the rows, some, or none: judged again next call. + _ = self._found_by_id.pop(found.table_id, None) + raise + self._found_by_id[found.table_id] = found + + +def _require_key( + table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] +) -> None: + """Refuse a table whose key is not the store's: ``__record_id``, binary. + + Args: + table: The table. + service_call: The store's ``service_call``. + + Raises: + SpiralStoreTableCollisionError: If its key is another. + """ + key_type = None + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + with service_call("read the schema of a store table"): + key_type = table.schema().field(codec.KEY_COLUMN).type + if key_type is not None and ( + pa.types.is_binary(key_type) or pa.types.is_large_binary(key_type) + ): + return + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + raise SpiralStoreTableCollisionError( + f"its key {codec.KEY_COLUMN!r} is {key_type}, not binary" + ) + raise SpiralStoreTableCollisionError( + f"its key columns are {list(table.key_columns)}, not [{codec.KEY_COLUMN!r}]" + ) + + +def _holds_rows( + table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] +) -> bool: + """Whether a keyed table has a row. + + Args: + table: The table. + service_call: The store's ``service_call``. + """ + with 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 _ids(records: pa.Table) -> list[bytes]: + """The record ids of rows, in row order.""" + return cast("list[bytes]", records.column(codec.KEY_COLUMN).to_pylist()) + + +def _without_ids(records: pa.Table, held: set[bytes]) -> pa.Table: + """The rows whose id is not in ``held``.""" + if not held: + return records + return records.filter( + pc.invert( + pc.is_in( + records.column(codec.KEY_COLUMN), + pa.array(list(held), pa.large_binary()), ) ) + ) def _last_of_each_key(records: pa.Table) -> pa.Table: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 795b52495..ce5429db3 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -264,9 +264,10 @@ def test_an_id_another_writer_stored_since_the_add_keeps_its_first_commit( [[b"r1", b"r3"], [b"r3", b"r1"], [b"a", b"r2", b"zz"], [b"q"], []], ids=["two", "two reversed", "around the stored", "none stored", "empty"], ) -def test_stored_ids_are_answered_by_one_key_range_read(asked: list[bytes]) -> None: - """``existing_record_ids``: one scan of the key column over the asked range, never - the whole table.""" +def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> None: + """``existing_record_ids``: one scan of the key column alone, with no filter (no + range: how the service orders binary values is not relied on), and a set + intersection.""" connector = store() db = ConnectorArrowDatabase(connector) db.add_records( @@ -280,15 +281,9 @@ def test_stored_ids_are_answered_by_one_key_range_read(asked: list[bytes]) -> No held = tables.existing_record_ids(name, set(asked)) scans = [*fake.scan_log, *fake.count_log] assert held == set(asked) & {b"r0", b"r1", b"r2", b"r3"} - keyed = [s for s in scans if s.columns == ["__record_id"] and s.filter is not None] - if asked: - assert len(keyed) == 1 - (bounds,) = [s.filter.terms for s in keyed] - assert [(n, op) for n, _, op in bounds] == [ - ("__record_id", ">="), - ("__record_id", "<="), - ] - assert [v.value for _, v, _ in bounds] == [min(asked), max(asked)] + keyed = [s for s in scans if s.limit is None] + assert len(keyed) == (1 if asked else 0) + assert all(s.filter is None for s in keyed), keyed assert all(s.columns == ["__record_id"] for s in scans), scans @@ -1034,9 +1029,13 @@ def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: @pytest.mark.usefixtures("root", "_cleared") -def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others() -> None: +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( + orchestrator: str, +) -> None: + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} database = ConnectorArrowDatabase(store()) - _ = _job(database, SOURCE_ROWS[:2]).run() + _ = _job(database, SOURCE_ROWS[:2]).run(orchestrator=run[orchestrator]()) before = { p: database.get_all_records(p, record_id_column="__rid") for p in database.list_table_paths() @@ -1044,7 +1043,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others() -> None: calls.clear() delivered.clear() fresh = ConnectorArrowDatabase(store()) - _ = _job(fresh, SOURCE_ROWS).run() + _ = _job(fresh, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) assert calls == [3] and delivered == [6] for path, earlier in before.items(): assert earlier is not None @@ -1083,3 +1082,354 @@ def test_a_path_outside_the_store_path_domain_is_refused_before_anything( db.flush() assert _tables() == [] assert db.list_table_paths() == [] + + +# ------------------------------------------- review round 1 (PR 692): regressions + + +def _add(db: ConnectorArrowDatabase, data: pa.Table, **kwargs: Any) -> None: + db.add_records(RESULT, data, record_id_column="__record_id", **kwargs) + + +def _get(db: ConnectorArrowDatabase) -> pa.Table | None: + return db.get_all_records(RESULT, record_id_column="__record_id") + + +def _binary_ids(ids: list[bytes], *, offset: int = 0) -> pa.Table: + data = rows(["unused"] * len(ids), offset=offset) + return data.set_column(0, "__record_id", pa.array(ids, pa.large_binary())) + + +def _signed_byte_order(monkeypatch: pytest.MonkeyPatch) -> None: + """Make the fake compare binary values as signed bytes, not unsigned: a service + order the store must not rely on.""" + unsigned = fake._ordered # pyright: ignore[reportPrivateUsage] + + def ordered(value: Any) -> Any: + if isinstance(value, bytes): + return tuple(b if b < 128 else b - 256 for b in value) + return unsigned(value) + + monkeypatch.setattr(fake, "_ordered", ordered) + + +def _failing_append(monkeypatch: pytest.MonkeyPatch, *, after_commit: bool) -> None: + """Make every append fail: before the service stores anything, or after it stored + the rows (the error reaching the client only then).""" + append = fake.FakeKeyedTable.append + + def fail(self: Any, data: pa.Table) -> Any: + if after_commit: + _ = append(self, data) + raise fake.SpiralError("injected append failure") + + monkeypatch.setattr(fake.FakeKeyedTable, "append", fail) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("ids", [[b"\x00", b"\xff"], [b"\xff", b"\x00"]]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_stored_ids_are_found_whatever_order_the_service_gives_binary_values( + monkeypatch: pytest.MonkeyPatch, ids: list[bytes], skip_duplicates: bool +) -> None: + """Finding 1: the existence check reads no range of ids, so a service that orders + binary values in another order than Python's never hides a stored id; no stored row + is replaced, strict or skipping duplicates, in either input order.""" + _signed_byte_order(monkeypatch) + db = ConnectorArrowDatabase(store()) + original = _binary_ids(ids) + _add(db, original, flush=True) + again = _binary_ids(ids, offset=100) + if skip_duplicates: + _add(db, again, skip_duplicates=True, flush=True) + else: + with pytest.raises(ValueError, match="already exist"): + _add(db, again) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(original)) + + +@pytest.mark.usefixtures("root") +def test_a_failed_first_append_leaves_no_table_known( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2: a first write whose append fails keeps nothing: the writer judges the + table again, as a fresh one does (recorded, no rows: new).""" + db = ConnectorArrowDatabase(store()) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["r0"]), flush=True) + fresh = ConnectorArrowDatabase(store()) + assert _get(db) is None and _get(fresh) is None + assert not db.table_exists(RESULT) and not fresh.table_exists(RESULT) + + +@pytest.mark.usefixtures("root") +def test_a_failed_first_append_lets_another_writer_record_the_table_anew( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2: after a failed first append, another writer records the empty table + with other columns; the first writer reads the table as that writer recorded it.""" + first = ConnectorArrowDatabase(store()) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(first, rows(["r0"]), flush=True) + second = ConnectorArrowDatabase(store()) + other = rows(["r1"]).rename_columns( + ["__record_id", "__data_context", "other", "__pod_ts", "s"] + ) + _add(second, other, flush=True) + for reader in (second, first): + got = _get(reader) + assert got is not None + assert by_id(got).equals(by_id(other), check_metadata=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_write", [True, False]) +def test_an_append_stored_before_its_error_reached_the_client_is_judged_again( + monkeypatch: pytest.MonkeyPatch, first_write: bool +) -> None: + """Finding 2: the service stored the rows, then the append raised. Nothing kept + from before the error is trusted: the rows are found, and are never stored + twice or replaced.""" + db = ConnectorArrowDatabase(store()) + if not first_write: + _add(db, rows(["r0"]), flush=True) + given = rows(["r1"], offset=10) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=True) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, given, flush=True) + expected = given if first_write else pa.concat_tables([rows(["r0"]), given]) + for reader in (db, ConnectorArrowDatabase(store())): + assert reader.table_exists(RESULT) + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(expected)) + with pytest.raises(ValueError, match="already exist"): + _add(ConnectorArrowDatabase(store()), rows(["r1"], offset=99)) + + +@pytest.mark.usefixtures("root") +def test_a_failed_append_to_a_table_with_rows_keeps_them( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2, a later write: the stored rows stay, and the table is read again.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["r2"], offset=2), flush=True) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(rows(["r0", "r1"]))) + + +OLDER = b'{"value_hash":"stored","version":0}' +"""Extension metadata of ``orcapod.path`` the tests make the type read too.""" + + +def _reads_an_older_identifier( + monkeypatch: pytest.MonkeyPatch, current: pa.Table, older: bytes +) -> None: + """Make ``orcapod.path`` read ``older`` beside the metadata ``current`` has.""" + from orcapod.contexts import get_default_context + + converter: Any = get_default_context().type_converter + path_type = converter.get_logical_type_by_arrow_extension_name("orcapod.path") + assert path_type is not None + recorded = (current.schema.field("p").metadata or {})[b"ARROW:extension:metadata"] + monkeypatch.setattr( + type(path_type), + "readable_extension_metadata", + lambda self: (recorded, older), # pyright: ignore[reportUnknownLambdaType] + ) + + +def _older_identifier(table: pa.Table, older: bytes) -> pa.Table: + """The table with its storage-form ``p`` column naming ``older`` metadata.""" + field = table.schema.field("p") + metadata: dict[bytes | str, bytes | str] = { + key: value for key, value in (field.metadata or {}).items() + } + metadata[b"ARROW:extension:metadata"] = older + position = table.schema.get_field_index("p") + return table.set_column(position, field.with_metadata(metadata), table.column("p")) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("committed", [False, True]) +@pytest.mark.parametrize("first_live", [True, False]) +def test_an_identifier_the_reader_also_reads_is_still_another_identifier( + monkeypatch: pytest.MonkeyPatch, committed: bool, first_live: bool +) -> None: + """Finding 3: a logical type's identifier bytes are compared as given, before a + storage-form column is made live, against the pending batch and the manifest as + recorded (ITL-1371): one the type also reads (an older identifier) is refused, and + nothing of it is written.""" + first = _with_path_column(rows(["r0"]), live=first_live) + current = _with_path_column(rows(["r1"]), live=False) + _reads_an_older_identifier(monkeypatch, current, OLDER) + older = OLDER + db = ConnectorArrowDatabase(store()) + _add(db, first, flush=committed) + with pytest.raises(InputValidationError, match="'p'"): + _add(db, _older_identifier(current, older)) + db.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + + +@pytest.mark.usefixtures("root") +def test_an_older_identifier_found_only_at_flush_is_refused( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 3, the flush side: rows buffered before another handle recorded the + table with other identifier bytes are compared with the manifest as recorded.""" + current = _with_path_column(rows(["r0"]), live=False) + _reads_an_older_identifier(monkeypatch, current, OLDER) + older = _older_identifier(_with_path_column(rows(["r1"]), live=False), OLDER) + buffered = ConnectorArrowDatabase(store()) + _add(buffered, older) + _add(ConnectorArrowDatabase(store()), current, flush=True) + with pytest.raises(InputValidationError, match="'p'"): + buffered.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("through", ["read", "write"]) +def test_a_table_renamed_away_is_never_used_through_its_earlier_name( + through: str, +) -> None: + """Finding 4: after the table is renamed and a foreign table made under its name, + the handle that knew it refuses the foreign table on read and on write, as a fresh + handle does: the name is resolved on every call.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + fake.FakeClient().project("p").create_keyed_table( + "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) + ) + with pytest.raises(SpiralStoreTableCollisionError): + _get(ConnectorArrowDatabase(store())) + db.refresh_table(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + if through == "read": + _get(db) + else: + _add(db, rows(["r1"]), flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_table_replaced_under_its_name_is_read_as_the_replacement() -> None: + """Finding 4: what a table records is kept by its id, never by its name: another + store table of the same path made under the name is read as itself.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + _add(ConnectorArrowDatabase(store()), rows(["r5"], offset=5), flush=True) + got = _get(db) + assert got is not None and got.column("__record_id").to_pylist() == [b"r5"] + + +@pytest.mark.usefixtures("root") +def test_a_storage_form_column_is_resolved_under_the_rows_data_context( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Should fix: a write resolves a storage-form logical type under the rows' own + data context, as a read does, not the default one.""" + from dataclasses import replace + from types import SimpleNamespace + + from orcapod import contexts + + alternate_key = "std:v2:review" + default = contexts.get_default_context() + alternate = replace(default, context_key=alternate_key) + unaware = replace( + default, + type_converter=SimpleNamespace( + get_logical_type_by_arrow_extension_name=lambda name: None, # pyright: ignore[reportUnknownLambdaType] + register_logical_type_from_arrow_metadata=_raise_value_error, + ), + ) + resolve = contexts.resolve_context + first = _with_path_column(rows(["r0"], context=alternate_key), live=True) + second = _with_path_column(rows(["r1"], context=alternate_key), live=False) + monkeypatch.setattr(contexts, "get_default_context", lambda: unaware) + monkeypatch.setattr( + contexts, + "resolve_context", + lambda key=None: alternate if key == alternate_key else resolve(key), # pyright: ignore[reportUnknownLambdaType] + ) + db = ConnectorArrowDatabase(store()) + _add(db, first, flush=True) + _add(db, second, flush=True) + got = _get(db) + assert got is not None and got.num_rows == 2 + assert isinstance(got.schema.field("p").type, pa.BaseExtensionType) + + +def _raise_value_error(*args: Any) -> Any: + raise ValueError("no type registered") + + +@pytest.mark.usefixtures("root") +def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> None: + """Should fix: ``get_table_schema`` of a stored table is the manifest's, field + metadata included, equal to the schema while the rows are queued.""" + db = ConnectorArrowDatabase(store()) + data = rows(["r0"]) + field = data.schema.field("a.b").with_metadata({b"unit": b"m"}) + data = data.set_column(data.schema.get_field_index("a.b"), field, data["a.b"]) + _add(db, data) + queued = db.get_table_schema(RESULT) + db.flush() + for reader in (db, ConnectorArrowDatabase(store())): + stored = reader.get_table_schema(RESULT) + assert stored is not None and queued is not None + assert stored.equals(queued, check_metadata=True) + assert stored.field("a.b").metadata == {b"unit": b"m"} + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("entry", ["run", "run_async"]) +def test_a_store_backed_job_holds_its_rows_and_reports_observer_losses( + entry: str, +) -> None: + """Should fix: a job on the store through both public entry points; a rerun holds + the rows it ran, and an observer's lost events are reported.""" + import asyncio + import warnings + + from tests.test_pipeline.test_observer_event_losses import ( + StatusObserver, + _database, # pyright: ignore[reportPrivateUsage] + ) + + database = ConnectorArrowDatabase(store()) + job = _job(database, SOURCE_ROWS) + + def run(**kwargs: Any) -> Any: + if entry == "run_async": + return asyncio.run(job.run_async(**kwargs)) + return job.run(**kwargs) + + with warnings.catch_warnings(record=True): + summary = run(observer=StatusObserver(_database())) + assert summary.ok and summary.lost_observer_events["status"].count > 0 + assert sorted(job.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] + calls.clear() + delivered.clear() + held = run() + assert held.nodes["dbl"].held == 3 + assert held.lost_observer_events == {} + assert calls == [] and delivered == [] From ba143785e86dcfbd8802b4f25504eb26428c72f7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 11:35:01 -0800 Subject: [PATCH 13/50] fix(spiraldb): store mode review round 2: one identifier-preserving declaration rule, one name open per operation (ITL-1840) - One declaration rule (declared_keeping_identifier) for the rows buffered and flushed, the schema a table reports and the schema its rows are decoded under: a logical type is made live only when that keeps the identifier bytes recorded. A table first written with an older identifier reads back and appends with it. - Each public operation of ConnectorArrowDatabase opens a table name once and reuses the handle until the store writes to it. - A flush reads keys again only for ids its add did not find absent; a write drops the ids it wrote, a failed append forgets the table's ids. - Plan: the key-range point lookup as the stage E candidate; the key-scan cost as a known limit (ITL-1841). Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 41 ++++- .../databases/connector_arrow_database.py | 65 +++++-- .../databases/spiraldb_store_tables.py | 160 +++++++++++++++-- .../test_spiraldb_store_mode.py | 166 +++++++++++++++++- 4 files changed, 394 insertions(+), 38 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index 19c28c45e..ef374b361 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -61,8 +61,22 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. order than the service's would hide a stored id (review round 1). spiral-sdk 0.16.78 has no membership expression; one equality per id would be a request per id, or an `or_` chain as long as the ids, whose cost on the service is not measured either. The key - column alone is the cheapest order-independent read available; a keyed lookup can - replace it when the SDK offers one. + column alone is the cheapest order-independent read available. +- The stage E candidate for a keyed lookup (review round 2, not adopted here): spiral-sdk + 0.16.78's `KeyedTable.scan(key_ranges=...)` takes several `KeyRange`s with inclusive + `KeyBound`s, so a range whose start and end are both the same key, one per id, would be + a batched point lookup with no ordering assumed in Python. The fake does not model key + ranges and nothing here ran against a live SpiralDB: binary key literals, correctness + (every stored id found, under the service's own order) and the work on the service are + to be validated live before it replaces the key-column read. +- Ids `existing_record_ids` found absent are remembered by table id, and a flush reads + again only the keys of ids not found absent (review round 2): a strict add followed by + its flush reads the keys once. Every write through the store drops the ids it wrote, + and a failed append forgets the table's ids (the service may hold the rows), so a write + by this process is always seen. A write by another writer between the add and the + flush is not: one writer at a time is already the rule, and the lease of stage C + (ITL-1452) makes it the only possibility. A skipping add checks no ids, so its flush + reads the keys. - A flush never overwrites a stored row. A SpiralDB append replaces a row of the same key, so the store writes only the keys the table does not hold (the same key-column read): a key another writer stored after this one's add keeps its first commit, as with every @@ -73,16 +87,24 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. ## Finding a table, and what is kept -- A table's name is opened on every call: a table can be renamed and another made under - its name, so nothing is read or written through an earlier answer. What a table that +- A table's name is opened once per public operation of `ConnectorArrowDatabase` (an add, + a flush, a read, a schema or listing call; `StoreTables.operation`), and that handle + reused within it until the store writes to the table (review round 2). The next + operation opens it again: a table can be renamed and another made under its name, so + nothing is read or written through an earlier operation's answer. What a table that holds rows records (key, identity record, manifest) is kept by its table id. - What a first write records is kept only once its append succeeded. A failed append (also one the service stored before the error reached the client) forgets it, and the next call judges the table again. - A logical type's identifier bytes are compared as given, before a storage-form column is - made live, against the pending batch and the manifest as recorded (ITL-1371). A column - is made live, under the rows' own data context, only when the live type states exactly - the bytes given. + made live, against the pending batch and the manifest as recorded (ITL-1371). +- One declaration rule, `spiraldb_store_tables.declared_keeping_identifier`, gives the + rows buffered and flushed, the schema a table reports and the schema its rows are + decoded under: a column is made live, under the data context of the rows or of the + table, only when the live type states exactly the identifier bytes recorded; one the + type reads under other bytes (an older identifier) stays in its storage form (review + round 2). A table first written with an older identifier reads back, reports its + schema and appends with those bytes. - `get_table_schema` of a stored table is the manifest's schema, field and schema metadata included, as a read gives it. @@ -105,3 +127,8 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. The one-writer lease (ITL-1452), the public switch-on with save and load, the live run, and fewer service calls per run (keyed reads, one existence answer per run). + +Known limit (stage E, ITL-1841): each strict existence check, and each flush of ids not +checked, reads the table's whole key column, so its cost grows with the table's history; +successive batches into a growing table cost quadratically many keys in all. Reads of +stored rows read the whole table the same way. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 9088c9d14..69a6b3939 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -22,8 +22,9 @@ from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext +from functools import wraps from threading import Lock -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, cast from weakref import WeakKeyDictionary, WeakValueDictionary import pyarrow as pa @@ -43,13 +44,11 @@ ) from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiraldb_store_tables import StoreTables -from orcapod.logical_types.canonical_form import ( - EXTENSION_METADATA_KEY, - EXTENSION_NAME_KEY, - declaration_form_field, - storage_form_schema, +from orcapod.databases.spiraldb_store_tables import ( + StoreTables, + declared_keeping_identifier, ) +from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, require_store_path_domain, @@ -130,8 +129,9 @@ def _with_live_logical_types( For a SpiralDB store only (ITL-1840): rows are buffered and recorded in one form, so a column given in storage form (its identifier as ``ARROW:extension:*`` field metadata) is wrapped as the live type the rows' data context resolves for it, the - rule a read applies (``declaration_form_field``: a registered type, or one a factory - rebuilds from the identifier). A column is wrapped only when the live type states + one rule a read and a table's schema apply too (``declared_keeping_identifier``: a + registered type, or one a factory rebuilds from the identifier). A column is + wrapped only when the live type states exactly the identifier bytes given: one the reader also reads under other bytes (an older identifier) is kept as given, so the bytes are never replaced (ITL-1371). Any other column, an identifier nothing resolves included, is kept @@ -151,22 +151,41 @@ def _with_live_logical_types( for position, field in enumerate(records.schema): if isinstance(field.type, pa.BaseExtensionType): continue - metadata = field.metadata or {} - name = metadata.get(EXTENSION_NAME_KEY) - if name is None: - continue - declared = declaration_form_field(field, converter) + declared = declared_keeping_identifier(field, converter) live = declared.type if not isinstance(live, pa.ExtensionType) or live.storage_type != field.type: - continue - given = (name, metadata.get(EXTENSION_METADATA_KEY, b"")) - if (live.extension_name.encode(), live.__arrow_ext_serialize__()) != given: - continue # another identifier the reader reads: kept as given + continue # kept as given: no logical type, or another identifier's bytes column = live.wrap_array(records.column(position)) records = records.set_column(position, declared, column) return records +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def _one_store_operation( + method: "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]", +) -> "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]": + """Run a public method as one operation of a SpiralDB store (``StoreTables.operation``): + each table name is opened once inside it and its handle reused. Any other + connector calls the method as it is. + """ + + @wraps(method) + def wrapped( + self: ConnectorArrowDatabase, *args: _P.args, **kwargs: _P.kwargs + ) -> _R: + if self._spiral_connector is None: # pyright: ignore[reportPrivateUsage] + return method(self, *args, **kwargs) + store = self._spiral # pyright: ignore[reportPrivateUsage] + assert store is not None + with store.operation(): + return method(self, *args, **kwargs) + + return wrapped + + def _alike(parts: list[pa.Table]) -> list[pa.Table]: """Stored and queued rows under one schema when they differ only in a column's nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary @@ -495,6 +514,7 @@ def _stored_conflicts( ) return self._connector.existing_record_ids(name, column, input_ids) + @_one_store_operation def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -561,6 +581,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) return sorted(found) + @_one_store_operation def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a table exists at ``record_path``. @@ -587,6 +608,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── + @_one_store_operation def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the committed or queued schema without fetching rows. @@ -719,6 +741,7 @@ def validate_records(self, records: pa.Table) -> None: return self._connector.validate_records(records) + @_one_store_operation def add_records( self, record_path: tuple[str, ...], @@ -1126,6 +1149,7 @@ def guard_table_schema( self._get_record_key(record_path), check ) + @_one_store_operation def flush(self) -> None: """Insert all ready batches into the connector.""" for record_key in list(self._pending_batches): @@ -1140,6 +1164,7 @@ def flush_result_batch( """Commit a durable result table even if no pipeline records are stored.""" self.flush_batch(record_path) + @_one_store_operation def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) @@ -1308,6 +1333,7 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # ── Read methods ────────────────────────────────────────────────────────── + @_one_store_operation def get_record_by_id( self, record_path: tuple[str, ...], @@ -1357,6 +1383,7 @@ def get_record_by_id( report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) + @_one_store_operation def get_all_records( self, record_path: tuple[str, ...], @@ -1388,6 +1415,7 @@ def get_all_records( table = parts[0] if len(parts) == 1 else pa.concat_tables(_alike(parts)) return self._handle_record_id_column(table, record_id_column) + @_one_store_operation def get_records_by_ids( self, record_path: tuple[str, ...], @@ -1412,6 +1440,7 @@ def get_records_by_ids( return None return self._handle_record_id_column(filtered, record_id_column) + @_one_store_operation def get_records_with_column_value( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index febbe5c33..2bed88580 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -32,6 +32,7 @@ from __future__ import annotations +import threading from collections.abc import Callable, Collection, Iterator, Mapping from contextlib import AbstractContextManager, contextmanager from dataclasses import dataclass @@ -45,7 +46,13 @@ from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain from orcapod.errors import InputValidationError -from orcapod.logical_types.canonical_form import declaration_form_schema +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, + declaration_form_field, + storage_form_field, +) +from orcapod.logical_types.identifier import arrow_type_identifier from orcapod.system_constants import constants from orcapod.types import ColumnInfo @@ -171,6 +178,15 @@ def __init__( self._judged: dict[str, _Seen] = {} # Tables last judged to exist with no rows: new to a writer, and read as no rows. self._empty: set[str] = set() + # Within one public operation (``operation``): what each name was judged, its + # name opened once and its handle reused. Empty outside an operation. + # Kept per thread: an operation is one thread's call. + self._now: threading.local = threading.local() + # Ids ``existing_record_ids`` found absent from a table holding rows, by table + # id: a write of them reads no keys again (``write``). Every write to a table + # through this store goes through ``_append``, which drops what it wrote, and + # drops the table's entry when it fails (the service may hold the rows). + self._absent_by_id: dict[str, set[bytes]] = {} key_column: str = codec.KEY_COLUMN """The key column of every store table.""" @@ -293,6 +309,39 @@ def _about(self, table_name: str) -> Iterator[None]: exc.add_note(f"SpiralDB store table {self._qualified(table_name)}") raise + # ── operations ─────────────────────────────────────────────────────────── + + @contextmanager + def operation(self) -> Iterator[None]: + """One public operation of ``ConnectorArrowDatabase`` (an add, a flush, a read): + each name is opened and judged once inside it, and that handle reused, until + this store writes to the table under it. Operations nest; the handles are + forgotten when the outermost ends, so the next operation opens each name again + (a table can be renamed, and another made under its name, between them). + """ + depth = cast(int, getattr(self._now, "depth", 0)) + if depth == 0: + self._now.judged = {} + self._now.depth = depth + 1 + try: + yield + finally: + self._now.depth = depth + if depth == 0: + self._now.judged = None + + def _judged_now(self) -> dict[str, _Opened | None] | None: + """What each name was judged in this thread's operation; ``None`` outside one.""" + return cast( + "dict[str, _Opened | None] | None", getattr(self._now, "judged", None) + ) + + def _forget_opened(self, table_name: str) -> None: + """Forget a name's handle in the current operation: this store writes to it.""" + judged = self._judged_now() + if judged is not None: + _ = judged.pop(table_name, None) + # ── finding a table ────────────────────────────────────────────────────── def _judge(self, table_name: str) -> _Opened | None: @@ -300,9 +349,10 @@ def _judge(self, table_name: str) -> _Opened | None: it is absent or new: no rows yet, with or without a record (spec 2.5: any first writer records it again). - The name is opened on every call, so a table renamed away, or replaced by - another under the name, is never read or written through an earlier answer; - what a table holding rows records is read once per table id. + The name is opened once per public operation (``operation``; on every call + outside one), so a table renamed away, or replaced by another under the name, is + never read or written through an earlier operation's answer; what a table + holding rows records is read once per table id. Args: table_name: A name ``table_name`` returned. @@ -314,8 +364,14 @@ def _judge(self, table_name: str) -> _Opened | None: SpiralStoreTableCollisionError: If the table's key is not the store's, it records another path or format, or it holds rows without a manifest. """ + judged = self._judged_now() + if judged is not None and table_name in judged: + return judged[table_name] with self._about(table_name): - return self._judge_table(table_name, self._path_of(table_name)) + opened = self._judge_table(table_name, self._path_of(table_name)) + if judged is not None: + judged[table_name] = opened + return opened def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Opened | None: """``_judge`` without naming the table on a refusal. @@ -528,7 +584,10 @@ def existing_record_ids( if opened is None: return set() with self._about(table_name): - return self._held_ids(opened.table, ids) + held = self._held_ids(opened.table, ids) + absent = self._absent_by_id.setdefault(opened.found.table_id, set()) + absent.update(set(ids) - held) + return held def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: """The ids among ``ids`` a snapshot holds (``existing_record_ids``). @@ -687,11 +746,17 @@ def write(self, table_name: str, records: pa.Table) -> None: f"the rows are not of the table's schema ({difference}): " + "schema evolution is not supported" ) - encoded = _encoded( - _without_ids(records, self._held_ids(opened.table, _ids(records))) + # Only ids not already found absent are read again: one writer at a time + # (until the lease, ITL-1452, makes it the only possibility), and every + # write of this store to the table drops the ids it wrote (``_append``). + unchecked = set(_ids(records)) - self._absent_by_id.get( + found.table_id, set() ) + held = self._held_ids(opened.table, unchecked) if unchecked else set() + encoded = _encoded(_without_ids(records, held)) if encoded.num_rows == 0: return # a write of no rows is never sent + self._forget_opened(table_name) self._append(opened.table, found, encoded) def _write_first( @@ -718,6 +783,7 @@ def _write_first( if encoded.num_rows == 0: return # nothing to write, so nothing is created seen = self._judged.pop(table_name, ("none", None)) + self._forget_opened(table_name) table = self._create_or_open(table_name) _require_key(table, self._service_call) if self._unchanged_since_judged(table, path, seen): @@ -750,10 +816,15 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: with self._service_call("write a store table"): _ = table.append(encoded) except BaseException: - # The service may hold the rows, some, or none: judged again next call. + # The service may hold the rows, some, or none: judged again next call, + # and its keys read again. _ = self._found_by_id.pop(found.table_id, None) + _ = self._absent_by_id.pop(found.table_id, None) raise self._found_by_id[found.table_id] = found + absent = self._absent_by_id.get(found.table_id) + if absent: + absent.difference_update(_ids(encoded)) def _require_key( @@ -894,12 +965,77 @@ def _require_data_context(found: _Found, context: str) -> None: require_same_data_context(context, found.record.data_context_key) +def declared_keeping_identifier( + field: pa.Field[Any], + type_converter: Any, # pyright: ignore[reportExplicitAny] # a data context's converter +) -> pa.Field[Any]: + """The one declaration rule of a SpiralDB store: a field in the declaration form + (``declaration_form_field``) only when that keeps its identifier's bytes. + + A logical type in its storage form is made live when the live type the converter + resolves states exactly the identifier bytes recorded. A type the converter also + reads under other bytes (an older identifier) resolves to a live type stating the + current bytes: such a field stays in its storage form, so the bytes it was written + with are never replaced (ITL-1371). The same rule gives the rows to buffer and + flush, the schema a table reports and the schema its rows are decoded under, so a + table first written with an older identifier reads back and appends with it. + + Args: + field: A field, live or in its storage form. + type_converter: The type converter of the rows' data context. + + Returns: + The field, live or in its storage form. + + Raises: + LogicalTypeIdentifierError: If the field names a known logical type with + metadata or storage that type does not read, naming the column. + """ + declared = declaration_form_field(field, type_converter) + live = declared.type + if declared is field or not isinstance(live, pa.ExtensionType): + return declared + stored = storage_form_field(field) + metadata = stored.metadata or {} + given = ( + metadata.get(EXTENSION_NAME_KEY), + metadata.get(EXTENSION_METADATA_KEY, b""), + ) + identifier = arrow_type_identifier(live) + if (identifier.name.encode("utf-8"), identifier.metadata) != given: + return stored # another identifier the converter reads: kept as recorded + return declared + + +def declared_schema_keeping_identifier( + schema: pa.Schema, + type_converter: Any, # pyright: ignore[reportExplicitAny] # a data context's converter +) -> pa.Schema: + """``declared_keeping_identifier`` on every field; schema metadata kept. + + Args: + schema: A schema. + type_converter: The type converter of the rows' data context. + + Returns: + The schema; ``schema`` itself when nothing changes. + """ + fields = [declared_keeping_identifier(field, type_converter) for field in schema] + if all(new is old for new, old in zip(fields, schema)): + return schema + metadata = cast("dict[bytes | str, bytes | str] | None", schema.metadata) + return pa.schema(fields, metadata=metadata) + + def _live(schema: pa.Schema, data_context: str) -> pa.Schema: - """A manifest's schema with its logical types live, as the rows were given: by the - type converter of the data context the table records.""" + """A manifest's schema as its rows are read: logical types live where that keeps + the recorded identifier (``declared_keeping_identifier``), by the type converter of + the data context the table records.""" from orcapod.contexts import resolve_context - return declaration_form_schema(schema, resolve_context(data_context).type_converter) + return declared_schema_keeping_identifier( + schema, resolve_context(data_context).type_converter + ) def _same_manifest(one: codec.StoreManifest, other: codec.StoreManifest) -> bool: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index ce5429db3..cbdf59d8a 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -12,7 +12,7 @@ import json from collections.abc import Iterator from pathlib import Path -from typing import Any +from typing import Any, cast import pyarrow as pa import pytest @@ -1433,3 +1433,167 @@ def run(**kwargs: Any) -> Any: assert held.nodes["dbl"].held == 3 assert held.lost_observer_events == {} assert calls == [] and delivered == [] + + +# ------------------------------------------- review round 2 (PR 692): regressions + + +def _record_ids(table: pa.Table) -> list[bytes]: + return cast("list[bytes]", table.column("__record_id").to_pylist()) + + +def _older_rows(ids: list[str]) -> pa.Table: + """Rows whose storage-form ``p`` column names the older identifier ``OLDER``.""" + return _older_identifier(_with_path_column(rows(ids), live=False), OLDER) + + +@pytest.fixture +def older_first(root: Path, monkeypatch: pytest.MonkeyPatch) -> ConnectorArrowDatabase: + """A table first written with an identifier ``orcapod.path`` also reads (older).""" + _reads_an_older_identifier( + monkeypatch, _with_path_column(rows(["r0"]), live=False), OLDER + ) + db = ConnectorArrowDatabase(store()) + _add(db, _older_rows(["r0"]), flush=True) + return db + + +def _p_identifier(schema: pa.Schema) -> bytes: + from orcapod.logical_types.canonical_form import storage_form_schema + + metadata = storage_form_schema(schema).field("p").metadata or {} + return metadata[b"ARROW:extension:metadata"] + + +def test_a_first_write_with_an_older_identifier_reads_back_with_it( + older_first: ConnectorArrowDatabase, +) -> None: + """Round 2, P1: a table first written with an older identifier the type reads is + read back, by the writer and a fresh handle, with the identifier bytes it was + written with (one declaration rule for the read and the write).""" + for reader in (older_first, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + assert _p_identifier(got.schema) == OLDER + + +def test_the_schema_of_a_table_written_with_an_older_identifier_keeps_it( + older_first: ConnectorArrowDatabase, +) -> None: + """Round 2, P1: ``get_table_schema`` reports the identifier bytes as recorded, + never the current ones the type would state live.""" + for reader in (older_first, ConnectorArrowDatabase(store())): + schema = reader.get_table_schema(RESULT) + assert schema is not None and _p_identifier(schema) == OLDER + + +@pytest.mark.parametrize("fresh", [False, True]) +def test_rows_with_the_same_older_identifier_append( + older_first: ConnectorArrowDatabase, fresh: bool +) -> None: + """Round 2, P1: a later batch with the same older bytes is accepted at add and at + flush (the stored layout and the pending rows in one form), by the first writer + and by a fresh handle; the current identifier is still refused beside it.""" + db = ConnectorArrowDatabase(store()) if fresh else older_first + _add(db, _older_rows(["r1"]), flush=True) + with pytest.raises(InputValidationError, match="'p'"): + _add(db, _with_path_column(rows(["r2"]), live=False)) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None + assert sorted(_record_ids(got)) == [b"r0", b"r1"] + assert _p_identifier(got.schema) == OLDER + + +def _counted(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: + """Count the fake's name opens and full key reads.""" + counts = {"opens": 0, "key_reads": 0} + keyed_table = fake.FakeClient.keyed_table + scan = fake.FakeKeyedTable.scan + + def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: + counts["opens"] += 1 + return keyed_table(self, *args, **kwargs) + + def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: + if args and kwargs.get("limit") is None: + counts["key_reads"] += 1 + return scan(self, *args, **kwargs) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", open_by_name) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted_scan) + return counts + + +@pytest.mark.usefixtures("root") +def test_one_operation_opens_the_name_once_and_a_flush_reads_no_checked_keys( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: an add opens the table's name once and reads its keys once; the + flush that follows opens it once and reads no keys the add already found absent. + A skipping add checks nothing, so its flush reads the keys.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + counts = _counted(monkeypatch) + _add(db, rows(["r2", "r3"], offset=2)) + assert counts == {"opens": 1, "key_reads": 1} + db.flush() + assert counts == {"opens": 2, "key_reads": 1} + _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) + assert counts == {"opens": 3, "key_reads": 2} + got = _get(db) + assert got is not None + assert sorted(_record_ids(got)) == [ + b"r0", + b"r1", + b"r2", + b"r3", + b"r4", + ] + + +@pytest.mark.usefixtures("root") +def test_ids_checked_by_two_handles_are_written_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: two databases on one connector both find an id absent; the first + flush writes it, and the second reads the keys again and keeps the first row, + never replacing it (a write drops what it wrote from the ids found absent).""" + connector = store() + first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) + _add(first, rows(["r0"]), flush=True) + _add(first, rows(["r1"], offset=1)) + _add(second, rows(["r1"], offset=50)) + first.flush() + second.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"r1": 1, + } + + +@pytest.mark.usefixtures("root") +def test_a_failed_append_forgets_the_ids_found_absent( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: after an append that stored its rows and then raised, a retry on + the same handle reads the keys again: the stored id is refused, or kept when + skipped.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=True) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["retry"], offset=10), flush=True) + with pytest.raises(ValueError, match="already exist"): + _add(db, rows(["retry"], offset=99)) + _add(db, rows(["retry", "new"], offset=99), skip_duplicates=True, flush=True) + got = _get(db) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"retry": 10, + b"new": 100, + } From d3ed38e0409638cb6df6b8304881c1a313b0d5bb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 11:54:32 -0800 Subject: [PATCH 14/50] fix: recover writer lease claims and skip reserved names --- docs/dev/plans/itl-1838-spiraldb-lease.md | 27 ++-- scripts/migrate_spiral_schemas.py | 8 +- src/orcapod/databases/spiraldb_connector.py | 50 +++---- src/orcapod/databases/spiraldb_lease.py | 140 ++++++++++++++---- tests/test_databases/test_spiral_lease.py | 152 ++++++++++++++++++-- 5 files changed, 290 insertions(+), 87 deletions(-) diff --git a/docs/dev/plans/itl-1838-spiraldb-lease.md b/docs/dev/plans/itl-1838-spiraldb-lease.md index eeb9ec3e8..e61d073b7 100644 --- a/docs/dev/plans/itl-1838-spiraldb-lease.md +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -3,14 +3,19 @@ Use exclusive keyed-table creation to claim a dataset's next numbered generation. Find the newest generation by probing names at powers of two, then bisecting. Keep generation tables in place so contenders that observed the same predecessor -try the same name. A contender that loses creation refuses once, even if the -winner has already released. +try the same name. A contender that loses creation refuses once and advises +retry if the winner has already released. Use the pinned SDK's keyed-table operations. Put a random claim token in the -key column name so exclusive creation establishes ownership atomically and a -lost create reply can be checked. Use separate keyed rows for owner details and +key column name. Check that token after an uncertain create reply, including +a conflict response. The protocol assumes the service makes concurrent exclusive +creation atomic. Verify that with concurrent requests against live test tables +once a developer decides where those tables may be created. +Use separate keyed rows for owner details and for the release marker. The release marker wins even when owner details arrive late. An empty generation is held, including after a crash during acquisition. +If acquisition fails after confirming the claim, attempt to release it and +report the generation ID if release cannot be confirmed. Expose acquire, check, release, and manual clear by immutable table ID in an internal module. Reopen the exact resource for check and release, and report @@ -29,15 +34,15 @@ issuing any store writes. Pass the returned lease to `check(client, lease)` before writes and to `release(client, lease)` after all writes have finished. Canonical numbered generation names are separate from record table names. If an older table occupies a generation name without the lease key, acquisition -reports its table ID and leaves the table untouched. Listing and direct lookup -use the key signature to hide lease tables and preserve those older tables. -The listing endpoint still returns generations in its pages. The connector -opens each numbered candidate to verify its key and drops confirmed leases -from the page results. +reports its table ID and leaves the table untouched. The connector reserves +numbered generation names for creation and lookup. The listing endpoint still +returns generations in its pages, and the connector skips them by name. A refusal identifies the blocking table ID. To clear a stale lease, first stop the previous writer and ensure all outstanding writes have settled. Then call `spiraldb_lease.clear(client, table_id, confirm_writer_stopped=True)` on the same service. Clearing a live writer can admit another writer while an earlier -write is still in flight. The lease has no time limit. Keep all generation -tables, including released ones, so generation discovery remains contiguous. +write is still in flight. The lease has no time limit. Keep every generation +table, including released ones. Deleting a numbered generation by hand breaks +the contiguous sequence and can admit a second holder while a newer generation +is still held. Use clear by ID for stale leases. diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 811de8d79..b64eca148 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -410,13 +410,13 @@ def require_own_schema_table( ) -> Any | None: """Return the dataset's schema table when this plan's write created it, ``None`` when there is none yet; refuse any other.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table + from orcapod.databases.spiraldb_connector import open_keyed_table if planned["schema_table"] is not None: raise MigrationError( f"{dataset}: {SCHEMA_TABLE} existed at the dry run ({planned['schema_table']})" ) - table = _open_keyed_table(client, args.project, dataset, SCHEMA_TABLE) + table = open_keyed_table(client, args.project, dataset, SCHEMA_TABLE) noted = read_note(args).get(dataset) if ( table is not None @@ -445,10 +445,10 @@ def require_own_schema_table( def open_rows(client: Any, project: str, dataset: str) -> tuple[dict[str, Any], Any]: """Return the schema table's rows by table id and its marker, as stored now.""" - from orcapod.databases.spiraldb_connector import _open_keyed_table + from orcapod.databases.spiraldb_connector import open_keyed_table from orcapod.databases.spiraldb_schema_table import read_rows, require_schema_table - table = _open_keyed_table(client, project, dataset, SCHEMA_TABLE) + table = open_keyed_table(client, project, dataset, SCHEMA_TABLE) if table is None or not require_schema_table(table): return {}, None return read_rows(table.scan().to_table().to_pylist()) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 179206e70..7bb9f5f2d 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,10 +49,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path -from orcapod.databases.store_table_names import ( - is_spiral_lease_table_name, - spiral_lease_key_column, -) +from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -171,7 +168,7 @@ def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: raise -def _open_keyed_table( +def open_keyed_table( client: Any, project_id: str, dataset: str, @@ -183,6 +180,13 @@ def _open_keyed_table( SpiralDB has no error class for a missing table. Only its exact message for this name means "no such table"; a missing project, a refused sign-in or a transport failure has another and is raised. + + Args: + client: The SDK client. + project_id: The project containing the table. + dataset: The dataset containing the table. + name: The plain table name. + health: Optional connector client health to update on failure. """ with _service_call(f"open table {project_id}/{dataset}/{name}", health): try: @@ -463,15 +467,10 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, # A page can be empty before the last one. entries = cast("list[dict[str, str]]", page["items"]) for entry in entries: - if entry["dataset"] != dataset: - continue name = entry["table"] - table_id = entry["id"] - if is_spiral_lease_table_name(name): - keys: Sequence[str] = client.keyed_table_by_id(table_id).key_columns - if spiral_lease_key_column(keys) is not None: - continue - names[table_id] = name + if entry["dataset"] != dataset or is_spiral_lease_table_name(name): + continue + names[entry["id"]] = name following = page.get("nextPageToken") if following is None: return names @@ -917,9 +916,7 @@ def __init__( self._schemas = SchemaTable( project_id, dataset, - lambda: _open_keyed_table( - client, project_id, dataset, SCHEMA_TABLE, health - ), + lambda: open_keyed_table(client, project_id, dataset, SCHEMA_TABLE, health), lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), _kept_rows_for(_api_url(overrides), project_id, dataset), ) @@ -944,12 +941,14 @@ def _service_call(self, doing: str, table_name: str) -> Any: return _service_call(f"{doing} {self._qualified(table_name)}", self._health) def _require_user_table(self, table_name: str) -> None: - """Refuse the reserved name of the dataset's schema table.""" + """Refuse names reserved for the dataset's internal tables.""" if table_name == SCHEMA_TABLE: raise ValueError( f"{SCHEMA_TABLE!r} is reserved: it is where Orcapod keeps the schemas of " f"the tables of dataset {self._dataset!r}" ) + if is_spiral_lease_table_name(table_name): + raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") def get_table_names(self) -> list[str]: """Return all table names in this connector's dataset, sorted alphabetically. @@ -973,11 +972,7 @@ def get_table_names(self) -> list[str]: gone = sorted( row.table_name for i, row in recorded.items() - if i not in listed - and not ( - is_spiral_lease_table_name(row.table_name) - and spiral_lease_key_column(row.key_columns) is not None - ) + if i not in listed and not is_spiral_lease_table_name(row.table_name) ) if gone: _warn_once( @@ -1010,16 +1005,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: or "." in table_name ): raise SpiralDBTableNotFoundError(missing) - table = _open_keyed_table( + table = open_keyed_table( self._client, self._project_id, self._dataset, table_name, self._health ) if table is None: raise SpiralDBTableNotFoundError(missing) - if ( - is_spiral_lease_table_name(table_name) - and spiral_lease_key_column(table.key_columns) is not None - ): - raise ValueError(f"{table_name!r} is reserved for SpiralDB writer leases") return SpiralDBTable(self, table, table_name) def _recorded_schema( @@ -1270,9 +1260,11 @@ def create_table_if_not_exists( """Refuse to create a table: Orcapod does not write SpiralDB yet. Raises: - SpiralDBWriteNotSupportedError: Always (ITL-1186). + ValueError: If the name is reserved for an internal table. + SpiralDBWriteNotSupportedError: For user tables (ITL-1186). """ self._require_open() + self._require_user_table(table_name) raise SpiralDBWriteNotSupportedError(_NO_WRITES) def existing_record_ids( diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 0240aa498..5b193a588 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -1,4 +1,9 @@ -"""Internal one-writer leases for SpiralDB stores.""" +"""Internal one-writer leases for SpiralDB stores. + +Generation discovery requires a contiguous sequence. Deleting a generation +table by hand can admit a second holder while a newer generation is still +held. Keep every generation table and use ``clear`` by ID to release stale leases. +""" from __future__ import annotations @@ -20,7 +25,6 @@ _CLAIM = "claim" _RELEASED = "released" -_CONFLICT = "remote service returned an unknown error (status 409)" class _Scan(Protocol): @@ -84,19 +88,36 @@ class LeaseError(OrcapodDatabaseError): class LeaseBusyError(LeaseError): - """Another claim prevents this acquisition.""" + """Another claim took the generation this writer needs. + + Attributes: + table_id: Immutable ID of the conflicting generation. + """ table_id: str - def __init__(self, dataset: str, table_id: str, owner: str | None) -> None: - """Identify the conflicting generation and how an operator can release it.""" + def __init__( + self, dataset: str, table_id: str, owner: str | None, *, released: bool = False + ) -> None: + """Identify the conflicting generation and explain how to proceed. + + Args: + dataset: Dataset where acquisition was refused. + table_id: Immutable ID of the conflicting generation. + owner: Owner details if recorded. + released: Whether the conflicting generation has already been released. + """ self.table_id = table_id description = f"owner {owner!r}" if owner is not None else "owner unknown" how_to_clear = ( f"spiraldb_lease.clear(client, {table_id!r}, confirm_writer_stopped=True)" ) conflict = f"SpiralDB dataset {dataset!r} has a conflicting writer lease" - recovery = f"If the lease is stale, confirm the writer has stopped and call {how_to_clear}." + recovery = ( + "The conflicting lease was released. Retry acquisition." + if released + else f"If the lease is stale, confirm the writer has stopped and call {how_to_clear}." + ) super().__init__( f"{conflict} ({description}, table ID {table_id!r}). {recovery}" ) @@ -125,7 +146,7 @@ def _open( """Open the latest snapshot of a generation by name.""" return cast( "_KeyedTable | None", - sdk._open_keyed_table( # pyright: ignore[reportPrivateUsage] + sdk.open_keyed_table( client, project_id, dataset, spiral_lease_table_name(generation) ), ) @@ -201,11 +222,15 @@ def _claim_generation( name = spiral_lease_table_name(generation) key_schema = pa.schema([pa.field(key, pa.large_string(), nullable=False)]) try: - return client.project(project_id).create_keyed_table( + claimed = client.project(project_id).create_keyed_table( dataset, name, key_schema, exist_ok=False ) + if _key(claimed) != key: + raise LeaseError( + f"Unexpected claim token in table ID {claimed.resource_id!r}" + ) + return claimed except Exception as exc: - conflict = str(exc).strip() == _CONFLICT location = f"dataset {dataset!r} at generation {generation}" recovery = "Inspect that generation before clearing it by ID." uncertain = LeaseError( @@ -219,15 +244,30 @@ def _claim_generation( if found is None: raise uncertain from exc found_key = _key(found) - if not conflict and found_key == key: + if found_key == key: return found + state = _state(found, found_key) raise LeaseBusyError( - dataset, found.resource_id, _state(found, found_key).owner + dataset, found.resource_id, state.owner, released=state.released ) from exc def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Lease: - """Claim a dataset for one writer or raise before any store data can be written.""" + """Claim a dataset for one writer or raise before any store data can be written. + + Args: + client: SDK client used for the lease. + project_id: Project containing the dataset. + dataset: Dataset to claim. + owner: Operator-visible description of the writer. + + Returns: + The verified lease for this process. + + Raises: + LeaseBusyError: If another claim prevents acquisition. + LeaseError: If the claim or its state cannot be verified. + """ generation, latest = _newest(client, project_id, dataset) if latest is not None: state = _state(latest, _key(latest)) @@ -237,23 +277,32 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le key = f"{SPIRAL_LEASE_KEY_PREFIX}{uuid4().hex}" row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) claimed = _claim_generation(client, project_id, dataset, generation + 1, key) - if _key(claimed) != key: - raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") lease = Lease(claimed.resource_id, key, os.getpid()) # Owner details and release are different keys. An operator's release survives # even if this write publishes after it. try: - _ = claimed.append(row) - except Exception as exc: try: + _ = claimed.append(row) + except Exception as exc: + try: + check(client, lease) + except Exception as verification_error: + verification_error.add_note( + f"Writing lease owner details also failed: {exc}" + ) + raise + else: check(client, lease) - except Exception as verification_error: - verification_error.add_note( - f"Writing lease owner details also failed: {exc}" + except BaseException as exc: + # The claim token was verified and no store writes could start. The release + # row can be written even if reading the current lease state failed. + try: + _write_release(client, claimed, key) + except Exception as cleanup_error: + exc.add_note( + f"Releasing the failed acquisition also failed: {cleanup_error}" ) - raise - else: - check(client, lease) + raise return lease @@ -267,7 +316,16 @@ def _held_table(client: _Client, lease: Lease) -> _KeyedTable: def check(client: _Client, lease: Lease) -> None: - """Raise if a claim cannot be verified immediately before use.""" + """Verify a claim immediately before use. + + Args: + client: SDK client for the service that issued the lease. + lease: Claim returned by ``acquire``. + + Raises: + LeaseError: If the lease is released, lacks an owner, or changed identity. + RuntimeError: If the lease belongs to a different process. + """ table = _held_table(client, lease) state = _state(table, lease.key) if state.released: @@ -278,10 +336,8 @@ def check(client: _Client, lease: Lease) -> None: ) -def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: - """Write the release marker once, settling ambiguous replies by the exact ID.""" - if _state(table, key).released: - return +def _write_release(client: _Client, table: _KeyedTable, key: str) -> None: + """Upsert the release marker and settle ambiguous replies by the exact ID.""" table_id = table.resource_id try: _ = table.append(_row(key, _RELEASED)) @@ -301,13 +357,39 @@ def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: ) from exc +def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: + """Write a release marker if this snapshot does not already show one.""" + if not _state(table, key).released: + _write_release(client, table, key) + + def release(client: _Client, lease: Lease) -> None: - """Release exactly this claim after the writer and all pending writes have stopped.""" + """Release exactly this claim after the writer and all pending writes have stopped. + + Args: + client: SDK client for the service that issued the lease. + lease: Claim returned by ``acquire``. + + Raises: + LeaseError: If the claim's identity or release cannot be verified. + RuntimeError: If the lease belongs to a different process. + """ _mark_released(client, _held_table(client, lease), lease.key) def clear(client: _Client, table_id: str, *, confirm_writer_stopped: bool) -> None: - """Manually release a stale generation by immutable table ID.""" + """Manually release a stale generation by immutable table ID. + + Args: + client: SDK client for the service holding the generation table. + table_id: Immutable ID reported in the refusal. + confirm_writer_stopped: Whether the previous writer and all pending + writes have stopped. + + Raises: + ValueError: If the operator did not confirm the writer has stopped. + LeaseError: If the generation's identity or release cannot be verified. + """ if confirm_writer_stopped is not True: raise ValueError( "Confirm that the writer has stopped before clearing its lease" diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index a72c5e04f..86fb624f4 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -18,6 +18,8 @@ release, ) from orcapod.databases.store_table_names import ( + SPIRAL_LEASE_KEY_PREFIX, + STORE_TABLE_NAME_PREFIX, is_spiral_lease_table_name, spiral_lease_table_name, store_table_name, @@ -95,20 +97,25 @@ def racing_create( return create(project, dataset, name, key_schema, exist_ok=exist_ok) monkeypatch.setattr(fake.FakeProject, "create_keyed_table", racing_create) - with pytest.raises(LeaseBusyError, match="winner"): + with pytest.raises(LeaseBusyError, match="winner") as refused: _ = acquire(client, _PROJECT, _DATASET, owner="loser") assert attempted == [spiral_lease_table_name(1)] * 2 + if winner_releases: + assert "Retry acquisition" in str(refused.value) + assert "confirm_writer_stopped=True" not in str(refused.value) + check(client, acquire(client, _PROJECT, _DATASET, owner="loser retry")) + else: + assert "confirm_writer_stopped=True" in str(refused.value) def test_crash_between_create_and_owner_record(client: fake.FakeClient) -> None: - with pytest.MonkeyPatch.context() as patch: - - def crash(_table: fake.FakeKeyedTable, _rows: pa.Table) -> fake.FakeKeyedTable: - raise KeyboardInterrupt - - patch.setattr(fake.FakeKeyedTable, "append", crash) - with pytest.raises(KeyboardInterrupt): - _ = acquire(client, _PROJECT, _DATASET, owner="first") + # A process that stops after exclusive creation leaves only its claim key. + key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" + _ = client.project(_PROJECT).create_keyed_table( + _DATASET, + spiral_lease_table_name(1), + pa.schema([pa.field(key, pa.large_string(), nullable=False)]), + ) with pytest.raises(LeaseBusyError, match="owner unknown") as refused: _ = acquire(client, _PROJECT, _DATASET, owner="second") clear(client, refused.value.table_id, confirm_writer_stopped=True) @@ -139,8 +146,9 @@ def clear_before_append( assert refused.value.table_id == ids[-1] -def test_create_reply_lost_after_exclusive_creation( - client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +@pytest.mark.parametrize("reply", ["timeout", "conflict"]) +def test_create_reply_reconciles_the_callers_token( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reply: str ) -> None: create = fake.FakeProject.create_keyed_table @@ -153,6 +161,8 @@ def lose_reply( exist_ok: bool = False, ) -> fake.FakeKeyedTable: _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) + if reply == "conflict": + return create(project, dataset, name, key_schema, exist_ok=exist_ok) raise TimeoutError("lost reply") monkeypatch.setattr(fake.FakeProject, "create_keyed_table", lose_reply) @@ -160,6 +170,78 @@ def lose_reply( check(client, holder) +@pytest.mark.parametrize("owner_reply", ["lost", "failed", "interrupted"]) +def test_acquire_recovers_or_releases_after_owner_write_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, owner_reply: str +) -> None: + append = fake.FakeKeyedTable.append + + def fail_owner_write( + table: fake.FakeKeyedTable, rows: pa.Table + ) -> fake.FakeKeyedTable: + if rows.column("owner").null_count == rows.num_rows: + return append(table, rows) + if owner_reply == "lost": + _ = append(table, rows) + if owner_reply == "interrupted": + raise KeyboardInterrupt + raise TimeoutError("owner write reply unavailable") + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", fail_owner_write) + if owner_reply == "lost": + holder = acquire(client, _PROJECT, _DATASET, owner="writer") + check(client, holder) + release(client, holder) + elif owner_reply == "interrupted": + with pytest.raises(KeyboardInterrupt): + _ = acquire(client, _PROJECT, _DATASET, owner="interrupted") + else: + with pytest.raises(LeaseError, match="no owner record"): + _ = acquire(client, _PROJECT, _DATASET, owner="failed") + + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +@pytest.mark.parametrize("failed_call", ["open", "scan"]) +def test_acquire_releases_after_verification_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, failed_call: str +) -> None: + def unavailable(*_args: object, **_kwargs: object) -> None: + raise TimeoutError("verification unavailable") + + with monkeypatch.context() as patch: + if failed_call == "open": + patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) + else: + patch.setattr(fake.FakeKeyedTable, "scan", unavailable) + with pytest.raises(TimeoutError, match="verification unavailable"): + _ = acquire(client, _PROJECT, _DATASET, owner="first") + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +def test_acquire_reports_cleanup_failure_with_generation_id( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + def unavailable(*_args: object) -> None: + raise TimeoutError("writes unavailable") + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", unavailable) + with pytest.raises(LeaseError, match="no owner record") as failed: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + + with pytest.raises(LeaseBusyError) as refused: + _ = acquire(client, _PROJECT, _DATASET, owner="next") + assert any( + "Releasing the failed acquisition also failed" in note + and refused.value.table_id in note + for note in failed.value.__notes__ + ) + clear(client, refused.value.table_id, confirm_writer_stopped=True) + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + @pytest.mark.parametrize("landed", [True, False]) def test_release_reply_lost( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, landed: bool @@ -200,6 +282,7 @@ def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( assert names[0] != names[1] lookalike = f"{lease_name}report" assert is_spiral_lease_table_name(lease_name) + assert not lease_name.startswith(STORE_TABLE_NAME_PREFIX) assert not is_spiral_lease_table_name(lookalike) key_schema = pa.schema([pa.field("id", pa.int64())]) for name in reversed(names) if reverse else names: @@ -235,16 +318,22 @@ def test_release_and_clear_keep_the_generation_sequence_contiguous( _ = acquire(client, _PROJECT, _DATASET, owner="fourth") -def test_preexisting_table_with_generation_name_remains_accessible( +def test_connector_reserves_generation_names_even_without_a_claim_key( client: fake.FakeClient, ) -> None: name = spiral_lease_table_name(1) + with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + with pytest.raises(ValueError, match="reserved"): + connector.create_table_if_not_exists(name, [], "id") + with pytest.raises(ValueError, match="reserved"): + _ = connector.lookup_table(name) table = client.project(_PROJECT).create_keyed_table( _DATASET, name, pa.schema([pa.field("id", pa.int64())]) ) with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: - assert connector.get_table_names() == [name] - assert connector.lookup_table(name).key_columns == ["id"] + assert connector.get_table_names() == [] + with pytest.raises(ValueError, match="reserved"): + _ = connector.lookup_table(name) with pytest.raises(LeaseError, match=table.resource_id): _ = acquire(client, _PROJECT, _DATASET, owner="writer") with pytest.raises(LeaseError, match=table.resource_id): @@ -252,6 +341,41 @@ def test_preexisting_table_with_generation_name_remains_accessible( assert client.keyed_table_by_id(table.resource_id).version_id == table.version_id +@pytest.mark.parametrize("past_generations", [0, 40]) +def test_listing_skips_generations_without_any_sdk_table_opens( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, past_generations: int +) -> None: + for _ in range(past_generations): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + name = store_table_name(["records"], hint_length=96, digest_length=64) + _ = client.project(_PROJECT).create_keyed_table( + _DATASET, name, pa.schema([pa.field("id", pa.int64())]) + ) + + def unexpected_open(*_args: object, **_kwargs: object) -> None: + pytest.fail("listing opened a keyed table") + + monkeypatch.setattr(fake.FakeClient, "keyed_table_by_id", unexpected_open) + monkeypatch.setattr(fake.FakeClient, "keyed_table", unexpected_open) + with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + assert connector.get_table_names() == [name] + + +@pytest.mark.parametrize("dropped_generation", [1, 2]) +def test_manual_deletion_can_admit_a_second_holder( + client: fake.FakeClient, dropped_generation: int +) -> None: + for _ in range(3): + release(client, acquire(client, _PROJECT, _DATASET, owner="past")) + first = acquire(client, _PROJECT, _DATASET, owner="first") + name = spiral_lease_table_name(dropped_generation) + fake.ExternalProject(_PROJECT).drop_table(f"{_DATASET}.{name}") + second = acquire(client, _PROJECT, _DATASET, owner="second") + check(client, first) + check(client, second) + assert first.table_id != second.table_id + + def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: first = acquire(client, _PROJECT, _DATASET, owner="first") second = acquire(client, _PROJECT, "other", owner="second") From 1e2964c32cef4021a1aa1fa0ca0e53422471b689 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 11:57:28 -0800 Subject: [PATCH 15/50] fix(spiraldb): keep the flush key read until the lease; schema test sets schema metadata (ITL-1840) A flush reads the keys again, also for ids its add found absent: until the one-writer lease (ITL-1452) another writer may store one in between, and an append would replace its row (ITL-1386). The skip is tracked by ITL-1841. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 17 +++++------ .../databases/spiraldb_store_tables.py | 28 ++++--------------- .../test_spiraldb_store_mode.py | 22 +++++++++------ 3 files changed, 27 insertions(+), 40 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index ef374b361..cd317279f 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -69,14 +69,11 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. ranges and nothing here ran against a live SpiralDB: binary key literals, correctness (every stored id found, under the service's own order) and the work on the service are to be validated live before it replaces the key-column read. -- Ids `existing_record_ids` found absent are remembered by table id, and a flush reads - again only the keys of ids not found absent (review round 2): a strict add followed by - its flush reads the keys once. Every write through the store drops the ids it wrote, - and a failed append forgets the table's ids (the service may hold the rows), so a write - by this process is always seen. A write by another writer between the add and the - flush is not: one writer at a time is already the rule, and the lease of stage C - (ITL-1452) makes it the only possibility. A skipping add checks no ids, so its flush - reads the keys. +- A flush reads the keys again, also for ids its add found absent (review round 2 + considered skipping it): until the one-writer lease (stage C, ITL-1452), another writer, + in this process or another, may store one of those ids between the add and the flush, + and an append would then replace its row. Once the lease makes this writer the only + one, the flush can rely on the add's check (ITL-1841). - A flush never overwrites a stored row. A SpiralDB append replaces a row of the same key, so the store writes only the keys the table does not hold (the same key-column read): a key another writer stored after this one's add keeps its first commit, as with every @@ -128,7 +125,7 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. The one-writer lease (ITL-1452), the public switch-on with save and load, the live run, and fewer service calls per run (keyed reads, one existence answer per run). -Known limit (stage E, ITL-1841): each strict existence check, and each flush of ids not -checked, reads the table's whole key column, so its cost grows with the table's history; +Known limit (stage E, ITL-1841): each strict existence check, and each flush, reads the +table's whole key column, so its cost grows with the table's history; successive batches into a growing table cost quadratically many keys in all. Reads of stored rows read the whole table the same way. diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 2bed88580..7b8c0b1ca 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -182,11 +182,6 @@ def __init__( # name opened once and its handle reused. Empty outside an operation. # Kept per thread: an operation is one thread's call. self._now: threading.local = threading.local() - # Ids ``existing_record_ids`` found absent from a table holding rows, by table - # id: a write of them reads no keys again (``write``). Every write to a table - # through this store goes through ``_append``, which drops what it wrote, and - # drops the table's entry when it fails (the service may hold the rows). - self._absent_by_id: dict[str, set[bytes]] = {} key_column: str = codec.KEY_COLUMN """The key column of every store table.""" @@ -584,10 +579,7 @@ def existing_record_ids( if opened is None: return set() with self._about(table_name): - held = self._held_ids(opened.table, ids) - absent = self._absent_by_id.setdefault(opened.found.table_id, set()) - absent.update(set(ids) - held) - return held + return self._held_ids(opened.table, ids) def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: """The ids among ``ids`` a snapshot holds (``existing_record_ids``). @@ -746,13 +738,10 @@ def write(self, table_name: str, records: pa.Table) -> None: f"the rows are not of the table's schema ({difference}): " + "schema evolution is not supported" ) - # Only ids not already found absent are read again: one writer at a time - # (until the lease, ITL-1452, makes it the only possibility), and every - # write of this store to the table drops the ids it wrote (``_append``). - unchecked = set(_ids(records)) - self._absent_by_id.get( - found.table_id, set() - ) - held = self._held_ids(opened.table, unchecked) if unchecked else set() + # The keys are read again at every write, also for ids the add found + # absent: until the one-writer lease (ITL-1452), another writer may have + # stored one since, and an append would replace its row. + held = self._held_ids(opened.table, _ids(records)) encoded = _encoded(_without_ids(records, held)) if encoded.num_rows == 0: return # a write of no rows is never sent @@ -816,15 +805,10 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: with self._service_call("write a store table"): _ = table.append(encoded) except BaseException: - # The service may hold the rows, some, or none: judged again next call, - # and its keys read again. + # The service may hold the rows, some, or none: judged again next call. _ = self._found_by_id.pop(found.table_id, None) - _ = self._absent_by_id.pop(found.table_id, None) raise self._found_by_id[found.table_id] = found - absent = self._absent_by_id.get(found.table_id) - if absent: - absent.difference_update(_ids(encoded)) def _require_key( diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index cbdf59d8a..7b16b5d0f 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1389,7 +1389,9 @@ def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> No db = ConnectorArrowDatabase(store()) data = rows(["r0"]) field = data.schema.field("a.b").with_metadata({b"unit": b"m"}) - data = data.set_column(data.schema.get_field_index("a.b"), field, data["a.b"]) + data = data.set_column( + data.schema.get_field_index("a.b"), field, data["a.b"] + ).replace_schema_metadata({b"source": b"test", b"opaque": b"\xff"}) _add(db, data) queued = db.get_table_schema(RESULT) db.flush() @@ -1398,6 +1400,9 @@ def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> No assert stored is not None and queued is not None assert stored.equals(queued, check_metadata=True) assert stored.field("a.b").metadata == {b"unit": b"m"} + assert stored.metadata == {b"source": b"test", b"opaque": b"\xff"} + rows_read = reader.get_all_records(RESULT) + assert rows_read is not None and rows_read.schema.metadata == stored.metadata @pytest.mark.usefixtures("root", "_cleared") @@ -1526,21 +1531,21 @@ def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: @pytest.mark.usefixtures("root") -def test_one_operation_opens_the_name_once_and_a_flush_reads_no_checked_keys( +def test_one_operation_opens_the_name_once( monkeypatch: pytest.MonkeyPatch, ) -> None: """Round 2, P2: an add opens the table's name once and reads its keys once; the - flush that follows opens it once and reads no keys the add already found absent. - A skipping add checks nothing, so its flush reads the keys.""" + flush that follows opens it once and reads the keys again (another writer may + have stored one since: an append would replace its row).""" db = ConnectorArrowDatabase(store()) _add(db, rows(["r0", "r1"]), flush=True) counts = _counted(monkeypatch) _add(db, rows(["r2", "r3"], offset=2)) assert counts == {"opens": 1, "key_reads": 1} db.flush() - assert counts == {"opens": 2, "key_reads": 1} + assert counts == {"opens": 2, "key_reads": 2} _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) - assert counts == {"opens": 3, "key_reads": 2} + assert counts == {"opens": 3, "key_reads": 3} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1558,7 +1563,8 @@ def test_ids_checked_by_two_handles_are_written_once( ) -> None: """Round 2, P2: two databases on one connector both find an id absent; the first flush writes it, and the second reads the keys again and keeps the first row, - never replacing it (a write drops what it wrote from the ids found absent).""" + never replacing it (the handle reused within an operation is never an earlier + operation's).""" connector = store() first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) _add(first, rows(["r0"]), flush=True) @@ -1575,7 +1581,7 @@ def test_ids_checked_by_two_handles_are_written_once( @pytest.mark.usefixtures("root") -def test_a_failed_append_forgets_the_ids_found_absent( +def test_a_retry_after_a_failed_append_reads_the_keys_again( monkeypatch: pytest.MonkeyPatch, ) -> None: """Round 2, P2: after an append that stored its rows and then raised, a retry on From a02aeaa716225c525f2dede2c3c14e7dba56e800 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 12:02:33 -0800 Subject: [PATCH 16/50] fix: reconcile interrupted lease creation and align migration listings --- scripts/migrate_spiral_schemas.py | 5 +- src/orcapod/databases/spiraldb_lease.py | 23 ++++-- .../test_migrate_spiral_schemas.py | 53 +++++++++++-- tests/test_databases/test_spiral_lease.py | 78 ++++++++++++++++++- 4 files changed, 144 insertions(+), 15 deletions(-) diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index b64eca148..5fb732b71 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -27,6 +27,7 @@ import importlib import json import os +import re import sys import warnings from datetime import datetime, timezone @@ -34,6 +35,8 @@ from typing import Any SCHEMA_TABLE = "__orcapod_schemas__" +# The legacy dry-run environment predates the lease name helper. +LEASE_TABLE_PATTERN = re.compile(r"orcapod_lease_v1_g[1-9][0-9]*") PLAN_FORMAT = "orcapod.spiral_migration" PLAN_VERSION = 1 ROW_FORMAT = "orcapod.table_schema" @@ -237,7 +240,7 @@ def dry_run(args: argparse.Namespace) -> None: for found in project.list_tables(): if found.table == SCHEMA_TABLE: schema_tables[found.dataset] = found.id - else: + elif not LEASE_TABLE_PATTERN.fullmatch(found.table): tables.setdefault(found.dataset, []).append(found.table) if missing := [d for d in args.dataset if d not in tables]: raise MigrationError( diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 5b193a588..d9cc309e3 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -225,11 +225,6 @@ def _claim_generation( claimed = client.project(project_id).create_keyed_table( dataset, name, key_schema, exist_ok=False ) - if _key(claimed) != key: - raise LeaseError( - f"Unexpected claim token in table ID {claimed.resource_id!r}" - ) - return claimed except Exception as exc: location = f"dataset {dataset!r} at generation {generation}" recovery = "Inspect that generation before clearing it by ID." @@ -250,6 +245,21 @@ def _claim_generation( raise LeaseBusyError( dataset, found.resource_id, state.owner, released=state.released ) from exc + except BaseException as exc: + try: + found = _open(client, project_id, dataset, generation) + if found is not None and spiral_lease_key_column(found.key_columns) == key: + _write_release(client, found, key) + except BaseException as cleanup_error: + exc.add_note( + f"Reconciling interrupted writer lease creation at generation " + f"{generation} also failed: {cleanup_error}" + ) + raise + + if _key(claimed) != key: + raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") + return claimed def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Lease: @@ -267,6 +277,9 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le Raises: LeaseBusyError: If another claim prevents acquisition. LeaseError: If the claim or its state cannot be verified. + TimeoutError: If an SDK operation times out and the error propagates. + Other SDK transport errors can also propagate unchanged. After claiming, + acquisition attempts release before re-raising. """ generation, latest = _newest(client, project_id, dataset) if latest is not None: diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 655fd8fb9..330a18326 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -1,8 +1,4 @@ -"""The migration tool's write and verify steps, on the fake (ITL-1186). - -The dry run needs pyspiral, so its plan is made here from the same functions; all three -steps were run on throwaway tables of the service. -""" +"""Exercise the migration tool with synthetic tables and fake clients.""" from __future__ import annotations @@ -11,7 +7,7 @@ import json from collections.abc import Callable from pathlib import Path -from types import ModuleType +from types import ModuleType, SimpleNamespace from typing import Any, cast import pyarrow as pa @@ -19,6 +15,7 @@ from orcapod.databases import SpiralDBConnector from orcapod.databases import spiraldb_schema_table as st +from orcapod.databases.store_table_names import spiral_lease_table_name from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -150,6 +147,50 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: assert schema.field("v").metadata == {b"unit": b"mV"} +def test_dry_run_and_write_skip_lease_generations( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + plan = tool.read_plan(args.plan) + descriptions = { + (dataset, table["row"]["table_name"]): table + for dataset, planned in plan["datasets"].items() + for table in planned["tables"] + } + listed = [ + SimpleNamespace(dataset=dataset, table=name, id=table["row"]["table_id"]) + for (dataset, name), table in descriptions.items() + ] + project = fake.FakeClient().project(args.project) + for generation in (1, 2): + name = spiral_lease_table_name(generation) + dataset = args.dataset[0] + lease = project.create_keyed_table( + dataset, name, pa.schema([pa.field("k", pa.large_string(), False)]) + ) + listed.append( + SimpleNamespace(dataset=dataset, table=name, id=lease.resource_id) + ) + + legacy = SimpleNamespace( + authn=SimpleNamespace(token=lambda: None), + project=lambda _project: SimpleNamespace(list_tables=lambda: listed), + ) + monkeypatch.setattr( + tool, "spiral_module", lambda: SimpleNamespace(Spiral=lambda: legacy) + ) + monkeypatch.setattr( + tool, + "describe_table", + lambda _connector, _project, dataset, name: descriptions[dataset, name], + ) + + tool.dry_run(args) + recorded = tool.read_plan(args.plan) + assert recorded == plan + tool.write(args) + tool.verify(args) + + @pytest.mark.parametrize("stop_after", [1, 2, 3, 4]) def test_an_interrupted_write_is_refused_by_reads_and_resumed( tool: ModuleType, args: argparse.Namespace, stop_after: int diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 86fb624f4..f21358b90 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -170,6 +170,64 @@ def lose_reply( check(client, holder) +def test_create_reply_reports_an_unexpected_claim_token( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + create = fake.FakeProject.create_keyed_table + other_key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" + + def return_another_claim( + project: fake.FakeProject, + dataset: str, + name: str, + _key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + schema = pa.schema([pa.field(other_key, pa.large_string(), nullable=False)]) + return create(project, dataset, name, schema, exist_ok=exist_ok) + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", return_another_claim) + with pytest.raises(LeaseError, match="Unexpected claim token"): + _ = acquire(client, _PROJECT, _DATASET, owner="first") + + +@pytest.mark.parametrize("own_claim", [True, False]) +def test_create_interruption_releases_only_the_callers_claim( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, own_claim: bool +) -> None: + create = fake.FakeProject.create_keyed_table + interrupted = KeyboardInterrupt("create reply interrupted") + + def interrupt_create( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + if not own_claim: + other_key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" + key_schema = pa.schema( + [pa.field(other_key, pa.large_string(), nullable=False)] + ) + _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) + raise interrupted + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeProject, "create_keyed_table", interrupt_create) + with pytest.raises(KeyboardInterrupt) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is interrupted + + if own_claim: + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + else: + with pytest.raises(LeaseBusyError, match="owner unknown"): + _ = acquire(client, _PROJECT, _DATASET, owner="next") + + @pytest.mark.parametrize("owner_reply", ["lost", "failed", "interrupted"]) def test_acquire_recovers_or_releases_after_owner_write_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, owner_reply: str @@ -203,20 +261,34 @@ def fail_owner_write( check(client, acquire(client, _PROJECT, _DATASET, owner="next")) -@pytest.mark.parametrize("failed_call", ["open", "scan"]) +@pytest.mark.parametrize("failed_call", ["open", "scan", "scan_after_write_error"]) def test_acquire_releases_after_verification_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, failed_call: str ) -> None: + append = fake.FakeKeyedTable.append + unavailable_error = TimeoutError("verification unavailable") + def unavailable(*_args: object, **_kwargs: object) -> None: - raise TimeoutError("verification unavailable") + raise unavailable_error + + def lose_owner_reply( + table: fake.FakeKeyedTable, rows: pa.Table + ) -> fake.FakeKeyedTable: + result = append(table, rows) + if rows.column("owner").null_count == 0: + raise TimeoutError("owner write reply unavailable") + return result with monkeypatch.context() as patch: if failed_call == "open": patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) else: patch.setattr(fake.FakeKeyedTable, "scan", unavailable) - with pytest.raises(TimeoutError, match="verification unavailable"): + if failed_call == "scan_after_write_error": + patch.setattr(fake.FakeKeyedTable, "append", lose_owner_reply) + with pytest.raises(TimeoutError, match="verification unavailable") as caught: _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is unavailable_error check(client, acquire(client, _PROJECT, _DATASET, owner="next")) From 215b9cef0f8442816fa884cc3ce47ee0a6f9fe7d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 12:05:33 -0800 Subject: [PATCH 17/50] Test lease name recognition parity --- .../test_migrate_spiral_schemas.py | 31 ++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 330a18326..5d2ebfc21 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -15,7 +15,11 @@ from orcapod.databases import SpiralDBConnector from orcapod.databases import spiraldb_schema_table as st -from orcapod.databases.store_table_names import spiral_lease_table_name +from orcapod.databases.store_table_names import ( + is_spiral_lease_table_name, + spiral_lease_table_name, + store_table_name, +) from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -147,6 +151,31 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: assert schema.field("v").metadata == {b"unit": b"mV"} +def test_lease_name_recognizers_agree(tool: ModuleType) -> None: + cases = [ + ("orcapod_lease_v1_g1", True), + ("orcapod_lease_v1_g10", True), + ("orcapod_lease_v1_g12345", True), + ("orcapod_lease_v1_g0", False), + ("orcapod_lease_v1_g01", False), + ("orcapod_lease_v1_g", False), + ("orcapod_lease_v1_g1x", False), + ("orcapod_lease_v1_g1\n", False), + ("orcapod_lease_v1_g12", False), + ("orcapod_lease_v1_g12", False), + ("ORCAPOD_LEASE_V1_G1", False), + (" orcapod_lease_v1_g1", False), + ("orcapod_lease_v2_g1", False), + ("orcapod_lease_v1_", False), + (store_table_name(("example",), hint_length=96, digest_length=64), False), + ] + for name, expected in cases: + assert (tool.LEASE_TABLE_PATTERN.fullmatch(name) is not None) == expected, repr( + name + ) + assert is_spiral_lease_table_name(name) == expected, repr(name) + + def test_dry_run_and_write_skip_lease_generations( tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch ) -> None: From 6fb1b6e16a188ae409d57cc0b0f6b130e52890cc Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 12:17:24 -0800 Subject: [PATCH 18/50] fix(spiraldb): open the table afresh at every write; run the schema check outside the operation (ITL-1840) A flush now opens the table by name again at the write, after the caller's schema check, refuses a foreign table under the name, and reads the keys from that fresh snapshot, so a key another writer stored during the check is kept and a table renamed away is never appended to. The caller's check runs outside the per-operation handle cache: a public call it makes looks every name up again, and the enclosing operation forgets its handles afterwards. One extra name open per flush. Co-Authored-By: Claude Opus 5.5 --- .../databases/connector_arrow_database.py | 9 +- .../databases/spiraldb_store_tables.py | 29 +++++- .../test_spiraldb_store_mode.py | 89 +++++++++++++++++-- 3 files changed, 118 insertions(+), 9 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 69a6b3939..0e40544af 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -1258,7 +1258,14 @@ def _write_ready_batch( existing = self._stored_columns(table_name, schema) if table_exists else None check = self._pending_commits.schema_check(record_key) if check is not None: - check(pending.schema if existing is None else pa.schema(existing)) + schema_now = pending.schema if existing is None else pa.schema(existing) + if store is None: + check(schema_now) + else: + # The caller's check runs outside this operation: a public call it + # makes looks every name up again, and the write opens its table again. + with store.outside_operation(): + check(schema_now) if existing is not None: if self.keeps_field_metadata and store is None: # A different handle may have created the table after this batch diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 7b8c0b1ca..13038fcc8 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -309,10 +309,11 @@ def _about(self, table_name: str) -> Iterator[None]: @contextmanager def operation(self) -> Iterator[None]: """One public operation of ``ConnectorArrowDatabase`` (an add, a flush, a read): - each name is opened and judged once inside it, and that handle reused, until - this store writes to the table under it. Operations nest; the handles are + each name is opened and judged once inside it, and that handle reused for + reads; a write always opens its name afresh. Operations nest; the handles are forgotten when the outermost ends, so the next operation opens each name again - (a table can be renamed, and another made under its name, between them). + (a table can be renamed, and another made under its name, between them). Code + the store does not control runs ``outside_operation``. """ depth = cast(int, getattr(self._now, "depth", 0)) if depth == 0: @@ -325,6 +326,23 @@ def operation(self) -> Iterator[None]: if depth == 0: self._now.judged = None + @contextmanager + def outside_operation(self) -> Iterator[None]: + """Run code this store does not control (a caller's callback) outside the + current operation: a public call it makes opens every name afresh in an + operation of its own, and the enclosing operation forgets every handle it held + once the code returns, since that code may have renamed or replaced a table. + """ + depth = cast(int, getattr(self._now, "depth", 0)) + judged = self._judged_now() + self._now.depth = 0 + self._now.judged = None + try: + yield + finally: + self._now.depth = depth + self._now.judged = None if judged is None else {} + def _judged_now(self) -> dict[str, _Opened | None] | None: """What each name was judged in this thread's operation; ``None`` outside one.""" return cast( @@ -725,6 +743,11 @@ def write(self, table_name: str, records: pa.Table) -> None: """ path = self._path_of(table_name) context = _one_data_context(records) + # Opened by name afresh at the write, never through a handle opened earlier in + # the operation: a caller's check may have run since (``outside_operation``), + # and another writer may have stored a key, or the table may have been renamed + # away and another made under its name. The keys are read from this snapshot. + self._forget_opened(table_name) opened = self._judge(table_name) with self._about(table_name): if opened is None: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 7b16b5d0f..d9272ce0d 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1534,18 +1534,20 @@ def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: def test_one_operation_opens_the_name_once( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Round 2, P2: an add opens the table's name once and reads its keys once; the - flush that follows opens it once and reads the keys again (another writer may - have stored one since: an append would replace its row).""" + """Round 2, P2: an add opens the table's name once and reads its keys once. The + flush that follows opens it once to check the rows and once more at the write, + after the caller's schema check, and reads the keys again from that last + snapshot (another writer may have stored one since: an append would replace its + row).""" db = ConnectorArrowDatabase(store()) _add(db, rows(["r0", "r1"]), flush=True) counts = _counted(monkeypatch) _add(db, rows(["r2", "r3"], offset=2)) assert counts == {"opens": 1, "key_reads": 1} db.flush() - assert counts == {"opens": 2, "key_reads": 2} + assert counts == {"opens": 3, "key_reads": 2} _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) - assert counts == {"opens": 3, "key_reads": 3} + assert counts == {"opens": 5, "key_reads": 3} got = _get(db) assert got is not None assert sorted(_record_ids(got)) == [ @@ -1603,3 +1605,80 @@ def test_a_retry_after_a_failed_append_reads_the_keys_again( b"retry": 10, b"new": 100, } + + +def _replace_with_a_foreign_table() -> None: + """Rename the store table away and make a table of another key under its name.""" + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + _ = ( + fake.FakeClient() + .project("p") + .create_keyed_table( + "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) + ) + ) + + +@pytest.mark.usefixtures("root") +def test_a_key_committed_during_the_schema_check_is_kept() -> None: + """Round 3, finding 1: another writer stores a key while the caller's schema check + runs; the flush reads the keys again after the check and keeps that writer's + row, never replacing it.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + peer = ConnectorArrowDatabase(store()) + _add(db, rows(["r1"], offset=90)) + + def commit_first(_schema: pa.Schema) -> None: + _add(peer, rows(["r1"], offset=10), flush=True) + + with db.guard_table_schema(RESULT, commit_first): + db.flush() + got = _get(peer) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"r1": 10, + } + + +@pytest.mark.usefixtures("root") +def test_a_table_replaced_during_the_schema_check_is_refused() -> None: + """Round 3, finding 2: the table is renamed away and a foreign table made under + its name while the caller's schema check runs; the flush refuses the replacement + and never appends to the table renamed away.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + _add(db, rows(["r1"], offset=1)) + + def replace_table(_schema: pa.Schema) -> None: + _replace_with_a_foreign_table() + + with db.guard_table_schema(RESULT, replace_table): + with pytest.raises(SpiralStoreTableCollisionError): + db.flush() + old = fake.FakeClient().keyed_table("p", "d", "renamed_away") + assert old.scan().to_table().num_rows == 1 + + +@pytest.mark.usefixtures("root") +def test_a_read_inside_the_schema_check_looks_the_name_up_again() -> None: + """Round 3, finding 3: a public read made by the caller's schema check never + reuses the enclosing flush's handle: after the table is replaced it refuses the + replacement, as a read after the flush does.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + _add(db, rows(["r1"], offset=1)) + + def read_after_replacing(_schema: pa.Schema) -> None: + _replace_with_a_foreign_table() + with pytest.raises(SpiralStoreTableCollisionError): + _ = _get(db) + raise RuntimeError("stop before the write") + + with db.guard_table_schema(RESULT, read_after_replacing): + with pytest.raises(RuntimeError, match="stop before the write"): + db.flush() + with pytest.raises(SpiralStoreTableCollisionError): + _ = _get(db) From ed788d97fec1c9819cbb8b67e043923758b4eb6a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 14:37:32 -0800 Subject: [PATCH 19/50] fix(spiraldb): refuse stored values the codec cannot restore; record the validated path (ITL-1837) CodeRabbit's review of 216f1982d on PR 691: - The identity record takes its layout from the validated path snapshot. - A small list rebuilt from more items than 32-bit offsets index is a StoredRowsError. - A stored decimal over its logical precision is a StoredRowsError, checked before the narrowing cast, which lets some coefficients through wrapped. - The manifest reader refuses a kind with no UTF-8 form, as the writer does. - The fake SDK decodes a dictionary or run-end encoded column with no chunk. - Tests: both orders of one path's components; docstrings on the test helpers. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiral_store.py | 21 ++++- .../databases/spiral_store_identity.py | 5 +- tests/test_databases/fake_spiral_sdk.py | 5 +- tests/test_databases/test_fake_spiral_sdk.py | 26 ++++++ tests/test_databases/test_spiral_store.py | 91 +++++++++++++++++++ .../test_spiral_store_identity.py | 80 ++++++++++++++++ 6 files changed, 221 insertions(+), 7 deletions(-) diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index c6e91e5e5..84e35630a 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -744,7 +744,12 @@ def _retyped(array: Any, target: Any) -> Any: 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()) + offsets = _offsets(array) + if offsets[-1] > np.iinfo(np.int32).max: + raise StoredRowsError( + f"{offsets[-1]} items in one chunk, more than a {target} can index" + ) + small_offsets = pa.array(offsets.astype(np.int32), pa.int32()) return pa.ListArray.from_arrays(small_offsets, items, type=target, mask=mask) return _large_list(array, items, target) @@ -786,7 +791,13 @@ def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: if t.is_time(logical): restored = restored.view(logical) # the same integers elif restored.type != logical: - restored = restored.cast(logical) # a decimal32 or decimal64 + # A decimal32 or decimal64. A coefficient over the precision is refused + # before the cast: pyarrow's narrowing cast lets some through, wrapped. + try: + restored.validate(full=True) + restored = restored.cast(logical) + except pa.ArrowInvalid as exc: + raise StoredRowsError(f"not a {logical} value: {exc}") from exc if not field.nullable and restored.null_count: raise StoredRowsError("a null in a non-nullable field") return restored @@ -935,6 +946,12 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM raise ManifestError("the record path is not a list of strings") if not isinstance(kind, str): raise ManifestError("the kind is not text") + try: + _require_utf8( + kind + ) # what a writer refuses (``new_manifest``), a reader refuses + except UnstorableInSpiralError as exc: + raise ManifestError(f"the kind is not UTF-8 text: {exc}") from exc try: _ = require_store_path_domain(cast("list[str]", path)) except ValueError as exc: diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py index a70a4f3b2..baae18c2b 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_store_identity.py @@ -138,13 +138,14 @@ def store_table_metadata( empty, or an entry is over SpiralDB's entry limit (``MAX_METADATA_ENTRY_BYTES``). """ - path_json = store_table_path_json(require_store_path_domain(path)) + components = require_store_path_domain(path) # one read of ``path``, kept + path_json = store_table_path_json(components) if not data_context_key: raise ValueError("a store table records the data context that created it") record = { STORE_KEY: STORE_FORMAT.encode(), PATH_KEY: path_json, - LAYOUT_KEY: path[-1].encode(), + LAYOUT_KEY: components[-1].encode(), DATA_CONTEXT_KEY: data_context_key.encode(), } for key, value in record.items(): diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 26349b244..ec79e2acd 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -605,9 +605,8 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: for i, field in enumerate(rows.schema): # nul, at every depth if _needs_decoding(field.type): # Stored as its values (``types``): decoded first, so its names are cut. - decoded = pa.chunked_array( - [_deep_decoded(c) for c in rows.column(i).chunks] - ) + chunks = rows.column(i).chunks or [pa.array([], field.type)] # no chunk + decoded = pa.chunked_array([_deep_decoded(c) for c in chunks]) rows = rows.set_column(i, field.with_type(decoded.type), decoded) field = rows.schema.field(i) cut = _names_cut_at_nul(field.type) diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py index 152de88c9..c572d95e8 100644 --- a/tests/test_databases/test_fake_spiral_sdk.py +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -2,6 +2,7 @@ from __future__ import annotations +from pathlib import Path from typing import Any import pyarrow as pa @@ -40,3 +41,28 @@ def test_a_zero_width_fixed_size_list_of_dictionaries_keeps_its_rows( assert len(got) == len(given) assert got.to_pylist() == given.to_pylist() assert got.type == pa.list_(pa.string(), 0) + + +@pytest.mark.parametrize( + "encoded", + [ + pa.dictionary(pa.int8(), pa.string()), + pa.run_end_encoded(pa.int32(), pa.string()), + ], +) +def test_an_encoded_column_with_no_chunk_is_written_as_no_rows( + tmp_path: Path, encoded: Any +) -> None: + """CodeRabbit on PR 691 (fake_spiral_sdk.py:610): a dictionary or run-end encoded + column with no chunk at all (``Table.from_batches([], schema)``) is decoded to its + values' type, as one with rows is, and the write stores no rows.""" + with fake.install(tmp_path): + key = pa.schema([pa.field("k", pa.large_string(), False)]) + table = fake.FakeClient().project("p").create_keyed_table("d", "t", key) + schema = pa.schema( + [pa.field("k", pa.large_string(), False), pa.field("v", encoded)] + ) + rows = pa.Table.from_batches([], schema=schema) + assert rows.column("v").num_chunks == 0 + written = table.append(rows) + assert written.scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_store.py index 733d4a842..0c37ecb3f 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_store.py @@ -53,6 +53,14 @@ def ids(n: int) -> Any: + """Return ``n`` distinct record ids, ``r0000`` onward, as a key column. + + Args: + n: The number of ids. + + Returns: + A ``large_binary`` array. + """ return pa.array([f"r{i:04d}".encode() for i in range(n)], pa.large_binary()) @@ -273,6 +281,15 @@ def walk(field: Any, named: bool, in_map: bool = False) -> None: def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: + """Check that ``encode_rows`` refuses ``rows`` with a message holding every word. + + Args: + rows: The rows to encode. + *words: Fragments the message must hold, each of them. + + Returns: + The error, for assertions on what it says (``error.path``). + """ with pytest.raises(store.UnstorableInSpiralError) as info: _ = store.encode_rows(rows) for word in words: @@ -517,6 +534,12 @@ def test_every_row_of_the_type_matrix_is_kept_or_refused( def scalar_cases() -> list[tuple[str, pa.DataType, list[Any]]]: + """Return one case per scalar Arrow type: its label, the type and three values. + + Returns: + ``(label, type, values)`` tuples, the values at the type's edges where it has + them. + """ D = decimal.Decimal return [ ("int8", pa.int8(), [-128, 127, 0]), @@ -1484,6 +1507,15 @@ def test_chunks_of_an_earlier_longer_manifest_are_not_read() -> None: def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, bytes]: + """Return manifest entries whose header has ``changes`` applied, chunks unchanged. + + Args: + entries_: A manifest's metadata entries. + **changes: Header fields to set. + + Returns: + The entries with the header rewritten. + """ header = {**json.loads(entries_[store.MANIFEST_KEY]), **changes} return {**entries_, store.MANIFEST_KEY: json.dumps(header).encode()} @@ -1669,3 +1701,62 @@ def test_the_manifest_is_cut_every_8000_bytes(target: int) -> None: for broken in (missing, modified): with pytest.raises(store.ManifestError): _ = store.read_manifest(broken, PATH) + + +# ------------------------------------- CodeRabbit review of PR 691 (216f1982d) + + +def _decimal128(coefficients: list[int], precision: int) -> Any: + """A ``decimal128(precision, 2)`` array holding ``coefficients`` as they are, beyond + the precision too, as rows read back from a table could hold them.""" + data = b"".join(c.to_bytes(16, "little", signed=True) for c in coefficients) + from_buffers: Any = pa.Array.from_buffers # the stubs take no missing validity + return from_buffers( + pa.decimal128(precision, 2), len(coefficients), [None, pa.py_buffer(data)] + ) + + +@pytest.mark.parametrize( + ("logical", "precision"), [(pa.decimal32(9, 2), 9), (pa.decimal64(18, 2), 18)] +) +@pytest.mark.parametrize("over", [0, 3, 12]) +def test_a_stored_decimal_over_its_precision_is_refused( + logical: Any, precision: int, over: int +) -> None: + """Thread on spiral_store.py:789: a stored coefficient with more digits than the + logical decimal's precision is a ``StoredRowsError`` naming the column, never a raw + Arrow error, and never a wrapped value (pyarrow's narrowing cast lets 10**12 into a + decimal32 as -7273799.68).""" + D = decimal.Decimal + table = keyed({"d": pa.array([D("1.25"), D("-3.50")], logical)}) + good = _stored(table) + assert_same(decode(good, table.schema), large_table(table)) + wide = 10 ** (precision + over) + rows = good.set_column( + good.column_names.index("d"), "d", _decimal128([125, wide], precision) + ) + with pytest.raises(store.StoredRowsError, match="'d'"): + _ = decode(rows, table.schema) + + +def test_a_small_list_over_its_offset_range_is_refused( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Thread on spiral_store.py:748: a decoded large list of maps rebuilt as a small + list whose items do not fit 32-bit offsets is a ``StoredRowsError``, never wrapped + offsets. Reaching it for real takes more than 2**31 map items in one chunk (some + 16 GB), so the large list's offsets are made to say so.""" + entry = pa.map_(pa.large_string(), pa.int8()) + given: Any = pa.array([[[("a", 1)]]], pa.large_list(entry)) + target = pa.list_(pa.map_(pa.string(), pa.int8())) + real = store._offsets # pyright: ignore[reportPrivateUsage] + + def offsets(array: Any) -> Any: + if pa.types.is_large_list(array.type): + return np.array([0, 2**31], np.int64) + return real(array) + + assert store._retyped(given, target).to_pylist() == given.to_pylist() # pyright: ignore[reportPrivateUsage] + monkeypatch.setattr(store, "_offsets", offsets) + with pytest.raises(store.StoredRowsError, match="2147483648 items"): + _ = store._retyped(given, target) # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_store_identity.py index e86003669..55fae7171 100644 --- a/tests/test_databases/test_spiral_store_identity.py +++ b/tests/test_databases/test_spiral_store_identity.py @@ -10,6 +10,8 @@ import json import random import re +from collections.abc import Sequence +from typing import overload import pyarrow as pa import pytest @@ -371,3 +373,81 @@ def test_the_record_and_the_manifest_accept_the_same_paths( manifest = spiral_store.new_manifest(path, "k", _schema()) entries = spiral_store.manifest_entries(manifest) assert spiral_store.read_manifest(entries, path) == manifest + + +# ------------------------------------- CodeRabbit review of PR 691 (216f1982d) + + +class _ShiftingPath(Sequence[str]): + """A path whose last component reads as another name after its first full read.""" + + def __init__(self) -> None: + """Start with ``("base", "rdb_v1")``, read once.""" + self.reads = 0 + + def __len__(self) -> int: + """Two components.""" + return 2 + + @overload + def __getitem__(self, index: int) -> str: ... + @overload + def __getitem__(self, index: slice) -> Sequence[str]: ... + def __getitem__(self, index: int | slice) -> str | Sequence[str]: + """``rdb_v1`` as the last component on the first read, ``pdb_v2`` later.""" + if isinstance(index, slice): + return [self[i] for i in range(2)][index] + if index < 0: + index += 2 + if index not in (0, 1): + raise IndexError(index) + if index == 0: + return "base" + self.reads += 1 + return "rdb_v1" if self.reads == 1 else "pdb_v2" + + +def test_the_layout_is_the_last_component_of_the_path_recorded() -> None: + """Thread on spiral_store_identity.py:147: the layout is taken from the validated + snapshot of the path, so a path that reads differently later records one path.""" + record = names.store_table_metadata(_ShiftingPath(), "std:v1:default") + found = names.read_store_table_metadata(record) + assert found is not None + assert (found.path, found.layout) == (("base", "rdb_v1"), "rdb_v1") + + +def test_the_record_keeps_the_order_of_its_path_components() -> None: + """Thread on test_spiral_store_identity.py:315: the same components in two orders + are two recorded paths, each read back in the order given; the layout is fixed.""" + first, second = ("base", "part", "rdb_v1"), ("part", "base", "rdb_v1") + one = names.store_table_metadata(first, "std:v1:default") + two = names.store_table_metadata(second, "std:v1:default") + assert one[names.PATH_KEY] != two[names.PATH_KEY] + assert one[names.LAYOUT_KEY] == two[names.LAYOUT_KEY] == b"rdb_v1" + for path, record in ((first, one), (second, two)): + found = names.read_store_table_metadata(record) + assert found is not None and found.path == path + + +@pytest.mark.parametrize("kind", ["", "k", "é
"]) +def test_a_manifest_kind_is_read_as_any_utf8_text(kind: str) -> None: + """Thread on spiral_store.py:937: an empty or non-ASCII kind still reads back.""" + path = ("ok", "rdb_v1") + manifest = spiral_store.new_manifest(path, kind, _schema()) + assert ( + spiral_store.read_manifest_bytes(spiral_store.manifest_bytes(manifest), path) + == manifest + ) + + +def test_a_manifest_kind_with_no_utf8_form_is_refused_on_read() -> None: + """Thread on spiral_store.py:937: a JSON escape can give a kind with a lone + surrogate, which ``new_manifest`` refuses; the reader refuses it too.""" + path = ("ok", "rdb_v1") + payload = spiral_store.manifest_bytes( + spiral_store.new_manifest(path, "k", _schema()) + ) + escaped = payload.replace(b'"kind":"k"', b'"kind":"\\udc00"') + assert escaped != payload + with pytest.raises(spiral_store.ManifestError, match="kind"): + _ = spiral_store.read_manifest_bytes(escaped, path) From acc6007d86561635a1a0d41a2a667035427b8d30 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:31:03 -0800 Subject: [PATCH 20/50] feat(spiraldb): public store keyword; job runs hold the dataset's writer lease (ITL-1844) SpiralDBConnector(..., store=True) opens a dataset as a job's store, saved in a job without credentials; a load refuses a SpiralDB connector of the other kind. Job runs (job.run, run_async, a job node's run, load-only included) take the writer lease of every store they may write before checking sources and release it at the end, also on failure; a second writer is refused (LeaseBusyError) before anything is written. A store write outside a run raises SpiralDBStoreLeaseRequiredError. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/core/nodes/function_node.py | 28 +- src/orcapod/core/nodes/operator_node.py | 33 +- src/orcapod/core/nodes/source_node.py | 17 +- src/orcapod/databases/spiraldb_connector.py | 53 +- .../databases/spiraldb_store_tables.py | 62 ++- src/orcapod/databases/spiraldb_write_scope.py | 158 ++++++ src/orcapod/errors.py | 10 + src/orcapod/pipeline/job.py | 107 +++- src/orcapod/pipeline/node_run.py | 86 ++++ src/orcapod/pipeline/serialization.py | 40 ++ .../test_spiraldb_store_mode.py | 71 ++- .../test_spiraldb_store_runs.py | 477 ++++++++++++++++++ 12 files changed, 1066 insertions(+), 76 deletions(-) create mode 100644 src/orcapod/databases/spiraldb_write_scope.py create mode 100644 tests/test_databases/test_spiraldb_store_runs.py diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3518b8450..3457c9d90 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -371,6 +371,7 @@ def run_job_node( depends_on_job_nodes, refuse_unloadable_inputs, run_with_dependencies, + store_write_scope, ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures @@ -385,18 +386,21 @@ def run_job_node( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([node]) - # Every source feeding the run first takes in any new data (ITL-1102). - unchecked = check_sources([node]) - if node.holds_current_run(load_only=load_only): - return - if depends_on_job_nodes(node): - summary = run_with_dependencies( - node, load_only=load_only, unchecked_sources=unchecked - ) - else: - if load_only: - refuse_unloadable_inputs(node) - summary = run_alone(unchecked) + # The writer leases of the SpiralDB stores the run may write are held from the + # source check to the end of the run; a second writer is refused (ITL-1844). + with store_write_scope([node], load_only=load_only): + # Every source feeding the run first takes in any new data (ITL-1102). + unchecked = check_sources([node]) + if node.holds_current_run(load_only=load_only): + return + if depends_on_job_nodes(node): + summary = run_with_dependencies( + node, load_only=load_only, unchecked_sources=unchecked + ) + else: + if load_only: + refuse_unloadable_inputs(node) + summary = run_alone(unchecked) if summary is None: return node._last_run = summary diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 91e5f7b25..91a290cf8 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2074,14 +2074,8 @@ def run(self, *, load_only: bool = False) -> StreamView: SourceSpecMismatchError: If a bound source now depends on a bindable slot or the live inputs contain a cycle (ITL-1559). """ - from orcapod.pipeline.node_run import ( - check_sources, - depends_on_job_nodes, - refuse_unloadable_inputs, - run_with_dependencies, - ) + from orcapod.pipeline.node_run import store_write_scope from orcapod.pipeline.restrictions import refuse_restriction_conflicts - from orcapod.pipeline.run_summary import warn_row_failures from orcapod.pipeline.source_consistency import ( require_consistent_sources, require_live_source_bindings, @@ -2095,6 +2089,29 @@ def run(self, *, load_only: bool = False) -> StreamView: # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([self]) + # The writer leases of the SpiralDB stores the run may write are held from the + # source check to the end of the run; a second writer is refused (ITL-1844). + with store_write_scope([self], load_only=load_only): + return self._run_holding_leases( + load_only=load_only, + caller=sys._getframe(1), # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + ) + + def _run_holding_leases(self, *, load_only: bool, caller: Any) -> StreamView: + """``run`` from its source check on, the run's writer leases held. + + Args: + load_only: As for ``run``. + caller: The frame of the ``run()`` caller, where a warning is shown. + """ + from orcapod.pipeline.node_run import ( + check_sources, + depends_on_job_nodes, + refuse_unloadable_inputs, + run_with_dependencies, + ) + from orcapod.pipeline.run_summary import warn_row_failures + # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([self]) if self.holds_current_run(load_only=load_only): @@ -2105,7 +2122,7 @@ def run(self, *, load_only: bool = False) -> StreamView: ) self._last_run = summary if not summary.ok: - warn_row_failures(summary, sys._getframe(1)) # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown + warn_row_failures(summary, caller) return self._run_view(computed=False) if self._loaded: raise self._cannot_compute_error() diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c0c1db3c..5c19f5f50 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1878,7 +1878,11 @@ def run(self, *, load_only: bool = False) -> StreamView: ValueError: If ``load_only`` and the bound stream computes or delivers when read (``node_run.refuse_unloadable_inputs``). """ - from orcapod.pipeline.node_run import check_sources, refuse_unloadable_inputs + from orcapod.pipeline.node_run import ( + check_sources, + refuse_unloadable_inputs, + store_write_scope, + ) from orcapod.pipeline.source_consistency import ( require_consistent_sources, require_live_source_bindings, @@ -1886,10 +1890,13 @@ def run(self, *, load_only: bool = False) -> StreamView: require_live_source_bindings([self]) require_consistent_sources([(f"node {self.label!r}", self)]) - _ = check_sources([self]) - if load_only: - refuse_unloadable_inputs(self) - return super().run() + # A cached source writes its cache when checked or read: its store's writer + # lease is held for the run (ITL-1844). + with store_write_scope([self], load_only=load_only): + _ = check_sources([self]) + if load_only: + refuse_unloadable_inputs(self) + return super().run() @property def bound_source(self) -> StreamProtocol | None: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 5f4382580..7ff386e60 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -893,11 +893,13 @@ 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``), for + store: Open the dataset as a job's pipeline store (ITL-1844), for ``ConnectorArrowDatabase``: tables named from their paths, rows through the - store codec. Private until the store is switched on (ITL-1446): such a - connector is not saved, and its tables are read and written only through - ``ConnectorArrowDatabase``. + store codec, one writer at a time (a job run takes the dataset's writer + lease, and a second writer is refused). Its tables are read and written only + through ``ConnectorArrowDatabase``, and only a job run writes them. + Provisional in 0.4.0: the store's table format and its lease may change in + a later version, which may not read tables written now. """ def __init__( @@ -906,8 +908,10 @@ def __init__( dataset: str = "default", overrides: dict[str, str] | None = None, *, - _store: bool = False, + store: bool = False, ) -> None: + if not isinstance(store, bool): # pyright: ignore[reportUnnecessaryIsInstance] # a saved or user value + raise TypeError(f"store must be True or False, got {store!r}") self._project_id = project_id self._dataset = dataset self._overrides = overrides @@ -930,15 +934,15 @@ def __init__( ) # Kept after ``close`` releases the store's tables, so a closed store connector # never acts as a plain one. - self._store_mode = _store + self._store_mode = store self._store: StoreTables | None = None - if _store: + if store: self._store = StoreTables( client, sp, project_id, dataset, - lambda name: _open_keyed_table( + lambda name: open_keyed_table( client, project_id, dataset, name, health ), lambda: _list_keyed_tables(client, project_id, dataset), @@ -966,6 +970,20 @@ def _store_tables(self) -> StoreTables | None: self._require_open() return self._store + def _writer_lease_key(self) -> tuple[str | None, str, str]: + """The dataset a writer lease is taken for: service address, project, dataset.""" + return (_api_url(self._overrides), self._project_id, self._dataset) + + def _writer_lease_target(self) -> tuple[Any, str, str]: + """What ``spiraldb_write_scope`` takes the writer lease with: the SDK client, + project and dataset. + + Raises: + RuntimeError: If this connector has been closed. + """ + self._require_open() + return (self._client, self._project_id, self._dataset) + def _refuse_in_store_mode(self) -> None: """Refuse an operation on raw tables of a store-mode connector.""" if self._store_mode: @@ -1410,26 +1428,26 @@ def __exit__(self, *args: Any) -> None: def to_config(self) -> dict[str, Any]: """Serialize connection configuration to a JSON-compatible dict. + No credential is saved: spiral-sdk signs in from its environment or saved + login. + Returns: Dict with ``connector_type``, ``project_id``, ``dataset``, and - ``overrides`` keys. + ``overrides`` keys, and ``store: True`` for a store connector. Raises: RuntimeError: If this connector has been closed. - ValueError: If this connector is in store mode, which is not saved yet. """ - if self._store_mode: - raise ValueError( - "a store-mode SpiralDB connector is not saved: the store is not " - "switched on yet (ITL-1446)" - ) self._require_open() - return { + config: dict[str, Any] = { "connector_type": "spiraldb", "project_id": self._project_id, "dataset": self._dataset, "overrides": self._overrides, } + if self._store_mode: + config["store"] = True + return config @classmethod def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: @@ -1437,7 +1455,7 @@ def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: Args: config: Dict with ``connector_type``, ``project_id``, and optionally - ``dataset`` and ``overrides`` keys. + ``dataset``, ``overrides`` and ``store`` keys. Returns: A new, open SpiralDBConnector instance. @@ -1454,4 +1472,5 @@ def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: project_id=config["project_id"], dataset=config.get("dataset", "default"), overrides=config.get("overrides"), + store=config.get("store", False), ) diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 13038fcc8..9756ae407 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -25,9 +25,12 @@ metadata of each candidate (cached by table id): that is how stale layouts are found (ITL-954). -One writer at a time, and no lease yet (ITL-1452): a first write re-reads the table just -before recording it and never overwrites what that read shows, but without a -compare-and-set two concurrent writers can still race in between. +One writer at a time (ITL-1844): every write needs the dataset's writer lease +(``spiraldb_lease``), handed in by the run that holds it (``spiraldb_write_scope``) and +checked before each write; a write with none is refused +(``SpiralDBStoreLeaseRequiredError``) before anything is created or written. A first write +still re-reads the table just before recording it and never overwrites what that read +shows. """ from __future__ import annotations @@ -45,7 +48,7 @@ import orcapod.databases.spiral_store_identity as identity from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, SpiralDBStoreLeaseRequiredError from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, @@ -182,6 +185,9 @@ def __init__( # name opened once and its handle reused. Empty outside an operation. # Kept per thread: an operation is one thread's call. self._now: threading.local = threading.local() + # The check of the writer lease a run holds for this dataset + # (``spiraldb_write_scope``); ``None`` when no run holds one. + self._lease_check: Callable[[], None] | None = None key_column: str = codec.KEY_COLUMN """The key column of every store table.""" @@ -619,6 +625,45 @@ def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: # ── writing ────────────────────────────────────────────────────────────── + def hold_lease(self, check: Callable[[], None]) -> None: + """Let this dataset be written under a lease a run holds (``spiraldb_write_scope``). + + Args: + check: Verifies the lease is still held; raises if it is not. + + Raises: + RuntimeError: If a lease is held for these tables already. + """ + if self._lease_check is not None: + raise RuntimeError("these store tables are already written under a lease") + self._lease_check = check + + def let_go_of_lease(self, check: Callable[[], None]) -> None: + """Stop writing under the lease ``hold_lease`` was given ``check`` for. + + Args: + check: The check given to ``hold_lease``; any other leaves the lease held. + """ + if self._lease_check is check: + self._lease_check = None + + def _require_lease(self) -> None: + """Refuse a write unless a run holds the dataset's writer lease, and check it. + + Raises: + SpiralDBStoreLeaseRequiredError: If no run holds the lease. + LeaseError: If the lease is no longer held (``spiraldb_lease.check``). + """ + check = self._lease_check + if check is None: + raise SpiralDBStoreLeaseRequiredError( + f"no job run holds the writer lease of SpiralDB dataset " + f"{self._project_id}/{self._dataset}: a SpiralDB store is written only " + "within a job run (job.run(), job.run_async() or a job node's run()), " + "which takes the lease; nothing was written" + ) + check() + def _create_or_open(self, table_name: str) -> _KeyedTable: """The table at a computed name, created now if absent. @@ -740,9 +785,14 @@ def write(self, table_name: str, records: pa.Table) -> None: or not the one the table records (checked when they are buffered too). SpiralStoreTableCollisionError: If the table under the name is not this path's store table. + SpiralDBStoreLeaseRequiredError: If no job run holds the dataset's writer + lease; nothing is written. + LeaseError: If the lease the run took is no longer held. """ path = self._path_of(table_name) context = _one_data_context(records) + # Before anything is created or written: one writer per dataset (ITL-1844). + self._require_lease() # Opened by name afresh at the write, never through a handle opened earlier in # the operation: a caller's check may have run since (``outside_operation``), # and another writer may have stored a key, or the table may have been renamed @@ -762,8 +812,8 @@ def write(self, table_name: str, records: pa.Table) -> None: + "schema evolution is not supported" ) # The keys are read again at every write, also for ids the add found - # absent: until the one-writer lease (ITL-1452), another writer may have - # stored one since, and an append would replace its row. + # absent: the lease keeps other Orcapod writers out, but not a hand-made + # write, and an append would replace its row (fewer reads: ITL-1841). held = self._held_ids(opened.table, _ids(records)) encoded = _encoded(_without_ids(records, held)) if encoded.num_rows == 0: diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py new file mode 100644 index 000000000..ce1811c0f --- /dev/null +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -0,0 +1,158 @@ +"""The writer leases a job run holds on the SpiralDB stores it writes (ITL-1844). + +A SpiralDB store (``SpiralDBConnector(..., store=True)``) has one writer at a time. A +job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) takes the writer +lease of every store dataset it may write (``store_writes``) before it checks a source, +computes or writes anything, and releases each lease when it ends, also when it fails. +A second writer is refused when it asks for the lease (``LeaseBusyError``), so before it +writes. A store write with no lease held is refused (``SpiralDBStoreLeaseRequiredError``, +raised by ``spiraldb_store_tables``). + +One lease per dataset: several store connectors on one dataset (a job's database and its +result database, a cached source's database) share the one lease the run takes. The lease +is refuse-only: no waiting, no taking over, no expiry (``spiraldb_lease``). +""" + +from __future__ import annotations + +import contextlib +from collections.abc import Callable, Iterable, Iterator +from typing import TYPE_CHECKING, Any + +from orcapod.databases import spiraldb_lease + +if TYPE_CHECKING: + from orcapod.databases.spiraldb_connector import SpiralDBConnector + + +def store_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: + """The distinct SpiralDB store connectors under ``databases``, in the order met. + + Args: + databases: Databases a run may write; ``None`` entries are skipped. + + Returns: + Each store connector once (by object). + """ + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + + found: list[SpiralDBConnector] = [] + for database in databases: + if not isinstance(database, ConnectorArrowDatabase): + continue + connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the store's connector, read by the one module that leases it + if connector is not None and not any(connector is c for c in found): + found.append(connector) + return found + + +@contextlib.contextmanager +def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: + """Hold the writer lease of every SpiralDB store dataset among ``databases``. + + Every lease is acquired before the body runs; a refused one releases those already + taken and raises. Each lease is released when the body ends, also when it raises + (or is cancelled or interrupted). A release that fails after the body raised is + added as a note to the body's error; after a body that succeeded it raises. + + Args: + databases: The databases the run may write. Nothing happens when none is a + SpiralDB store. + owner: Who holds the leases, shown to a refused second writer. + + Raises: + LeaseBusyError: If another writer holds one of the datasets; nothing of the + body ran. + LeaseError: If a lease cannot be verified, or released after the body + succeeded (the run's writes are committed then; the message says how to + clear the lease). + """ + groups: dict[tuple[str | None, str, str], list[SpiralDBConnector]] = {} + for connector in store_connectors(databases): + groups.setdefault(connector._writer_lease_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only + held: list[ + tuple[list[SpiralDBConnector], Callable[[], None], Callable[[], None]] + ] = [] + try: + for connectors in groups.values(): + check, release = take_lease(connectors[0], owner) + held.append((connectors, check, release)) + for connector in connectors: + _tables(connector).hold_lease(check) + except BaseException as error: + _release_all(held, error) + raise + try: + yield + except BaseException as error: + _release_all(held, error) + raise + _release_all(held, None) + + +def take_lease( + connector: SpiralDBConnector, owner: str +) -> tuple[Callable[[], None], Callable[[], None]]: + """Acquire the writer lease of a store connector's dataset (``spiraldb_lease``). + + Args: + connector: A SpiralDB store connector. + owner: Who holds it, shown to a refused second writer. + + Returns: + ``(check, release)``: verifies the lease is still held; releases it. + + Raises: + LeaseBusyError: If another writer holds the dataset. + LeaseError: If the claim cannot be verified. + """ + client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only + lease = spiraldb_lease.acquire(client, project_id, dataset, owner=owner) + + def check() -> None: + spiraldb_lease.check(client, lease) + + def release() -> None: + spiraldb_lease.release(client, lease) + + return check, release + + +def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # StoreTables; a store connector always has them while open + tables = connector._store_tables() # pyright: ignore[reportPrivateUsage] # the lease is handed to the store by this module only + if tables is None: + raise RuntimeError("not a SpiralDB store connector") + return tables + + +def _release_all( + held: list[tuple[list[SpiralDBConnector], Callable[[], None], Callable[[], None]]], + error: BaseException | None, +) -> None: + """Let go of and release every lease in ``held``. + + Args: + held: The leases taken, with their connectors. + error: The body's error, which a failed release is noted on; ``None`` when the + body succeeded, and the first failed release then raises. + """ + failure: BaseException | None = None + for connectors, check, release in reversed(held): + for connector in connectors: + with contextlib.suppress(RuntimeError): # closed: holds nothing any more + _tables(connector).let_go_of_lease(check) + try: + release() + except Exception as exc: # noqa: BLE001 # every lease is released; failures are reported below + if error is not None: + error.add_note( + f"Releasing the SpiralDB writer lease also failed: {exc}" + ) + elif failure is None: + failure = exc + else: + failure.add_note( + f"Releasing another SpiralDB writer lease failed: {exc}" + ) + if failure is not None: + raise failure diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 91a77a590..9b58f94cb 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -738,6 +738,16 @@ class SpiralDBWriteNotSupportedError(NotImplementedError): """ +class SpiralDBStoreLeaseRequiredError(RuntimeError): + """A SpiralDB store was written outside a job run (ITL-1844). + + A store (``SpiralDBConnector(..., store=True)``) is written only while a job run + (``job.run()``, ``job.run_async()`` or a job node's ``run()``) holds the dataset's + writer lease. A write anywhere else (a ``CachedSource`` read outside a run, a + ``ConnectorArrowDatabase`` flushed directly) is refused before anything is written. + """ + + class SpiralDBObserverNotSupportedError(SpiralDBWriteNotSupportedError): """A status or logging observer was given a SpiralDB store at setup (ITL-1540).""" diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 7ac378968..dff112297 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -41,6 +41,8 @@ check_sources, clear_run_rows, plan_run, + run_owner, + store_write_scope, ) from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( @@ -1373,10 +1375,41 @@ def run( whatever the orchestrator's ``error_policy``, also when the read was needed to write a node's results. Its rows are not recomputed and the table is not overwritten. + LeaseBusyError: If another writer holds a SpiralDB store the run would + write (ITL-1844): refused before any source is checked and before + anything is computed or written. The leases a run takes are + released when it ends, also when it fails. + LeaseError: If a SpiralDB writer lease cannot be verified, or released + at the end of a run that succeeded (its writes are committed). """ + # The writer leases of the SpiralDB stores the run writes are held from the + # source check to the end of the run (ITL-1844). + with contextlib.ExitStack() as leases: + return self._run_holding( + leases, + orchestrator, + observer, + materialize_results, + commit_every_rows, + load_only=load_only, + ) + + def _run_holding( + self, + leases: contextlib.ExitStack, + orchestrator: "SyncPipelineOrchestrator | AsyncPipelineOrchestrator | None", + observer: "ExecutionObserverProtocol | None", + materialize_results: bool, + commit_every_rows: int, + *, + load_only: bool, + ) -> RunSummary: + """``run``, with the run's writer leases entered on ``leases``.""" from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator - prepared = self._prepare_run(commit_every_rows, load_only=load_only) + prepared = self._prepare_run( + commit_every_rows, load_only=load_only, leases=leases + ) # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan counter = RunCountingObserver() @@ -1458,6 +1491,8 @@ async def run_async( RuntimeError: As for ``run``. OrcapodDatabaseWriteError: As for ``run``. OrcapodDatabaseReadError: As for ``run``. + LeaseBusyError: As for ``run``. + LeaseError: As for ``run``. """ from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator @@ -1469,7 +1504,31 @@ async def run_async( f"{type(orchestrator).__name__}. Use job.run(orchestrator=...) to run " "it." ) - prepared = self._prepare_run(commit_every_rows, load_only=load_only) + # The writer leases of the SpiralDB stores the run writes (ITL-1844). + with contextlib.ExitStack() as leases: + return await self._run_async_holding( + leases, + orchestrator, + observer, + materialize_results, + commit_every_rows, + load_only=load_only, + ) + + async def _run_async_holding( + self, + leases: contextlib.ExitStack, + orchestrator: "AsyncPipelineOrchestrator", + observer: "ExecutionObserverProtocol | None", + materialize_results: bool, + commit_every_rows: int, + *, + load_only: bool, + ) -> RunSummary: + """``run_async``, with the run's writer leases entered on ``leases``.""" + prepared = self._prepare_run( + commit_every_rows, load_only=load_only, leases=leases + ) # The state rule (ITL-1095): a node that holds a current run is not run again. plan = prepared.plan counter = RunCountingObserver() @@ -1499,13 +1558,19 @@ async def run_async( return summary def _prepare_run( - self, commit_every_rows: int, *, load_only: bool = False + self, + commit_every_rows: int, + *, + load_only: bool = False, + leases: contextlib.ExitStack | None = None, ) -> "_PreparedRun": """Check the job can run and build what a run needs; shared by both run forms. Args: commit_every_rows: As for ``run``. load_only: As for ``run``: a loaded job can run only this way. + leases: Where the run's SpiralDB writer leases are entered (ITL-1844), + just before its sources are checked; ``None`` takes none. Returns: The execution DAG, run id, pipeline URI and the database views of the run. @@ -1707,6 +1772,19 @@ def _prepare_run( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts(exec_dag.nodes()) + # One writer per SpiralDB store (ITL-1844): the run takes the writer lease of + # every store it may write before a source is checked (a cached source writes + # its cache then) and before anything is computed or written. A second writer + # is refused here. + if leases is not None: + leases.enter_context( + store_write_scope( + list(exec_dag.nodes()), + load_only=load_only, + databases=(pipeline_db, result_db), + owner=run_owner("/".join(self._name)), + ) + ) # Every source first takes in any new data, moving its modified time, before # the state rule judges any node (ITL-1102). unchecked = check_sources(exec_dag.nodes()) @@ -2250,7 +2328,10 @@ def load( such a file then loads. Also if the file's database or result database is a connector database (SQLite, PostgreSQL, SpiralDB) and the argument that gives it is missing: a connector is not rebuilt - from a file. The message names each such binding. + from a file. The message names each such binding. Also if a + SpiralDB database was saved on a store + (``SpiralDBConnector(..., store=True)``) and the one given is not, + or the other way round (ITL-1844). """ import json as _json import os @@ -2269,6 +2350,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, + spiraldb_store_mismatch, warn_saved_tags_as_data, ) @@ -2304,6 +2386,23 @@ def load( f"{path}: a database connector is not rebuilt from a saved job; it " "must be given to PipelineJob.load. " + "; ".join(missing) + "." ) + # A SpiralDB store and a plain SpiralDB connector read different tables + # (ITL-1844). + mismatched = [ + f"bindings.{slot_name}: {reason}" + for slot_name, given in ( + ("database", database), + ("result_database", result_database), + ) + if ( + reason := spiraldb_store_mismatch( + data.get("bindings", {}).get(slot_name), given + ) + ) + is not None + ] + if mismatched: + raise ValueError(f"{path}: " + "; ".join(mismatched) + ".") # Reconstruct pipeline from embedded blueprint data with tempfile.NamedTemporaryFile(suffix=".json", delete=False, mode="w") as tmp: diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index a18f23049..c5576750f 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -210,6 +210,92 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found +def _cache_databases(streams: Iterable[Any]) -> list[Any]: + """The databases of every ``CachedSource`` feeding ``streams`` (a cached source + writes its cache when it is checked or read), through wrapped sources and streams. + """ + from orcapod.core.nodes.source_node import SourceJobNode + from orcapod.core.sources.cached_source import CachedSource + + found: list[Any] = [] + visited: list[Any] = [] + pending = list(streams) + while pending: + stream = pending.pop(0) + if any(stream is seen for seen in visited): + continue + visited.append(stream) + if isinstance(stream, SourceJobNode): + if stream.bound_source is not None: + pending.append(stream.bound_source) + continue + if isinstance(stream, CachedSource): + found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the store a run must hold the lease of + inputs = getattr(stream, "live_source_inputs", None) + pending.extend(inputs or ()) + pending.extend(getattr(stream, "upstreams", ())) + return found + + +def _job_nodes_under(target: Any) -> list[Any]: + """``target`` and every job node it depends on.""" + found: list[Any] = [] + pending = [target] + while pending: + node = pending.pop() + if any(node is seen for seen in found) or not _is_job_node(node): + continue + found.append(node) + pending.extend(getattr(node, "upstreams", ())) + return found + + +def store_write_scope( + streams: Sequence[Any], + *, + load_only: bool, + databases: Iterable[Any] = (), + owner: str | None = None, +) -> Any: + """The writer leases a run holds on the SpiralDB stores it may write (ITL-1844). + + A full run may write ``databases`` (a job's database and result database), the + databases of the job nodes in ``streams`` and of every job node they depend on, and + the cache of every ``CachedSource`` feeding them. A load-only run writes none of + the nodes' databases; it may still write a cached source's cache, which takes in + new rows when checked or read. Entered before the run checks its sources + (``spiraldb_write_scope.store_writes``). + + Args: + streams: The nodes of the run, or the node whose ``run()`` it is. + load_only: Whether the run is load-only. + databases: The job's own databases, for a full run. + owner: Who holds the leases, shown to a refused second writer; by default + the job of the first of ``streams`` (``run_owner``). + + Returns: + The context manager that holds the leases. + """ + from orcapod.databases.spiraldb_write_scope import store_writes + + written: list[Any] = [] + if not load_only: + written.extend(databases) + nodes = [n for stream in streams for n in _job_nodes_under(stream)] + written.extend(_databases(nodes)) + written.extend(_cache_databases(streams)) + if owner is None: + owner = run_owner(_job_name(streams[0]) if streams else "") + return store_writes(written, owner=owner) + + +def run_owner(name: str) -> str: + """The owner text of a run's writer leases: the job and the process.""" + import os + + return f"orcapod job {name or '(unnamed)'} run, process {os.getpid()}" + + def check_sources(streams: Iterable[Any]) -> tuple[str, ...]: """Ask each source feeding ``streams`` once whether its data changed (ITL-1102). diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 71d9dc394..f7361d4ab 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -571,6 +571,46 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" +def spiraldb_store_mismatch(config: Any, given: Any) -> str | None: + """Why a database given at load cannot stand for a saved SpiralDB one, or ``None``. + + A job saved on a SpiralDB store (``SpiralDBConnector(..., store=True)``, ITL-1844) + is loaded with a store connector, and one saved on a plain SpiralDB connector with + a plain one: the two read different tables. The project and dataset are not + compared (a job may be pointed at a copy). + + Args: + config: The saved database configuration. + given: The database given to ``PipelineJob.load``. + + Returns: + The reason, or ``None`` when they agree or either is not a SpiralDB database. + """ + from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.spiraldb_connector import SpiralDBConnector + + if saved_connector_kind(config) != "spiraldb": + return None + if not isinstance(given, ConnectorArrowDatabase): + return None + connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over + if not isinstance(connector, SpiralDBConnector): + return None + saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) + saved_store = saved.get("store", False) is True + given_store = connector._store_mode # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a store + if saved_store == given_store: + return None + if saved_store: + return ( + "the job was saved on a SpiralDB store: pass a store connector, " + "SpiralDBConnector(..., store=True)" + ) + return ( + "the job was saved on a plain SpiralDB connector: pass one without store=True" + ) + + def _warn_unknown_resave_block(block: str) -> None: """Name the retained block without logging its type or values.""" logger.warning("Saving unknown %s block unchanged. It may hold credentials.", block) diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index d9272ce0d..8904a6f2f 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1,7 +1,8 @@ """A SpiralDB connector in store mode, under ``ConnectorArrowDatabase`` (ITL-1840). -On the fake (``fake_spiral_sdk``); no live SpiralDB. Store mode is private: a -``SpiralDBConnector`` built with ``_store=True``. The tests cover each table kind's +On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBConnector`` built +with ``store=True``. Direct writes hold the dataset's writer lease for the whole test +(``store(held=True)``), as a job run does for its own (ITL-1844). The tests cover each table kind's layout written and read back, the write rules of ITL-1386, refusals of tables that are not the store's, the data-context checks and the listing the stale-layout check uses. """ @@ -26,6 +27,8 @@ from orcapod.databases import spiral_store_identity as identity from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.databases.spiraldb_write_scope import store_writes, take_lease +from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import InputValidationError, SpiralDBWriteNotSupportedError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod @@ -39,14 +42,34 @@ utc = dt.timezone.utc +# The writer lease each dataset written directly holds for the test: (check, release). +_test_leases: dict[tuple[str, str], tuple[Any, Any]] = {} + + @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) + try: + yield tmp_path + finally: + for _, release in _test_leases.values(): + release() + _test_leases.clear() + + +def store( + project: str = "p", dataset: str = "d", *, held: bool = True +) -> SpiralDBConnector: + """A store connector; ``held`` writes it directly under the dataset's writer lease, + taken once per test (a job run takes its own: pass ``held=False``).""" + connector = SpiralDBConnector(project, dataset, store=True) + if held: + lease = _test_leases.get((project, dataset)) + if lease is None: + lease = take_lease(connector, "test") + _test_leases[(project, dataset)] = lease + tables_of(connector).hold_lease(lease[0]) + return connector def tables_of(connector: SpiralDBConnector) -> StoreTables: @@ -84,7 +107,12 @@ def _table(name: str) -> Any: def _tables() -> list[dict[str, Any]]: - return fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + """The dataset tables, without the writer lease's generation tables.""" + return [ + t + for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + if not is_spiral_lease_table_name(t["name"]) + ] # ------------------------------------------------------------------ write and read @@ -862,15 +890,7 @@ def the_other_writer(_: str) -> None: assert values == {b"r1": 0, b"r9": 101} -# ------------------------------------------------------ private, plain, closed - - -@pytest.mark.usefixtures("root") -def test_a_store_mode_connector_is_not_saved() -> None: - with pytest.raises(ValueError, match="not saved"): - _ = store().to_config() - with pytest.raises(ValueError, match="not saved"): - _ = ConnectorArrowDatabase(store()).to_config() +# ------------------------------------------------------ plain, closed @pytest.mark.usefixtures("root") @@ -1004,12 +1024,14 @@ def _cleared() -> Iterator[None]: @pytest.mark.parametrize("orchestrator", ["sync", "async"]) def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(store()) + database = ConnectorArrowDatabase(store(held=False)) _ = _job(database, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) - cached = _cached(database).as_table() + # A cached source read outside a job run writes under a lease held here. + with store_writes([database], owner="test"): + cached = _cached(database).as_table() assert sorted(calls) == [1, 2, 3] and sorted(delivered) == [2, 4, 6] - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(store(held=False)) paths = fresh.list_table_paths() assert sorted(p[-1] for p in paths) == sorted(LAYOUTS) for path in paths: @@ -1025,7 +1047,8 @@ def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: assert calls == [] and delivered == [] assert sorted(again.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] assert sorted(again.nodes["sel"].as_table()["double"].to_pylist()) == [2, 4, 6] - assert _cached(fresh).as_table().equals(cached) + with store_writes([fresh], owner="test"): + assert _cached(fresh).as_table().equals(cached) @pytest.mark.usefixtures("root", "_cleared") @@ -1034,7 +1057,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( orchestrator: str, ) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(store()) + database = ConnectorArrowDatabase(store(held=False)) _ = _job(database, SOURCE_ROWS[:2]).run(orchestrator=run[orchestrator]()) before = { p: database.get_all_records(p, record_id_column="__rid") @@ -1042,7 +1065,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( } calls.clear() delivered.clear() - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(store(held=False)) _ = _job(fresh, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) assert calls == [3] and delivered == [6] for path, earlier in before.items(): @@ -1420,7 +1443,7 @@ def test_a_store_backed_job_holds_its_rows_and_reports_observer_losses( _database, # pyright: ignore[reportPrivateUsage] ) - database = ConnectorArrowDatabase(store()) + database = ConnectorArrowDatabase(store(held=False)) job = _job(database, SOURCE_ROWS) def run(**kwargs: Any) -> Any: diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py new file mode 100644 index 000000000..6f42ef3c3 --- /dev/null +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -0,0 +1,477 @@ +"""Job runs on a SpiralDB store: every table kind, the writer lease, save and load +(ITL-1844). + +On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a store +(``SpiralDBConnector(..., store=True)``) and on Delta, and every stored table is +compared: same paths, same rows, apart from the columns a run fills with its own time +or a random id. +""" + +from __future__ import annotations + +import asyncio +import json +from collections.abc import Callable, Iterator +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.core.operators import SelectDataColumns +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import ( + ConnectorArrowDatabase, + DeltaTableDatabase, + SpiralDBConnector, +) +from orcapod.databases import spiraldb_lease +from orcapod.databases.spiraldb_write_scope import take_lease +from orcapod.databases.store_table_names import is_spiral_lease_table_name +from orcapod.errors import SpiralDBStoreLeaseRequiredError +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.side_effects import SideEffectPod, sink_pod +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode +from tests.test_databases import fake_spiral_sdk as fake + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +JOB = "itl1844" +LAYOUTS = ("odb_v3", "pdb_v2", "rdb_v1", "sdb_v2", "tdb_v2") +# Filled by each run with its own time or a random id. +VOLATILE = { + "__data_id", + "__pipeline_record_id", + "__pipeline_run_id", + "__pod_ts", + "__recorded_at", + "_source_total", + "_source_ratio", + "executed_at", + "pipeline_run_id", +} + +calls: list[tuple[int, int]] = [] +delivered: list[int] = [] + + +@function_pod(output_keys=("total", "ratio")) +def combine(x: int, y: int) -> tuple[int, float]: + calls.append((x, y)) + return x + y, x / y + + +def _deliver(total: int, ratio: float, ctx: Any) -> None: + delivered.append(total) + + +def _rows(n: int = 3) -> pa.Table: + """Two tags and two data columns.""" + schema = pa.schema( + [ + pa.field("unit", pa.large_string(), nullable=False), + pa.field("trial", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + return pa.table( + { + "unit": ["u1", "u2", "u1", "u2"][:n], + "trial": [1, 1, 2, 2][:n], + "x": [1, 2, 3, 4][:n], + "y": [5, 6, 7, 8][:n], + }, + schema=schema, + ) + + +def _cached(cache: Any, table: pa.Table, *, order: str = "as given") -> CachedSource: + if order == "reversed": + table = table.select(list(reversed(table.column_names))) + return CachedSource( + ArrowTableSource( + table, + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ), + cache_database=cache, + ) + + +def _job( + database: Any, + *, + result_database: Any = None, + table: pa.Table | None = None, + cache_mode: CacheMode = CacheMode.LOG, + order: str = "as given", +) -> PipelineJob: + """Every table kind: a cached source (sdb), a function node (pdb, rdb), a logged + operator node (odb) and a sink (tdb).""" + job = PipelineJob(name=JOB, database=database, result_database=result_database) + with job: + source = _cached(database, _rows() if table is None else table, order=order) + out = combine.pod(source, label="combine") + SelectDataColumns(["total", "ratio"])(out, label="select") + sink = sink_pod(_deliver) + assert isinstance(sink, SideEffectPod) + sink.process(out, label="sink") + job.nodes["select"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=cache_mode + ) + return job + + +@pytest.fixture +def root(tmp_path: Path) -> Iterator[Path]: + calls.clear() + delivered.clear() + with fake.install(tmp_path): + yield tmp_path + calls.clear() + delivered.clear() + + +def _store(dataset: str = "d") -> ConnectorArrowDatabase: + return ConnectorArrowDatabase(SpiralDBConnector("p", dataset, store=True)) + + +def _store_tables(dataset: str = "d") -> list[str]: + return sorted( + t["name"] + for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + if t["dataset"] == dataset and not is_spiral_lease_table_name(t["name"]) + ) + + +def _lease_tables(dataset: str = "d") -> list[str]: + return sorted( + t["name"] + for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + if t["dataset"] == dataset and is_spiral_lease_table_name(t["name"]) + ) + + +def _comparable(table: pa.Table) -> list[tuple[Any, ...]]: + kept = [c for c in sorted(table.column_names) if c not in VOLATILE] + return sorted( + (tuple(str(row[c]) for c in kept) for row in table.select(kept).to_pylist()) + ) + + +def _same_tables(store: Any, delta: Any) -> None: + """Same paths, and in each the same rows, apart from the volatile columns.""" + paths = sorted(store.list_table_paths()) + assert paths == sorted(delta.list_table_paths()) + for path in paths: + on_store = store.get_all_records(path) + on_delta = delta.get_all_records(path) + assert on_store is not None and on_delta is not None, path + assert on_store.schema.names == on_delta.schema.names, path + assert _comparable(on_store) == _comparable(on_delta), path + + +def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: + if entry == "sync": + return job.run(**kwargs) + if entry == "async orchestrator": + return job.run(orchestrator=AsyncPipelineOrchestrator(), **kwargs) + if entry == "run_async": + return asyncio.run(job.run_async(**kwargs)) + assert entry == "node run" + for label in ("select", "sink"): + _ = job.nodes[label].run(**kwargs) + return None + + +ENTRIES = ["sync", "async orchestrator", "run_async", "node run"] +# Leases one run of an entry takes: a node run runs two nodes, each with its own. +LEASES = {"sync": 1, "async orchestrator": 1, "run_async": 1, "node run": 2} + + +# ------------------------------------------------------------ every table kind + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("order", ["as given", "reversed"]) +def test_every_table_kind_is_stored_as_on_delta( + root: Path, entry: str, order: str +) -> None: + store = _store() + delta = DeltaTableDatabase(root / "delta") + for database in (store, delta): + _ = _run(_job(database, order=order), entry) + assert sorted(p[-1] for p in store.list_table_paths()) == sorted(LAYOUTS) + _same_tables(store, delta) + # Each run took the store's lease once and released it. + assert len(_lease_tables()) == LEASES[entry] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("dataset", ["other", "same"]) +def test_a_separate_result_database_is_stored_as_on_delta( + root: Path, entry: str, dataset: str +) -> None: + """Results in a separate store, on another dataset (two leases) or on the same + dataset through another connector (one lease).""" + store, results = _store(), _store("r" if dataset == "other" else "d") + delta = DeltaTableDatabase(root / "delta") + delta_results = DeltaTableDatabase(root / "delta_results") + _ = _run(_job(store, result_database=results), entry) + _ = _run(_job(delta, result_database=delta_results), entry) + if dataset == "other": + _same_tables(store, delta) + _same_tables(results, delta_results) + assert len(_lease_tables("d")) == LEASES[entry] + assert len(_lease_tables("r")) == LEASES[entry] + else: + on_delta = sorted( + [*delta.list_table_paths(), *delta_results.list_table_paths()] + ) + assert sorted(store.list_table_paths()) == on_delta + assert len(_lease_tables("d")) == LEASES[entry] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_new_input_and_a_replay_are_stored_as_on_delta( + root: Path, entry: str +) -> None: + """A second run with one more row computes it alone; a REPLAY run of the operator + reads the operator cache back, on both databases alike.""" + store = _store() + delta = DeltaTableDatabase(root / "delta") + for database in (store, delta): + _ = _run(_job(database, table=_rows(3)), entry) + calls.clear() + for database in (store, delta): + _ = _run(_job(database, table=_rows(4)), entry) + assert calls == [(4, 8), (4, 8)] + _same_tables(store, delta) + replayed = [] + for database in (store, delta): + job = _job(database, table=_rows(4), cache_mode=CacheMode.REPLAY) + _ = _run(job, entry) + replayed.append(_comparable(job.nodes["select"].as_table())) + assert replayed[0] == replayed[1] and len(replayed[0]) == 4 + _same_tables(store, delta) + + +# ------------------------------------------------------------------ load only + + +@pytest.mark.usefixtures("root") +def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None: + store = _store() + job = _job(store) + _ = job.run() + saved = root / "job.json" + job.save(saved) + text = saved.read_text() + assert '"store": true' in text + assert not any(word in text.lower() for word in ("secret", "token", "private")) + leases = _lease_tables() + loaded = PipelineJob.load(saved, database=_store()) + for label in ("combine", "select"): + stored = loaded.nodes[label].as_source().as_table() + assert stored.num_rows == 3, label + # A load-only run of the loaded job writes nothing: it takes no lease. (Its cached + # source, over a connector database, is not rebuilt from the file.) + _ = loaded.run(load_only=True) + assert _lease_tables() == leases + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +def test_a_load_only_run_over_a_cached_source_holds_its_lease(entry: str) -> None: + """A cached source writes its cache when checked or read, so a load-only run takes + the lease of the cache's store; it writes no node's table.""" + store = _store() + _ = _job(store).run() + before = {p: store.get_all_records(p) for p in store.list_table_paths()} + job = _job(store, table=_rows(4)) + _ = _run(job, entry, load_only=True) + assert len(_lease_tables()) == 1 + LEASES[entry] + for path, rows in before.items(): + now = store.get_all_records(path) + assert now is not None and rows is not None + expected = 4 if path[-1] == "sdb_v2" else rows.num_rows + assert now.num_rows == expected, path + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize(("saved_store", "given_store"), [(True, False), (False, True)]) +def test_load_refuses_a_spiraldb_connector_of_the_other_kind( + root: Path, saved_store: bool, given_store: bool +) -> None: + saved = root / "job.json" + if saved_store: + _job(_store()).save(saved) + else: + delta = DeltaTableDatabase(root / "delta") + _job(delta).save(saved) + data = json.loads(saved.read_text()) + data["bindings"]["database"] = ConnectorArrowDatabase( + SpiralDBConnector("p", "d") + ).to_config() + saved.write_text(json.dumps(data)) + given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=given_store)) + with pytest.raises(ValueError, match="bindings.database.*store"): + _ = PipelineJob.load(saved, database=given) + + +@pytest.mark.usefixtures("root") +def test_the_store_flag_is_saved_without_credentials() -> None: + assert SpiralDBConnector("p", "d", store=True).to_config() == { + "connector_type": "spiraldb", + "project_id": "p", + "dataset": "d", + "overrides": None, + "store": True, + } + assert "store" not in SpiralDBConnector("p", "d").to_config() + rebuilt = SpiralDBConnector.from_config( + SpiralDBConnector("p", "d", store=True).to_config() + ) + assert rebuilt._store_tables() is not None # pyright: ignore[reportPrivateUsage] + with pytest.raises(TypeError, match="store must be True or False"): + _ = SpiralDBConnector("p", "d", store="yes") # pyright: ignore[reportArgumentType] + + +# ------------------------------------------------------------------ the lease + + +def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: + """Hold the dataset's lease as another writer would; returns its release.""" + _, release = take_lease( + SpiralDBConnector("p", dataset, store=True), "another writer" + ) + return release + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ENTRIES) +@pytest.mark.parametrize("load_only", [False, True]) +def test_a_second_writer_is_refused_before_anything( + entry: str, load_only: bool +) -> None: + release = _held_by_another_writer() + job = _job(_store()) + with pytest.raises(spiraldb_lease.LeaseBusyError, match="another writer"): + _ = _run(job, entry, load_only=load_only) + assert _store_tables() == [] + assert calls == [] and delivered == [] + # Once the other writer releases, the run goes ahead. + release() + if not load_only: + _ = _run(job, entry) + assert len(calls) == 3 + + +@pytest.mark.usefixtures("root") +def test_a_second_writer_on_the_result_database_is_refused() -> None: + release = _held_by_another_writer("r") + job = _job(_store(), result_database=_store("r")) + with pytest.raises(spiraldb_lease.LeaseBusyError): + _ = job.run() + assert _store_tables("d") == [] and _store_tables("r") == [] + # The lease the run took on its own database was released. + _, own = take_lease(SpiralDBConnector("p", "d", store=True), "check") + own() + release() + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_the_lease_is_released_when_a_run_fails(entry: str) -> None: + @function_pod(output_keys="z") + def boom(x: int) -> int: + raise RuntimeError("boom") + + store = _store() + job = PipelineJob(name=JOB, database=store) + with job: + source = _cached(store, _rows()) + boom.pod(source.select_data_columns(["x"]), label="boom") + orchestrator = ( + SyncPipelineOrchestrator(error_policy="fail_fast") + if entry == "sync" + else AsyncPipelineOrchestrator(error_policy="fail_fast") + ) + with pytest.raises(Exception, match="boom"): + if entry == "run_async": + assert isinstance(orchestrator, AsyncPipelineOrchestrator) + _ = asyncio.run(job.run_async(orchestrator=orchestrator)) + else: + _ = job.run(orchestrator=orchestrator) + # Released: another writer can take it. + _held_by_another_writer()() + + +@pytest.mark.usefixtures("root") +def test_a_failed_release_after_a_run_raises_and_the_tables_are_complete( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = _store() + + def failing(client: Any, lease: Any) -> None: + raise spiraldb_lease.LeaseError("release lost") + + monkeypatch.setattr(spiraldb_lease, "release", failing) + with pytest.raises(spiraldb_lease.LeaseError, match="release lost"): + _ = _job(store).run() + monkeypatch.undo() + delta = DeltaTableDatabase(root / "delta") + _ = _job(delta).run() + fresh = _store() + assert sorted(p[-1] for p in fresh.list_table_paths()) == sorted(LAYOUTS) + _same_tables(fresh, delta) + + +@pytest.mark.usefixtures("root") +def test_a_failed_release_after_a_failed_run_is_noted_on_its_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + @function_pod(output_keys="z") + def boom(x: int) -> int: + raise RuntimeError("boom") + + def failing(client: Any, lease: Any) -> None: + raise spiraldb_lease.LeaseError("release lost") + + store = _store() + job = PipelineJob(name=JOB, database=store) + with job: + boom.pod(_cached(store, _rows()).select_data_columns(["x"]), label="boom") + monkeypatch.setattr(spiraldb_lease, "release", failing) + with pytest.raises(RuntimeError, match="boom") as raised: + _ = job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast")) + assert any("release lost" in note for note in raised.value.__notes__) + + +@pytest.mark.usefixtures("root") +def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: + store = _store() + with pytest.raises(SpiralDBStoreLeaseRequiredError, match="within a job run"): + _ = _cached(store, _rows()).as_table() + store.add_records( + ("t", "rdb_v1"), + pa.table( + { + "__record_id": pa.array([b"r0"], pa.large_binary()), + "v": [1], + "__data_context": ["std:v1:default"], + } + ), + record_id_column="__record_id", + ) + with pytest.raises(SpiralDBStoreLeaseRequiredError): + store.flush() + assert _store_tables() == [] and _lease_tables() == [] From ad9a91c78d997e4b6674ad5c1a690a3ef07c639d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:33:54 -0800 Subject: [PATCH 21/50] docs(spiraldb): the SpiralDB store page, changelog fragment and end-to-end evaluation script (ITL-1844) Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1844.md | 28 ++ docs/api/databases.md | 4 +- docs/api/errors.md | 2 + docs/concepts/pipeline-job.md | 8 +- docs/concepts/spiraldb-store.md | 125 +++++++ docs/dev/scripts/itl_1844_store_evaluation.py | 331 ++++++++++++++++++ docs/reference/database-types.md | 2 +- site/astro.config.mjs | 1 + tests/test_databases/type_matrix.py | 2 +- 9 files changed, 497 insertions(+), 6 deletions(-) create mode 100644 changelog.d/ITL-1844.md create mode 100644 docs/concepts/spiraldb-store.md create mode 100644 docs/dev/scripts/itl_1844_store_evaluation.py diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md new file mode 100644 index 000000000..bb0054013 --- /dev/null +++ b/changelog.d/ITL-1844.md @@ -0,0 +1,28 @@ +### Added + +- A SpiralDB dataset can be a job's database: `SpiralDBConnector(project_id, dataset, store=True)` + under `ConnectorArrowDatabase` stores every table a job writes (function results and + pipeline records, operator caches, cached sources, side-effect logs), also as a separate + result database. Provisional in 0.4.0: the store's table format and its writer lease may + change in a later version, which may not read tables written now. Nothing of the store + enters a hash. See "SpiralDB as a Job's Database" in the concepts. +- One writer per SpiralDB store: `job.run()`, `job.run_async()` and a job node's `run()` + take the dataset's writer lease before checking a source or writing anything, and release + it when they end, also when they fail. A second writer is refused then with + `LeaseBusyError`, before anything of its run happens. A stale lease is cleared by its + table id with `spiraldb_lease.clear(..., confirm_writer_stopped=True)`. +- A job saved on a store records `store: true` and no credential; `PipelineJob.load` + takes the connector again and refuses a SpiralDB connector of the other kind. + +### Known limitations + +- Only a job run writes a SpiralDB store: a write outside a run (a cached source read + outside a run, a `ConnectorArrowDatabase` flushed directly) raises + `SpiralDBStoreLeaseRequiredError`. A way to hold the lease outside a run is later work + (ITL-1849). +- The writer lease is refuse-only: no waiting, no takeover, no expiry. Each run leaves one + small lease table in the dataset, which is kept. +- A store reads a table's whole key column to tell which rows it holds, and whole tables + to read stored rows, so a run's cost grows with the tables' history. +- The store does not take over tables it did not write, and status and logging observers + still refuse a SpiralDB database. diff --git a/docs/api/databases.md b/docs/api/databases.md index 0c12ead5a..e787ee033 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -7,7 +7,9 @@ code. See site/README.md. --> Database backends store pipeline results. The SQLite and PostgreSQL connectors support -reads and writes through `ConnectorArrowDatabase`. The SpiralDB connector is read-only. +reads and writes through `ConnectorArrowDatabase`. The SpiralDB connector reads, and writes +only when opened as a job's store (`store=True`, provisional; see +[SpiralDB as a Job's Database](../concepts/spiraldb-store.md)). **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. diff --git a/docs/api/errors.md b/docs/api/errors.md index 860739d66..c4b21e759 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -132,6 +132,8 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.SpiralDBObserverNotSupportedError +::: orcapod.errors.SpiralDBStoreLeaseRequiredError + ::: orcapod.errors.SpiralDBSignInError ## Feature availability and stability diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 90dde0c30..0557a3deb 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -277,8 +277,9 @@ refused. PostgreSQL also refuses column names and explicit table identifiers lon 63 bytes, which it would truncate (`UnstorableTableNameError` for a table). SQLite and PostgreSQL stores generate table names within 63 bytes from the node's path, using a readable hint and a digest of the full path. A database on -`SpiralDBConnector` refuses every write for now (`SpiralDBWriteNotSupportedError`): Orcapod -reads SpiralDB only. The full list, +`SpiralDBConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened +as a store, `SpiralDBConnector(..., store=True)`: see +[SpiralDB as a Job's Database](spiraldb-store.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds @@ -292,7 +293,8 @@ is attached to them, before anything runs: - every side-effect node, on SQLite; - every operator node with caching on (`CacheMode.LOG` or `REPLAY`), on SQLite: the SQLite connector has no column type for a timestamp (adding one is ITL-1482); -- every node that stores anything, on SpiralDB. +- every node that stores anything, on a plain SpiralDB connector (a SpiralDB store keeps + them all). An operator cache or cached source on a SQL connector is also refused when it is written, before anything is stored, if one of its own columns has a type or name the connector does not store. On diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md new file mode 100644 index 000000000..86663f086 --- /dev/null +++ b/docs/concepts/spiraldb-store.md @@ -0,0 +1,125 @@ +# SpiralDB as a Job's Database + +A job can keep everything it stores in a SpiralDB dataset: function results, pipeline +records, operator caches, cached sources and side-effect logs. Open the dataset as a +**store** and give it to the job as any other database. + +!!! warning "Provisional in 0.4.0" + The SpiralDB store is provisional. The format of its tables (how a table is named, + what its metadata records, how values are encoded) and its writer lease may change in + a later version, and a later version may not read tables written now. Nothing of the + store enters a hash: a job's hashes, ids and stored paths are the same on SpiralDB as + on Delta. + +## Opening a store + +`SpiralDBConnector(project_id, dataset, store=True)` opens one dataset as a store. Wrap it +in `ConnectorArrowDatabase` and use it as the job's database, its separate result +database, or a cached source's database: + + +```python +from orcapod import PipelineJob +from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector + +store = ConnectorArrowDatabase( + SpiralDBConnector("my-project-123456", "pipeline_results", store=True) +) +job = PipelineJob(name="experiment", database=store) +``` + +Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved +`spiral login`. Without `store=True`, a `SpiralDBConnector` reads existing keyed tables +(a `SpiralDBTableSource`) and writes nothing. + +Each stored table is one keyed table of the dataset, named from its path (a readable +part of the path and a digest of all of it). Its metadata records the full path, the +layout, the data context and the columns, so a table under that name that another +writer made for something else is refused, never written over. The store reads and +writes only the tables it made: it does not take over a table it did not write. + +## One writer at a time + +A store has one writer at a time. Every run of a job (`job.run()`, `job.run_async()`, +a job node's `run()`, and a load-only run that reads a cached source) takes the +dataset's **writer lease** before it checks a source, computes or writes anything, and +releases it when it ends, also when it fails. A run whose database and result database +are on one dataset takes one lease. + +While one run holds the lease, a second writer, in this process or another, is refused +when its run starts, with `LeaseBusyError`. Nothing of its run has happened then: no +source was checked, nothing computed, no table made. The error names the lease's table +id and who holds it. The lease is refuse-only: the second writer does not wait and never +takes the lease over, and a lease does not expire. + + +```python +from orcapod.databases.spiraldb_lease import LeaseBusyError + +try: + job.run() +except LeaseBusyError as refused: + print(refused) + # SpiralDB dataset 'pipeline_results' has a conflicting writer lease (owner ..., table ID ...). ... +``` + +Only a job run writes a store. A write anywhere else (a cached source read outside a +run, a `ConnectorArrowDatabase` flushed directly) raises +`SpiralDBStoreLeaseRequiredError` before anything is written. A load-only run of a job +writes no node's table, so it takes a lease only for a cached source it reads. + +### A lease left behind + +A process that stops in the middle of a run (killed, or a lost connection) leaves its +lease held, and every later run is refused. Once you are sure that writer has stopped, +and every write it sent has settled, clear the lease by the table id the refusal named: + + +```python +import spiral + +from orcapod.databases import spiraldb_lease + +spiraldb_lease.clear( + spiral.Client(), "
", confirm_writer_stopped=True +) +``` + +Clearing the lease of a writer that is still running lets a second writer in while the +first is still writing. Each lease is a small keyed table of the dataset; keep every +one, also released ones: removing one by hand can let two writers in. + +## Saving and loading a job + +A job saved on a store records the connector (`connector_type`, project, dataset, the +service address and `store: true`), never a credential. A connector is not rebuilt from +a saved file: give it again when loading, as for every connector database: + + +```python +loaded = PipelineJob.load( + "experiment.json", + database=ConnectorArrowDatabase( + SpiralDBConnector("my-project-123456", "pipeline_results", store=True) + ), +) +``` + +A job saved on a store is loaded with a store connector, and one saved on a plain +`SpiralDBConnector` with a plain one: the load refuses the other kind, since the two +read different tables. + +## Limits + +- Each check of which rows a table holds reads the table's whole key column, and each + read of stored rows reads the whole table, so the cost of a run grows with the + table's history. +- Only a job run writes a store: a cached source over a store is read within a run. A + way to hold the lease outside a run is planned (ITL-1849). +- Status and logging observers do not write to SpiralDB: they raise + `SpiralDBObserverNotSupportedError` at setup; give them another database such as + Delta. +- The store does not take over tables it did not write. +- A column the store cannot keep (a null struct, a duration, a nested logical type) is + refused before anything of its table is written, naming the column. The other databases are compared type by type in + [Data types per database](../reference/database-types.md). diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_store_evaluation.py new file mode 100644 index 000000000..b0018f6ae --- /dev/null +++ b/docs/dev/scripts/itl_1844_store_evaluation.py @@ -0,0 +1,331 @@ +"""End-to-end evaluation of the SpiralDB store, as switched on by ITL-1844. + +One job holding every table kind (a cached source: ``sdb_v2``; a function pod: ``pdb_v2`` +and ``rdb_v1``; a logged operator node: ``odb_v3``; a side-effect sink: ``tdb_v2``) is run +through each scenario on Delta and on a SpiralDB store, and every stored table is compared +value for value, apart from the columns a run fills with its own time or a random id. + +Scenarios: a first run (sync), a second run with one more input row, a REPLAY run of the +operator, an async run (``run_async``) and a node run on fresh job names, a separate +result database on the same dataset, a saved job loaded with the store and read back, a +load-only run, and a second writer refused while a lease is held. + + uv run python docs/dev/scripts/itl_1844_store_evaluation.py fake + uv run python docs/dev/scripts/itl_1844_store_evaluation.py live \\ + --project --dataset + +``live`` needs a sign-in spiral-sdk finds (the ``SPIRAL_*`` environment variables) and +writes into the given dataset only: store tables of job names starting with +``itl1844_eval_``, and one lease table per run. spiral-sdk cannot drop a keyed +table, so they stay; the report lists every one. Prints a JSON report. +""" + +from __future__ import annotations + +import argparse +import asyncio +import contextlib +import json +import sys +import tempfile +import time +import warnings +from collections.abc import Iterator +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import pyarrow as pa + +REPO = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(REPO)) + +from orcapod import PipelineJob, function_pod # noqa: E402 +from orcapod.core.operators import SelectDataColumns # noqa: E402 +from orcapod.core.sources.cached_source import CachedSource # noqa: E402 +from orcapod.databases import ( # noqa: E402 + ConnectorArrowDatabase, + DeltaTableDatabase, + SpiralDBConnector, +) +from orcapod.databases import spiraldb_lease # noqa: E402 +from orcapod.databases.spiral_store_identity import spiral_store_table_name # noqa: E402 +from orcapod.databases.spiraldb_connector import open_keyed_table # noqa: E402 +from orcapod.databases.spiraldb_write_scope import take_lease # noqa: E402 +from orcapod.databases.store_table_names import spiral_lease_table_name # noqa: E402 +from orcapod.side_effects import SideEffectPod, sink_pod # noqa: E402 +from orcapod.sources import ArrowTableSource # noqa: E402 +from orcapod.types import CacheMode # noqa: E402 + +warnings.filterwarnings("ignore") + +VOLATILE = { + "__data_id", + "__pipeline_record_id", + "__pipeline_run_id", + "__pod_ts", + "__recorded_at", + "_source_total", + "_source_ratio", + "executed_at", + "pipeline_run_id", +} +CALLS: list[tuple[int, int]] = [] +SENT: list[int] = [] + + +@function_pod(output_keys=("total", "ratio")) +def combine(x: int, y: int) -> tuple[int, float]: + """The function pod (counted).""" + CALLS.append((x, y)) + return x + y, x / y + + +def deliver(total: int, ratio: float, ctx: Any) -> None: + """The side effect: records each delivered total.""" + SENT.append(total) + + +def rows(n: int) -> pa.Table: + """``n`` input rows: two tags, two data columns.""" + schema = pa.schema( + [ + pa.field("unit", pa.large_string(), nullable=False), + pa.field("trial", pa.int64(), nullable=False), + pa.field("x", pa.int64(), nullable=False), + pa.field("y", pa.int64(), nullable=False), + ] + ) + return pa.Table.from_pylist( + [ + {"unit": f"u{i % 3}", "trial": i // 3, "x": i + 1, "y": 2 * i + 5} + for i in range(n) + ], + schema=schema, + ) + + +def build( + name: str, + database: Any, + *, + n: int, + result_database: Any = None, + cache_mode: CacheMode = CacheMode.LOG, +) -> PipelineJob: + """The evaluated job: every table kind.""" + job = PipelineJob(name=name, database=database, result_database=result_database) + with job: + source = CachedSource( + ArrowTableSource( + rows(n), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ), + cache_database=database.at(name, "cache"), + ) + out = combine.pod(source, label="combine") + SelectDataColumns(["total", "ratio"])(out, label="select") + sink = sink_pod(deliver) + assert isinstance(sink, SideEffectPod) + sink.process(out, label="sink") + job.nodes["select"].attach_databases( + pipeline_database=database.at(name), cache_mode=cache_mode + ) + return job + + +def comparable(table: pa.Table) -> list[tuple[str, ...]]: + kept = [c for c in sorted(table.column_names) if c not in VOLATILE] + return sorted( + tuple(str(r[c]) for c in kept) for r in table.select(kept).to_pylist() + ) + + +def compare(store: Any, delta: Any, prefix: tuple[str, ...]) -> dict[str, Any]: + """Every table under ``prefix``: the same paths and rows on both.""" + paths = sorted(store.list_table_paths(prefix)) + other = sorted(delta.list_table_paths(prefix)) + report: dict[str, Any] = {"same_paths": paths == other, "tables": {}} + for path in paths: + a, b = store.get_all_records(path), delta.get_all_records(path) + same = ( + a is not None + and b is not None + and a.schema.names == b.schema.names + and comparable(a) == comparable(b) + ) + report["tables"]["/".join(path)] = { + "layout": path[-1], + "rows": None if a is None else a.num_rows, + "same_as_delta": same, + } + report["ok"] = report["same_paths"] and all( + t["same_as_delta"] for t in report["tables"].values() + ) + return report + + +def timed(report: dict[str, Any], label: str, run: Any) -> Any: + start = time.perf_counter() + result = run() + report.setdefault("seconds", {})[label] = round(time.perf_counter() - start, 3) + return result + + +def evaluate(project: str, dataset: str, stamp: str, work: Path) -> dict[str, Any]: + def store() -> ConnectorArrowDatabase: + return ConnectorArrowDatabase(SpiralDBConnector(project, dataset, store=True)) + + delta = DeltaTableDatabase(work / "delta") + report: dict[str, Any] = {"stamp": stamp, "scenarios": {}} + s = report["scenarios"] + + # 1. first run, sync. + name = f"itl1844_eval_{stamp}_sync" + on_store = store() + CALLS.clear() + _ = timed(report, "first run (store)", lambda: build(name, on_store, n=6).run()) + store_calls = len(CALLS) + _ = build(name, delta, n=6).run() + s["first run"] = { + **compare(on_store, delta, (name,)), + "calls_on_store": store_calls, + } + + # 2. one more input row: only it is computed and delivered. + CALLS.clear() + SENT.clear() + _ = timed(report, "new row (store)", lambda: build(name, store(), n=7).run()) + store_calls, store_sent = len(CALLS), len(SENT) + _ = build(name, delta, n=7).run() + s["new row"] = { + **compare(store(), delta, (name,)), + "calls_on_store": store_calls, + "delivered_on_store": store_sent, + } + + # 3. REPLAY of the operator cache. + replayed = [] + for database in (store(), delta): + job = build(name, database, n=7, cache_mode=CacheMode.REPLAY) + _ = job.run() + replayed.append(comparable(job.nodes["select"].as_table())) + s["replay"] = {"ok": replayed[0] == replayed[1], "rows": len(replayed[0])} + + # 4. run_async and 5. node runs, on fresh names. + for label, run in ( + ("run_async", lambda job: asyncio.run(job.run_async())), + ("node run", lambda job: [job.nodes[k].run() for k in ("select", "sink")]), + ): + fresh = f"itl1844_eval_{stamp}_{label.replace(' ', '_')}" + _ = timed(report, f"{label} (store)", lambda: run(build(fresh, store(), n=6))) + _ = run(build(fresh, delta, n=6)) + s[label] = compare(store(), delta, (fresh,)) + + # 6. a separate result database on the same dataset (one lease). + fresh = f"itl1844_eval_{stamp}_results" + results_delta = DeltaTableDatabase(work / "delta_results") + _ = build(fresh, store(), n=6, result_database=store().at(fresh, "results")).run() + _ = build(fresh, delta, n=6, result_database=results_delta).run() + stored = sorted(store().list_table_paths((fresh,))) + s["separate results"] = { + "ok": len(stored) + == len(delta.list_table_paths((fresh,))) + + len(results_delta.list_table_paths()), + "tables": len(stored), + } + + # 7. save, load with the store, read back, load-only run. + saved = work / "job.json" + build(name, store(), n=7).save(saved) + loaded = PipelineJob.load(saved, database=store()) + read = { + k: loaded.nodes[k].as_source().as_table().num_rows + for k in ("combine", "select") + } + _ = loaded.run(load_only=True) + s["save and load"] = { + "store_flag_saved": '"store": true' in saved.read_text(), + "rows_read": read, + "ok": read == {"combine": 7, "select": 7}, + } + + # 8. a second writer is refused while another holds the lease. + _, release = take_lease( + SpiralDBConnector(project, dataset, store=True), "evaluation: another writer" + ) + fresh = f"itl1844_eval_{stamp}_refused" + try: + build(fresh, store(), n=6).run() + refused = False + except spiraldb_lease.LeaseBusyError: + refused = True + finally: + release() + s["second writer"] = { + "refused": refused, + "nothing_written": store().list_table_paths((fresh,)) == [], + } + + # Every store table this evaluation wrote, by name and layout. + every = sorted(store().list_table_paths()) + report["store_tables"] = [ + {"name": spiral_store_table_name(p), "layout": p[-1], "path": "/".join(p)} + for p in every + if p[0].startswith(f"itl1844_eval_{stamp}") + ] + report["ok"] = all(v.get("ok", True) for v in s.values()) and refused + return report + + +def lease_tables(project: str, dataset: str) -> list[dict[str, str]]: + """The dataset's lease generation tables (contiguous from 1), by name and id.""" + connector = SpiralDBConnector(project, dataset) + client = connector._client # pyright: ignore[reportPrivateUsage] # a listing for the report + found: list[dict[str, str]] = [] + generation = 1 + while True: + name = spiral_lease_table_name(generation) + table = open_keyed_table(client, project, dataset, name) + if table is None: + return found + found.append({"name": name, "id": str(table.resource_id)}) + generation += 1 + + +@contextlib.contextmanager +def fake_service(work: Path) -> Iterator[None]: + from tests.test_databases import fake_spiral_sdk as fake + + with fake.install(work / "fake"): + yield + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("mode", choices=["fake", "live"]) + parser.add_argument("--project", default="p") + parser.add_argument("--dataset", default="d") + args = parser.parse_args() + stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") + with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack: + work = Path(tmp) + if args.mode == "fake": + stack.enter_context(fake_service(work)) + before = {t["name"] for t in lease_tables(args.project, args.dataset)} + report = evaluate(args.project, args.dataset, stamp, work) + report["lease_tables_created"] = [ + t + for t in lease_tables(args.project, args.dataset) + if t["name"] not in before + ] + report["mode"] = args.mode + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 if report["ok"] else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 9ba71342d..4a0335757 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -61,7 +61,7 @@ The library value types (NumPy, pandas, Polars, torch) are The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB but does not write it for now (`SpiralDBWriteNotSupportedError`). See [The database](../concepts/pipeline-job.md#the-database) for how a +SpiralDB and writes it only as a job's store ([SpiralDB as a Job's Database](../concepts/spiraldb-store.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/site/astro.config.mjs b/site/astro.config.mjs index 13497cefd..d7b1b05b6 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -169,6 +169,7 @@ export default defineConfig({ page('Function Pods', 'concepts/function-pods'), page('Data-tags', 'concepts/data-tags'), page('Pipelines and Jobs', 'concepts/pipeline-job'), + page('SpiralDB as a Job\'s Database', 'concepts/spiraldb-store'), page('Provenance', 'concepts/provenance'), page('Working in Notebooks', 'concepts/notebooks'), page('Your Own Data Types', 'concepts/your-own-data-types'), diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 93ed6ae66..126e2bb48 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1108,7 +1108,7 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB but does not write it for now (`SpiralDBWriteNotSupportedError`). See [The database](../concepts/pipeline-job.md#the-database) for how a +SpiralDB and writes it only as a job's store ([SpiralDB as a Job's Database](../concepts/spiraldb-store.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: From fb61329a55d15ed047e546612506c73e49413836 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:34:17 -0800 Subject: [PATCH 22/50] fix(spiraldb): store mode review round 3: per-operation judgments, add-time context check, stored-names refusal (ITL-1840) - A name's judgment (no table, a table with no rows and what it recorded, a table with rows) is kept in the thread's operation only: the shared empty-table set and first-write observation map are gone. A table judged empty reads as no rows for the rest of the operation, and a first write compares the table with its own observation, never one another call made since. - Rows of another data context than those pending for the same table are refused when they are added, never buffered. - An append is refused when the table's manifest records other stored names than the codec's rule gives the rows, at any depth. - The stored-ids test passes both orders to existing_record_ids. - The stage B plan limits the no-overwrite guarantee to keys the flush's key scan sees, and explains the second name lookup at a flush. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 36 +++- .../databases/connector_arrow_database.py | 10 ++ .../databases/spiraldb_store_tables.py | 143 ++++++++++----- .../test_spiraldb_store_mode.py | 163 +++++++++++++++++- 4 files changed, 304 insertions(+), 48 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index cd317279f..cec476f89 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -70,26 +70,46 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. (every stored id found, under the service's own order) and the work on the service are to be validated live before it replaces the key-column read. - A flush reads the keys again, also for ids its add found absent (review round 2 - considered skipping it): until the one-writer lease (stage C, ITL-1452), another writer, - in this process or another, may store one of those ids between the add and the flush, - and an append would then replace its row. Once the lease makes this writer the only + considered skipping it): until the one-writer lease (ITL-1838, wired into every job run + by stage D, ITL-1844), another writer, in this process or another, may store one of + those ids between the add and the flush, and an append would then replace its row. Once the lease makes this writer the only one, the flush can rely on the add's check (ITL-1841). -- A flush never overwrites a stored row. A SpiralDB append replaces a row of the same key, - so the store writes only the keys the table does not hold (the same key-column read): a - key another writer stored after this one's add keeps its first commit, as with every - other connector. +- A flush never overwrites a row its key scan sees. A SpiralDB append replaces a row of the + same key, so the store writes only the keys the table does not hold in the snapshot the + flush reads its keys from (the same key-column read): a key another writer stored after + this one's add, and before that scan, keeps its first commit, as with every other + connector. A key another writer commits between that scan and the append is not seen, + and the pending row then replaces it: SpiralDB has no insert-if-absent. Nothing in this + stage closes that window; the one-writer lease (ITL-1838) and stage D, which takes it in + every job run and refuses store writes outside one (ITL-1844), do. - Storage metadata must match on append: the stored schema (the manifest's, logical types live) is held as for any connector that keeps field metadata (`_refuse_changed_columns`), and the store compares the rows with the manifest again when it writes. +- An append is refused when the table's manifest records other stored names than the + codec's rule gives the rows (at any depth): the reader reads the names the manifest + records, so columns written under other names could not be read back. Only a manifest + this writer did not make (another writer, or a later naming rule) records other names. +- Rows of another data context than those pending for the same table are refused when + they are added, never buffered, as the write refuses a batch of two contexts. ## Finding a table, and what is kept - A table's name is opened once per public operation of `ConnectorArrowDatabase` (an add, a flush, a read, a schema or listing call; `StoreTables.operation`), and that handle - reused within it until the store writes to the table (review round 2). The next + reused within it until the store writes to the table (review round 2). A flush of a table + that holds rows opens the name twice: the caller's schema check reads through the + operation's handle, and the write then looks the name up again and reads the keys from + that new snapshot. The second lookup is needed because the check is the caller's code + (run outside the operation): it, or another writer meanwhile, can rename or replace the + table or commit a key, and a write through the earlier handle would then append to the + wrong table or replace that key's row. The next operation opens it again: a table can be renamed and another made under its name, so nothing is read or written through an earlier operation's answer. What a table that holds rows records (key, identity record, manifest) is kept by its table id. +- What a name was judged (no table; a table with no rows, with what it recorded; a table + with rows) is kept in the thread's operation only. No other call can change it: a table + judged empty reads as no rows for the rest of the operation, and a first write compares + the table with what its own judgment saw. - What a first write records is kept only once its append succeeded. A failed append (also one the service stored before the error reached the client) forgets it, and the next call judges the table again. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 0e40544af..06a14c1f4 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -819,6 +819,16 @@ def add_records( self._connector.validate_records(records) record_key = self._get_record_key(record_path) + if store is not None: + # One data context per store table, as its write requires: rows of another + # one than those pending for the table are refused here, never buffered. + pending = self._pending_batches.get(record_key) + if pending is not None: + from orcapod.contexts.stored import require_same_data_context + + require_same_data_context( + store.data_context(records), store.data_context(pending) + ) committed_table = None pending_owner_key: tuple[str, str] | None = None if self._sql_store is not None: diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 13038fcc8..d8d69af35 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -137,6 +137,28 @@ class _Opened: table: _KeyedTable +_Seen = tuple[str, object] +"""What a table recorded when judged: ``("none", None)``, ``("manifest", manifest)``, or +``("unreadable", header bytes)`` for a manifest that cannot be decoded (never equal to +anything: ``_same_seen``).""" + + +@dataclass(frozen=True) +class _New: + """A store table found under its name with no rows yet: new to any first writer. + + Attributes: + seen: What it recorded when it was judged (``_seen_manifest``): its first write + records it only as it was then. + """ + + seen: _Seen + + +_Judgment = _Opened | _New | None +"""What a name was judged: a table with rows, a table with none, or no table.""" + + class StoreTables: """The store tables of one SpiralDB dataset. @@ -173,14 +195,11 @@ def __init__( # on every call (a table can be renamed, and another made under its name). self._found_by_id: dict[str, _Found] = {} self._records_by_id: dict[str, identity.StoreTableRecord] = {} - # What each table recorded when it was last judged new (``_seen_manifest``): a - # first write may record a table only as it was then. - self._judged: dict[str, _Seen] = {} - # Tables last judged to exist with no rows: new to a writer, and read as no rows. - self._empty: set[str] = set() # Within one public operation (``operation``): what each name was judged, its # name opened once and its handle reused. Empty outside an operation. - # Kept per thread: an operation is one thread's call. + # Kept per thread: an operation is one thread's call, and no other operation + # can change what this one judged (a table with no rows stays one, and what it + # recorded stays what its first write compares with). self._now: threading.local = threading.local() key_column: str = codec.KEY_COLUMN @@ -343,11 +362,9 @@ def outside_operation(self) -> Iterator[None]: self._now.depth = depth self._now.judged = None if judged is None else {} - def _judged_now(self) -> dict[str, _Opened | None] | None: + def _judged_now(self) -> dict[str, _Judgment] | None: """What each name was judged in this thread's operation; ``None`` outside one.""" - return cast( - "dict[str, _Opened | None] | None", getattr(self._now, "judged", None) - ) + return cast("dict[str, _Judgment] | None", getattr(self._now, "judged", None)) def _forget_opened(self, table_name: str) -> None: """Forget a name's handle in the current operation: this store writes to it.""" @@ -360,7 +377,20 @@ def _forget_opened(self, table_name: str) -> None: def _judge(self, table_name: str) -> _Opened | None: """Return the table under a name now if it holds rows of this path; ``None`` if it is absent or new: no rows yet, with or without a record (spec 2.5: any first - writer records it again). + writer records it again). ``_judgment`` tells the two apart. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The table and what it records, or ``None``. + """ + judgment = self._judgment(table_name) + return judgment if isinstance(judgment, _Opened) else None + + def _judgment(self, table_name: str) -> _Judgment: + """What the name holds now: a table with rows of this path, a table with none + (``_New``, with what it recorded), or no table (``None``). The name is opened once per public operation (``operation``; on every call outside one), so a table renamed away, or replaced by another under the name, is @@ -371,7 +401,7 @@ def _judge(self, table_name: str) -> _Opened | None: table_name: A name ``table_name`` returned. Returns: - The table and what it records, or ``None``. + The judgment. Raises: SpiralStoreTableCollisionError: If the table's key is not the store's, it @@ -381,29 +411,26 @@ def _judge(self, table_name: str) -> _Opened | None: if judged is not None and table_name in judged: return judged[table_name] with self._about(table_name): - opened = self._judge_table(table_name, self._path_of(table_name)) + judgment = self._judge_table(table_name, self._path_of(table_name)) if judged is not None: - judged[table_name] = opened - return opened + judged[table_name] = judgment + return judgment - def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Opened | None: - """``_judge`` without naming the table on a refusal. + def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: + """``_judgment`` without naming the table on a refusal. Args: table_name: A name ``table_name`` returned. path: The full record path it was computed from. Returns: - The table and what it records, or ``None``. + The judgment. """ table = self._open_table(table_name) if table is None: - self._judged[table_name] = ("none", None) - self._empty.discard(table_name) return None known = self._found_by_id.get(str(table.resource_id)) if known is not None and known.record.path == path: - self._empty.discard(table_name) return _Opened(known, table) _require_key(table, self._service_call) with self._service_call("read the metadata of a store table"): @@ -413,9 +440,7 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Opened | None identity.require_store_table_path(record, path) if not _holds_rows(table, self._service_call): # New: its first write records it, unless what it saw here changed. - self._judged[table_name] = _seen_manifest(metadata, path) - self._empty.add(table_name) - return None + return _New(_seen_manifest(metadata, path)) try: manifest = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: @@ -424,7 +449,6 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Opened | None raise SpiralStoreTableCollisionError("it holds rows but no store manifest") found = _Found(str(table.resource_id), record, manifest) self._found_by_id[found.table_id] = found - self._empty.discard(table_name) return _Opened(found, table) def has_table(self, table_name: str) -> bool: @@ -558,11 +582,11 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: Raises: KeyError: If there is no table at the name. """ - opened = self._judge(table_name) + opened = self._judgment(table_name) if opened is None: - if table_name in self._empty: - return # it exists, with no rows raise KeyError(f"no store table {self._qualified(table_name)}") + if isinstance(opened, _New): + return # it exists, with no rows found = opened.found schema = _live(found.manifest.schema, found.record.data_context_key) with self._about(table_name), self._service_call("read a store table"): @@ -748,10 +772,13 @@ def write(self, table_name: str, records: pa.Table) -> None: # and another writer may have stored a key, or the table may have been renamed # away and another made under its name. The keys are read from this snapshot. self._forget_opened(table_name) - opened = self._judge(table_name) + opened = self._judgment(table_name) with self._about(table_name): - if opened is None: - self._write_first(table_name, path, context, records) + if not isinstance(opened, _Opened): + # Compared with what this write's own judgment saw, never with what + # another call judged since. + seen = opened.seen if isinstance(opened, _New) else ("none", None) + self._write_first(table_name, path, context, records, seen) return found = opened.found _require_data_context(found, context) @@ -761,6 +788,15 @@ def write(self, table_name: str, records: pa.Table) -> None: f"the rows are not of the table's schema ({difference}): " + "schema evolution is not supported" ) + difference = _stored_names_difference(found.manifest, records.schema) + if difference is not None: + # The codec writes the stored names its rule gives; the reader reads + # those the manifest records. Rows written under other names could not + # be read back, so they are never written. + raise ValueError( + f"the table stores its columns under other names ({difference}): " + + "an append would write columns its manifest does not record" + ) # The keys are read again at every write, also for ids the add found # absent: until the one-writer lease (ITL-1452), another writer may have # stored one since, and an append would replace its row. @@ -777,6 +813,7 @@ def _write_first( path: tuple[str, ...], context: str, records: pa.Table, + seen: _Seen, ) -> None: """The first write of a table judged absent or new (``write``). @@ -785,6 +822,8 @@ def _write_first( path: The full record path it was computed from. context: The rows' data context. records: The rows, record id column included. + seen: What the table recorded when this write judged it + (``_seen_manifest``; ``("none", None)`` when it was absent). """ manifest = codec.new_manifest(path, path[-1], records.schema) metadata = { @@ -794,7 +833,6 @@ def _write_first( encoded = _encoded(records) if encoded.num_rows == 0: return # nothing to write, so nothing is created - seen = self._judged.pop(table_name, ("none", None)) self._forget_opened(table_name) table = self._create_or_open(table_name) _require_key(table, self._service_call) @@ -812,7 +850,6 @@ def _write_first( # Another writer may have written these keys meanwhile. held = self._held_ids(table, _ids(records)) encoded = _encoded(_without_ids(records, held)) - self._empty.discard(table_name) if encoded.num_rows > 0: self._append(table, recorded, encoded) @@ -834,6 +871,40 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: self._found_by_id[found.table_id] = found +def _stored_names_difference( + manifest: codec.StoreManifest, schema: pa.Schema +) -> str | None: + """Where the stored names ``codec.encode_rows`` gives rows of ``schema`` differ from + those ``manifest`` records, at any depth; ``None`` when they are the same. + + Columns are matched by logical name (their order never counts). A manifest records + the stored names it was written with, and the reader reads those; the codec always + applies its current rule. + + Args: + manifest: The table's manifest. + schema: The schema of rows to append, of the manifest's logical schema. + """ + written = dict( + zip(codec.logical_schema(schema).names, codec.physical_schema(schema)) + ) + for logical, recorded in zip(manifest.schema, manifest.physical): + field = written.get(logical.name) + if field is not None and _names_of(field) != _names_of(recorded): + return f"column {logical.name!r} is stored as {recorded}, not as {field}" + return None + + +def _names_of(field: pa.Field[Any]) -> tuple[object, ...]: + """A field's name and the names of its child fields, at every depth.""" + arrow_type = cast(Any, field.type) # pyright: ignore[reportExplicitAny] + children = [ + _names_of(cast("pa.Field[Any]", arrow_type.field(i))) + for i in range(cast(int, arrow_type.num_fields)) + ] + return (field.name, tuple(children)) + + def _require_key( table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] ) -> None: @@ -1062,12 +1133,6 @@ def _by_name(schema: pa.Schema) -> dict[str, pa.Field[Any]]: return {field.name: field for field in schema} -_Seen = tuple[str, object] -"""What a table recorded when judged: ``("none", None)``, ``("manifest", manifest)``, or -``("unreadable", header bytes)`` for a manifest that cannot be decoded (never equal to -anything: ``_same_seen``).""" - - def _seen_manifest(metadata: Mapping[str, bytes], path: tuple[str, ...]) -> _Seen: """What a table's metadata records, to compare later (``_same_seen``).""" try: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index d9272ce0d..0327df43a 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -278,7 +278,7 @@ def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> N name = tables.table_name(RESULT) fake.scan_log.clear() fake.count_log.clear() - held = tables.existing_record_ids(name, set(asked)) + held = tables.existing_record_ids(name, asked) scans = [*fake.scan_log, *fake.count_log] assert held == set(asked) & {b"r0", b"r1", b"r2", b"r3"} keyed = [s for s in scans if s.limit is None] @@ -1682,3 +1682,164 @@ def read_after_replacing(_schema: pa.Schema) -> None: db.flush() with pytest.raises(SpiralStoreTableCollisionError): _ = _get(db) + + +# ------------------------------------------------- review of 6fb1b6e16 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_alternate", [False, True]) +def test_rows_of_another_data_context_than_the_pending_ones_are_refused_at_add( + monkeypatch: pytest.MonkeyPatch, first_alternate: bool +) -> None: + """Two data contexts this Orcapod resolves: rows of one buffered for a table, rows + of the other are refused when they are added, never buffered, and the flush + writes the first rows only (it used to fail at the flush, keeping both).""" + from dataclasses import replace + + from orcapod import contexts + + alternate_key = "std:v9:alternate" + alternate = replace(contexts.get_default_context(), context_key=alternate_key) + resolve = contexts.resolve_context + monkeypatch.setattr( + contexts, + "resolve_context", + lambda key=None: alternate if key == alternate_key else resolve(key), # pyright: ignore[reportUnknownLambdaType] + ) + first, second = CONTEXT, alternate_key + if first_alternate: + first, second = second, first + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"], context=first)) + with pytest.raises(InputValidationError) as raised: + _add(db, rows(["r2"], context=second, offset=2)) + assert first in str(raised.value) and second in str(raised.value) + db.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None + assert sorted(_record_ids(got)) == [b"r0", b"r1"] + assert set(got.column("__data_context").to_pylist()) == {first} + + +@pytest.mark.usefixtures("root") +def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: + """A manifest records the stored names a table was written with, and the reader + reads those; the codec writes the names its rule gives. An append to a table + whose manifest records other names (another writer, or another rule) is refused + before anything is written: it used to write columns the manifest does not + record, and the next read failed.""" + written = rows(["r0"]) + ConnectorArrowDatabase(store()).add_records( + RESULT, written, record_id_column="__record_id", flush=True + ) + current = codec.new_manifest(RESULT, "rdb_v1", written.schema) + renamed = pa.schema( + [ + f.with_name(f"{f.name}_v0") if logical.name == "s" else f + for logical, f in zip(current.schema, current.physical) + ] + ) + other = codec.StoreManifest(RESULT, current.kind, current.schema, renamed) + name = identity.spiral_store_table_name(RESULT) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(other), + } + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="other names") as raised: + _add(db, rows(["r1", "r2"], offset=1), flush=True) + assert "'s'" in str(raised.value) + stored = _table(name).scan().to_table() + assert stored.column("__record_id").to_pylist() == [b"r0"] + assert "s_v0" not in stored.column_names + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_judged_in_an_operation_stays_empty_after_another_writes() -> ( + None +): + """What a table was judged is kept by the operation that judged it: a table + judged empty is read as no rows in that operation even after another thread's + first write fills it (it used to raise ``KeyError``, as for no table).""" + import threading + + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) + failures: list[BaseException] = [] + + def write_elsewhere() -> None: + try: + ConnectorArrowDatabase(connector).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + except BaseException as exc: # noqa: BLE001 # reported by the test + failures.append(exc) + + with tables.operation(): + assert not tables.has_table(name) + writer = threading.Thread(target=write_elsewhere) + writer.start() + writer.join() + assert failures == [] + assert list(tables.scan(name)) == [] + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and _record_ids(got) == [b"r0"] + + +@pytest.mark.usefixtures("root") +def test_a_first_writer_compares_the_table_with_its_own_observation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A first write compares the table with what its own judgment saw, never with + what another call judged since: another writer records the empty table with + another manifest and a second thread then judges it; the first write refuses it + and keeps that manifest (it used to take the second thread's judgment as its own + and record over it).""" + import threading + + first_seen = rows(["x"]).drop_columns(["s"]) + _make_table( + identity.spiral_store_table_name(RESULT), + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries( + codec.new_manifest(RESULT, "rdb_v1", first_seen.schema) + ), + }, + with_rows=False, + ) + peers = rows(["x"]).drop_columns(["a.b"]) + peers_manifest = codec.new_manifest(RESULT, "rdb_v1", peers.schema) + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + new_manifest = codec.new_manifest + interfered: list[bool] = [] + + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + if not interfered: + interfered.append(True) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(peers_manifest), + } + ) + judge = threading.Thread(target=lambda: tables.has_table(name)) + judge.start() + judge.join() + return new_manifest(*args, **kwargs) + + monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) + with tables.operation(): + with pytest.raises(SpiralStoreTableCollisionError): + tables.write(name, rows(["a0"])) + assert interfered == [True] + kept = codec.read_manifest(_table(name).get_metadata(), RESULT) + assert kept is not None and kept.schema.equals(peers_manifest.schema) + assert _table(name).scan().to_table().num_rows == 0 From 406c8066451a59f7763cfe1b34d5e5ad145439bd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:47:54 -0800 Subject: [PATCH 23/50] fix(pipeline): issue the run-completion warnings from run() and run_async() themselves (ITL-1844) The leases are held in a helper frame; the warnings still point at the caller's line. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/job.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index dff112297..a487d2605 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1385,7 +1385,7 @@ def run( # The writer leases of the SpiralDB stores the run writes are held from the # source check to the end of the run (ITL-1844). with contextlib.ExitStack() as leases: - return self._run_holding( + summary = self._run_holding( leases, orchestrator, observer, @@ -1393,6 +1393,10 @@ def run( commit_every_rows, load_only=load_only, ) + # Warned from here: the warnings point at the caller's line. + if not summary.ok or summary.lost_observer_events: + _warn_run_completion(summary) + return summary def _run_holding( self, @@ -1451,8 +1455,6 @@ def _run_holding( asynchronous=not is_sync, lost_observer_events=losses.by_kind(), ) - if not summary.ok or summary.lost_observer_events: - _warn_run_completion(summary) return summary async def run_async( @@ -1506,7 +1508,7 @@ async def run_async( ) # The writer leases of the SpiralDB stores the run writes (ITL-1844). with contextlib.ExitStack() as leases: - return await self._run_async_holding( + summary = await self._run_async_holding( leases, orchestrator, observer, @@ -1514,6 +1516,10 @@ async def run_async( commit_every_rows, load_only=load_only, ) + # Warned from here: the warnings point at the caller's line. + if not summary.ok or summary.lost_observer_events: + _warn_run_completion(summary) + return summary async def _run_async_holding( self, @@ -1553,8 +1559,6 @@ async def _run_async_holding( asynchronous=True, lost_observer_events=losses.by_kind(), ) - if not summary.ok or summary.lost_observer_events: - _warn_run_completion(summary) return summary def _prepare_run( From 537d66ff636ffc15f77e21bfe860cbf8a38b707d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:48:12 -0800 Subject: [PATCH 24/50] build(deps): pin spiral-sdk 0.16.80; ignore its keyed-table deprecation for Orcapod's opens only (ITL-1837) - Pin spiral-sdk 0.16.80 (was 0.16.78), the newest release. - spiral-sdk 0.16.79 and later warn on every keyed-table open, attributed to the calling module. One helper in spiraldb_connector, the only Orcapod module that opens keyed tables, installs before each open (if missing) an ignore filter for that exact message, DeprecationWarning, and that module only. A direct SDK call still warns. The move off keyed tables is ITL-1846. - Measured live on 0.16.80: a duration column is accepted and read back as given (0.16.78 refused it). The fake follows 0.16.80, the refusal test drops durations, and a live check reads the duration back. The store codec still refuses durations (ITL-1852). - Tests: Orcapod's opens raise no warning with every warning an error; a direct SDK open from a test still warns (real SDK client over a stub native client). Co-Authored-By: Claude Opus 5.5 --- RELEASING.md | 9 +- changelog.d/ITL-1837.md | 8 +- ...026-12-01-itl-1837-spiral-store-stage-a.md | 57 +++++++--- pyproject.toml | 2 +- src/orcapod/databases/spiral_store.py | 4 +- src/orcapod/databases/spiraldb_connector.py | 37 +++++++ tests/test_databases/fake_spiral_sdk.py | 8 +- .../test_spiraldb_connector_integration.py | 11 +- .../test_spiraldb_keyed_table_deprecation.py | 104 ++++++++++++++++++ uv.lock | 12 +- 10 files changed, 219 insertions(+), 33 deletions(-) create mode 100644 tests/test_databases/test_spiraldb_keyed_table_deprecation.py diff --git a/RELEASING.md b/RELEASING.md index c66d0de9d..db3c95d4a 100644 --- a/RELEASING.md +++ b/RELEASING.md @@ -342,6 +342,11 @@ releases daily, of which Orcapod uses two attributes that are not public API To move the pin: change it there, run `uv lock`, and run the conformance tests live (`tests/test_databases/test_spiraldb_connector_integration.py`, see its docstring). A refusal or a value that changed is a change of `tests/test_databases/fake_spiral_sdk.py` (its `RULES`) first. +From 0.16.79 spiral-sdk warns on every keyed-table open; Orcapod's connector ignores that one +message for its own opens (`spiraldb_connector._ignore_keyed_table_deprecation`), and +`tests/test_databases/test_spiraldb_keyed_table_deprecation.py` fails if a new release changes +the message, the category or the module it is attributed to. The move off keyed tables is +ITL-1846. ### Migrating a SpiralDB dataset from pyspiral @@ -358,12 +363,12 @@ uv run --no-project --isolated --python 3.12 \ uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.80 scripts/migrate_spiral_schemas.py \ write --project --dataset --plan plan.json --digest uv run --no-project --isolated --python 3.12 \ --with "orcapod[spiraldb] @ git+https://github.com/metamorphic-labs/orcapod-python@" \ - --with spiral-sdk==0.16.78 scripts/migrate_spiral_schemas.py \ + --with spiral-sdk==0.16.80 scripts/migrate_spiral_schemas.py \ verify --project --dataset --plan plan.json ``` diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md index 0079b1198..4fa7f484e 100644 --- a/changelog.d/ITL-1837.md +++ b/changelog.d/ITL-1837.md @@ -1,8 +1,10 @@ ### Changed -- The `spiraldb` extra pins `spiral-sdk==0.16.78` (was `0.16.74`), a release that reads - and writes a SpiralDB table's own metadata (the one it was measured with). 0.16.79 is not used: it deprecates the keyed - tables Orcapod reads, with a warning on every open. Orcapod still only reads SpiralDB. +- The `spiraldb` extra pins `spiral-sdk==0.16.80` (was `0.16.74`), a release that reads + and writes a SpiralDB table's own metadata. spiral-sdk 0.16.79 and later mark the keyed + tables Orcapod reads as deprecated and warn on every open; Orcapod ignores that one + warning for its own opens only, so a direct call to spiral-sdk still warns. The move to + spiral-sdk's newer table format is ITL-1846. Orcapod still only reads SpiralDB. (ITL-1837) ### Known limitations diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md index b94966b44..247ab8097 100644 --- a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -17,25 +17,52 @@ so: the identity record's format is `orcapod.spiral_store.draft` version 0 (`spiral_store.MANIFEST_FORMAT`). When the format is fixed it gets a new marker, and what to do with draft tables is decided then. No golden value pins any of it. -## 1. spiral-sdk 0.16.78 +## 1. spiral-sdk 0.16.80 Table metadata arrives in two steps: `KeyedTable.get_metadata` first appears in 0.16.76, -and `set_metadata` in 0.16.77 (neither is in 0.16.74 or 0.16.75). The Python files of -0.16.77 and 0.16.78 are identical; only their native libraries differ. 0.16.78 is kept -because it is the release the table metadata, the type rules and the entry limits were -measured with (live, 2026-11-26), and it is the last release before the keyed-table -deprecation of 0.16.79. Compared with `main`'s 0.16.74, the Python layer of 0.16.78 changes -only those two methods (and the generated service schemas); the snapshot pinning -(`keyed_table_by_id(..., asof=)`), projection (`scan(columns=)`) and key ranges `main` uses -are untouched there. - -0.16.79 (2026-11-27) is newer but not chosen: it marks keyed tables deprecated, and -`Client.keyed_table`, `keyed_table_by_id` and `Project.create_keyed_table` each issue a -`DeprecationWarning`. Every SpiralDB path of Orcapod (the source, the connector, the store) -is on keyed tables. Its other change is a description of the ingest writer's lifetime. +and `set_metadata` in 0.16.77 (neither is in 0.16.74 or 0.16.75). The table metadata, the +type rules and the entry limits were measured live with 0.16.78 (2026-11-26). Compared with +`main`'s 0.16.74, the Python layer changes only those two methods (and the generated service +schemas); the snapshot pinning (`keyed_table_by_id(..., asof=)`), projection +(`scan(columns=)`) and key ranges `main` uses are untouched. + +The pin is 0.16.80 (2026-12-01), the newest release, at the developer's request: the newest +SDK, provided the keyed-table deprecation can be silenced in a targeted way. 0.16.79 marks +keyed tables deprecated: `Client.keyed_table`, `keyed_table_by_id` and +`Project.create_keyed_table` each call `warn("Keyed tables are deprecated.", +DeprecationWarning, stacklevel=3)`, so the warning is attributed to the module that calls +the SDK. 0.16.80 changes nothing else Orcapod uses (it removes the duration types, which +the store already refuses). Orcapod's only module that opens keyed tables is +`orcapod.databases.spiraldb_connector`; before each open it installs, if missing, one +filter: action `ignore`, that exact message, `DeprecationWarning`, and that module only +(`_ignore_keyed_table_deprecation`). A user's own call to the SDK, another message and +another category still warn. It is installed before each open, not once at import, +because a `warnings.catch_warnings` block (pytest wraps every test in one) drops a filter +added inside it, and it uses no `catch_warnings` itself, which is not safe with threads. +`tests/test_databases/test_spiraldb_keyed_table_deprecation.py` checks both sides with the +real SDK client over a stub native client. + +The live conformance run on 0.16.80 (2026-12-01, as the agent workload, in the +conformance dataset of the test project) found one measured rule change: a keyed-table +write of a `duration[s]` column, which 0.16.78 refused, is accepted and read back with the +same unit and value (the same case run again with 0.16.78 is still refused, so the change +comes with the SDK, not the service). The fake follows 0.16.80 (rule `unsupported`), the +refusal test no longer lists durations, and +`test_a_duration_is_stored_and_read_back_as_given` checks the read-back. The store codec +still refuses durations: whether it stores them is ITL-1852. `main`'s CI keeps the 0.16.78 +rules until this pin merges. Side effect of the run: the existing fixed table +`store_codec_refusals` got a new version at 2026-12-01 23:41:50 UTC with a new column +`d: duration[s]` and one row (`k = "r0"`, one second), and the read-back check wrote that +same row again at 23:44:22 UTC. No table was created. A SpiralDB source over a duration +column reads it as any source does: the Arrow type is kept and the Python type is `Any`; +no test pins it. + +Keyed tables are on their way out; their replacement (Tables, with branches and commits) +has no primary key and no table metadata. The move is ITL-1846. The conformance tests ran +live on 0.16.80 before the pin moved. The bump is a dependency change for the developer to approve; it is one commit of its own -(`pyproject.toml`, `uv.lock`, `RELEASING.md`). +(`pyproject.toml`, `uv.lock`, `RELEASING.md`, the filter and its tests). ## 2. The fake's table metadata diff --git a/pyproject.toml b/pyproject.toml index fbb692496..6a22699a9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,7 +47,7 @@ postgresql = ["psycopg[binary]>=3.1.17"] spiraldb = [ # Exact: a pre-alpha that releases daily, and Orcapod reads two attributes that are # not its public API (ITL-1186). How to move it: RELEASING.md. - "spiral-sdk==0.16.78", + "spiral-sdk==0.16.80", ] # Convenience extra that installs PyTorch. Orcapod's torch.Tensor support depends only on # torch being importable, however it was installed (ITL-871). 2.6 is the first version whose diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_store.py index 84e35630a..100d0bbab 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_store.py @@ -191,7 +191,9 @@ def error(self) -> UnstorableInSpiralError: 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), + # spiral-sdk 0.16.80 accepts a duration column (0.16.78 refused it); whether the + # store keeps durations is decided apart (ITL-1852). + Refusal("a duration", "its encoding is not decided (ITL-1852)", _types.is_duration), Refusal("an interval", _REFUSED_LIVE, _types.is_interval), ) """Every refusal that new evidence or a decision may lift. A type that is in neither this diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 61e695bd9..402d43edc 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -167,6 +167,41 @@ def _service_call(doing: str, health: _Health | None = None) -> Iterator[None]: raise +# spiral-sdk 0.16.79 and later warn on every keyed-table open, attributed to the module +# that calls the SDK (``stacklevel=3``): this one, for every open Orcapod makes. Orcapod +# reads and writes keyed tables until it moves to spiral-sdk's Table format (ITL-1846), so +# this one message is ignored for this module's own opens only: a user's own call to the +# SDK, another message, and another category still warn. +_KEYED_TABLE_DEPRECATION = r"Keyed tables are deprecated\.\Z" +_THIS_MODULE = re.escape(__name__) + r"\Z" +# The filter as ``warnings.filterwarnings`` stores it, to find it in ``warnings.filters``. +_KEYED_TABLE_FILTER = ( + "ignore", + re.compile(_KEYED_TABLE_DEPRECATION, re.IGNORECASE), + DeprecationWarning, + re.compile(_THIS_MODULE), + 0, +) + + +def _ignore_keyed_table_deprecation() -> None: + """Ignore spiral-sdk's keyed-table deprecation for this module's own opens. + + Called before each open, not once at import: a ``warnings.catch_warnings`` block + (pytest wraps every test in one) drops a filter added inside it. Added only when it + is missing, so the filter list does not change in steady state. No + ``catch_warnings`` here: it swaps the process-wide filter list and is not safe with + threads. + """ + if _KEYED_TABLE_FILTER not in warnings.filters: + warnings.filterwarnings( + "ignore", + message=_KEYED_TABLE_DEPRECATION, + category=DeprecationWarning, + module=_THIS_MODULE, + ) + + def _open_keyed_table( client: Any, project_id: str, @@ -182,6 +217,7 @@ def _open_keyed_table( """ with _service_call(f"open table {project_id}/{dataset}/{name}", health): try: + _ignore_keyed_table_deprecation() return client.keyed_table(project_id, dataset, name) except sp.SpiralError as exc: if str(exc).strip() != f"resource not found: {project_id}.{dataset}.{name}": @@ -658,6 +694,7 @@ def _at(self, asof: int | None) -> Any: opened = self._versions.get(str(asof)) if opened is None: with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle + _ignore_keyed_table_deprecation() opened = self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle self.table_id, asof=asof ) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index ec79e2acd..72b0c9f9c 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -69,8 +69,9 @@ "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", + "unsupported": "interval, fixed-size binary, union, an empty struct and a null " + "struct outside a list are refused; a duration is accepted and read back as given " + "(spiral-sdk 0.16.80, December 1, 2026: a duration[s] column, which 0.16.78 refused)", "non-null": "a null in a column, struct field or list item declared or stored " "non-null is refused", "literal": "a literal must have the column's exact type (large_string is none)", @@ -193,8 +194,7 @@ def _refused_type(t: pa.DataType) -> str | None: if isinstance(t, pa.BaseExtensionType): return _refused_type(t.storage_type) if ( - pa.types.is_duration(t) - or pa.types.is_interval(t) + pa.types.is_interval(t) or pa.types.is_fixed_size_binary(t) or pa.types.is_union(t) ): diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 12c9a773b..010316e3d 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -683,7 +683,6 @@ def test_the_store_codec_round_trips(place: _Place) -> None: 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([]))}), ], @@ -708,6 +707,16 @@ def test_what_the_store_codec_avoids_is_refused( assert again.version_id == table.version_id +def test_a_duration_is_stored_and_read_back_as_given(place: _Place) -> None: + """A duration column is accepted from spiral-sdk 0.16.80 and read back with its unit + and value (the fake's ``unsupported``; 0.16.78 refused it). Written to the table of + the refusals above, which already holds this column and row: no new table.""" + column = pa.table({"d": pa.array([1], pa.duration("s"))}) + got = _written_and_read(place, "store_codec_refusals", column) + assert got.schema.field("d").type == pa.duration("s") + assert got.column("d").to_pylist() == [dt.timedelta(seconds=1)] + + def _written_and_read(place: _Place, name: str, column: pa.Table) -> pa.Table: """Write ``column`` under keys r0... to a fixed table and read those rows back.""" client = _client(place) diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py new file mode 100644 index 000000000..77bfadade --- /dev/null +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -0,0 +1,104 @@ +"""spiral-sdk's keyed-table deprecation is ignored for Orcapod's own opens only (ITL-1837). + +spiral-sdk 0.16.79 and later warn on every keyed-table open, attributed to the module that +calls the SDK. These tests use the real spiral-sdk client, its native client replaced by a +stub, so the warning is the SDK's own and no service is called. +""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator +from typing import Any +from unittest.mock import patch + +import pytest + +sp = pytest.importorskip("spiral") + +from orcapod.databases import spiraldb_connector # noqa: E402 # after the skip +from orcapod.databases.spiraldb_connector import ( # noqa: E402 # after the skip + SpiralDBConnector, + SpiralDBTableNotFoundError, +) + +MESSAGE = r"Keyed tables are deprecated\." + + +class _NativeTable: + """What the SDK's keyed table handle reads from its native table.""" + + resource_id = "tbl_1" + version_id = "1" + key_columns = ("k",) + + +class _NativeClient: + """A native client that answers an open of table ``t`` and nothing else.""" + + def keyed_table( + self, project: str, dataset: str, name: str, *, asof: int | None = None + ) -> _NativeTable: + """Open ``t``; any other name is not found, in the service's words.""" + if name == "t": + return _NativeTable() + raise sp.SpiralError(f"resource not found: {project}.{dataset}.{name}") + + def keyed_table_by_id(self, table_id: str, *, asof: int | None = None) -> Any: + """Refuse every version: the tests stop at the open.""" + raise sp.SpiralError(f"no version {asof} of {table_id}") + + +class _Client(sp.Client): + """spiral-sdk's client with the stub native client: its own methods run.""" + + def __init__(self, **_: Any) -> None: # pyright: ignore[reportMissingSuperCall] # the SDK's would sign in + """Hold the stub; sign in nowhere.""" + self._native = _NativeClient() + + +class _SDK: + """The ``spiral`` module as the connector sees it, with the stubbed client.""" + + Client = _Client + SpiralError = sp.SpiralError + + +@pytest.fixture +def connector() -> Iterator[SpiralDBConnector]: + """A connector on the real spiral-sdk client over the stub native client.""" + with ( + patch.object(spiraldb_connector, "sp", _SDK), + patch.object(spiraldb_connector, "require_sign_in", lambda: None), + ): + made = SpiralDBConnector("p", "d") + yield made + made.close() + + +def test_orcapod_opens_keyed_tables_with_no_deprecation_warning( + connector: SpiralDBConnector, +) -> None: + """With every warning an error, Orcapod's opens of a table (by name, found and not + found) and of a version (by id) raise what the stub raises, never the deprecation.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + with pytest.raises(SpiralDBTableNotFoundError): + _ = connector.lookup_table("missing") + table = connector.lookup_table("t") + assert table.table_id == "tbl_1" + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + + +def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: + """The filter Orcapod installs covers its own module only: an open called from + another module (this test), by name or by id, still warns, after Orcapod's open.""" + client = _Client() + with warnings.catch_warnings(): + warnings.simplefilter("error") + _ = connector.lookup_table("t") # installs Orcapod's filter + with pytest.raises(DeprecationWarning, match=MESSAGE): + _ = client.keyed_table("p", "d", "t") + with pytest.raises(DeprecationWarning, match=MESSAGE): + _ = client.keyed_table_by_id("tbl_1", asof=1) diff --git a/uv.lock b/uv.lock index b1579fcc0..f69cfb20b 100644 --- a/uv.lock +++ b/uv.lock @@ -1960,8 +1960,8 @@ requires-dist = [ { name = "redis", marker = "extra == 'all'", specifier = ">=6.2.0" }, { name = "redis", marker = "extra == 'redis'", specifier = ">=6.2.0" }, { name = "s3fs", specifier = ">=2025.12.0" }, - { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.78" }, - { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.78" }, + { name = "spiral-sdk", marker = "extra == 'all'", specifier = "==0.16.80" }, + { name = "spiral-sdk", marker = "extra == 'spiraldb'", specifier = "==0.16.80" }, { name = "starfix", specifier = ">=0.6.0,<0.7" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'all'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, { name = "torch", marker = "sys_platform == 'linux' and extra == 'torch'", specifier = ">=2.6", index = "https://download.pytorch.org/whl/cpu" }, @@ -3292,16 +3292,16 @@ wheels = [ [[package]] name = "spiral-sdk" -version = "0.16.78" +version = "0.16.80" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "opentelemetry-api" }, { name = "pyarrow" }, ] wheels = [ - { 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" }, + { url = "https://files.pythonhosted.org/packages/37/68/bd93a203ee7f396392793f80e39171d06bc76795a0b8d6a7e0c14b2df1b0/spiral_sdk-0.16.80-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:c95b6904c52fea12f490c86bb304faa7d094e2c4799bf8727658064b32c5f99e", size = 81700548, upload-time = "2026-12-01T19:57:09.62Z" }, + { url = "https://files.pythonhosted.org/packages/4f/e9/fc70c16a510718d9291d4f5488b04906e66af201a169cfe282d7394374f9/spiral_sdk-0.16.80-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:0e68cea27f8adecce96bde17e5360b0a5e3a78f8d223e739db7b438798666a4e", size = 92515194, upload-time = "2026-12-01T19:57:20.856Z" }, + { url = "https://files.pythonhosted.org/packages/76/6d/8a582e269c35854464bd99f64900e248ddafe6dbf23435f494229ddf34c0/spiral_sdk-0.16.80-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:283915dfbac6b30b9e9ec813c475713b23d1c4cbab893ae510c8d93ddf24d3fb", size = 94853432, upload-time = "2026-12-01T19:57:25.124Z" }, ] [[package]] From 57f1b66e02335cdc021b79e18aab321e835bcfce Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 15:55:50 -0800 Subject: [PATCH 25/50] fix(spiraldb): open and create every store table through the connector (ITL-1840) spiral-sdk 0.16.79 and later warn on every keyed-table call, attributed to the calling module, and Orcapod ignores that warning for spiraldb_connector's own calls only. The store created tables and opened them by id itself; both now go through connector helpers (_open_keyed_table_by_id, _create_keyed_table) handed to StoreTables as callables, so a store-mode add, flush and listing raise no deprecation with warnings as errors. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 6 +++ src/orcapod/databases/spiraldb_connector.py | 27 +++++++++++- .../databases/spiraldb_store_tables.py | 34 +++++--------- .../test_spiraldb_store_mode.py | 44 +++++++++++++++++++ 4 files changed, 88 insertions(+), 23 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index cec476f89..fab5f8bcf 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -94,6 +94,12 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. ## Finding a table, and what is kept +- Every keyed table the store opens (by name or by id) or creates is opened or created by + `spiraldb_connector` (`_open_keyed_table`, `_open_keyed_table_by_id`, + `_create_keyed_table`), handed to `StoreTables` as callables: spiral-sdk 0.16.79 and later + warn on every keyed-table call, attributed to the calling module, and Orcapod ignores that + warning for that module's own calls only (stage A, `_ignore_keyed_table_deprecation`). + - A table's name is opened once per public operation of `ConnectorArrowDatabase` (an add, a flush, a read, a schema or listing call; `StoreTables.operation`), and that handle reused within it until the store writes to the table (review round 2). A flush of a table diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 1833c36a8..d5cf31d04 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -226,6 +226,28 @@ def _open_keyed_table( return None +def _open_keyed_table_by_id(client: Any, table_id: str) -> Any: + """Return the latest snapshot of the keyed table with id ``table_id``. + + Opened here, so spiral-sdk's keyed-table deprecation is ignored for it as for every + other open Orcapod makes (``_ignore_keyed_table_deprecation``). + """ + _ignore_keyed_table_deprecation() + return client.keyed_table_by_id(table_id) + + +def _create_keyed_table( + client: Any, project_id: str, dataset: str, name: str, key_schema: pa.Schema +) -> Any: + """Create a keyed table in a dataset, by name and key schema. + + Created here, so spiral-sdk's keyed-table deprecation is ignored for it as for every + open Orcapod makes (``_ignore_keyed_table_deprecation``). + """ + _ignore_keyed_table_deprecation() + return client.project(project_id).create_keyed_table(dataset, name, key_schema) + + def _warn_unrecorded(table: str, table_id: str) -> None: """Warn once per table and process that its schema is not recorded. @@ -962,13 +984,16 @@ def __init__( self._store: StoreTables | None = None if _store: self._store = StoreTables( - client, sp, project_id, dataset, lambda name: _open_keyed_table( client, project_id, dataset, name, health ), + lambda table_id: _open_keyed_table_by_id(client, table_id), + lambda name, key: _create_keyed_table( + client, project_id, dataset, name, key + ), lambda: _list_keyed_tables(client, project_id, dataset), lambda doing: _service_call( f"{doing} of {project_id}/{dataset}", health diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index d8d69af35..e3086cb86 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -92,22 +92,6 @@ def 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 holds rows, with what its metadata records. @@ -162,31 +146,38 @@ class _New: class StoreTables: """The store tables of one SpiralDB dataset. + Every keyed table is opened or created through the connector's callables, never + through the SDK client here: the connector owns every call that opens a keyed table + (spiral-sdk's keyed-table deprecation is ignored for its own calls only). + Args: - client: A spiral-sdk client. sdk: The spiral-sdk module (its error class). project_id: The project. dataset: The dataset. open_table: Opens a keyed table by name; ``None`` when there is none. + open_table_by_id: Opens a keyed table by its id. + create_table: Creates a keyed table in the dataset, by name and key schema. 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, sdk: Any, # pyright: ignore[reportExplicitAny] # the optional spiral-sdk module project_id: str, dataset: str, open_table: Callable[[str], _KeyedTable | None], + open_table_by_id: Callable[[str], _KeyedTable], + create_table: Callable[[str, pa.Schema], object], list_tables: Callable[[], dict[str, str]], service_call: Callable[[str], AbstractContextManager[None]], ) -> None: - self._client: _Client = client self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] self._project_id: str = project_id self._dataset: str = dataset self._open_table: Callable[[str], _KeyedTable | None] = open_table + self._open_table_by_id: Callable[[str], _KeyedTable] = open_table_by_id + self._create_table: Callable[[str, pa.Schema], object] = create_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, ...]] = {} @@ -510,7 +501,7 @@ def _record_of( record = self._records_by_id.get(table_id) if record is None: with self._service_call("read the metadata of a store table"): - metadata = self._client.keyed_table_by_id(table_id).get_metadata() + metadata = self._open_table_by_id(table_id).get_metadata() record = identity.read_store_table_metadata(metadata) if record is None: return None # never kept: its record may be written later @@ -659,10 +650,9 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: if table is not None: return table 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) + _ = self._create_table(table_name, key) except self._sdk.SpiralError as exc: # pyright: ignore[reportAny] if "status 409" not in str(exc): # pyright: ignore[reportAny] raise diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 0327df43a..82e7e8c97 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1843,3 +1843,47 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: kept = codec.read_manifest(_table(name).get_metadata(), RESULT) assert kept is not None and kept.schema.equals(peers_manifest.schema) assert _table(name).scan().to_table().num_rows == 0 + + +@pytest.mark.usefixtures("root") +def test_a_store_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """spiral-sdk 0.16.79 and later warn on every keyed-table open and creation, + attributed to the module that calls the SDK; Orcapod ignores that warning for its + connector's own calls only. The fake warns the same way here, so the store's + creation, opens by name and opens by id must all be the connector's: with every + warning an error, an add, a flush and a listing raise none (the store used to create + a table and open one by id itself, and raised). A direct call from elsewhere still + warns.""" + import warnings + + called: dict[str, int] = {} + + def deprecated(name: str, original: Any) -> Any: + def call(*args: Any, **kwargs: Any) -> Any: + called[name] = called.get(name, 0) + 1 + warnings.warn( + "Keyed tables are deprecated.", DeprecationWarning, stacklevel=2 + ) + return original(*args, **kwargs) + + return call + + for owner, name in [ + (fake.FakeClient, "keyed_table"), + (fake.FakeClient, "keyed_table_by_id"), + (fake.FakeProject, "create_keyed_table"), + ]: + monkeypatch.setattr(owner, name, deprecated(name, getattr(owner, name))) + with warnings.catch_warnings(): + warnings.simplefilter("error") + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + _add(db, rows(["r2"], offset=2), flush=True) + assert ConnectorArrowDatabase(store()).list_table_paths() == [RESULT] + got = _get(db) + assert got is not None and sorted(_record_ids(got)) == [b"r0", b"r1", b"r2"] + with pytest.raises(DeprecationWarning, match="Keyed tables are deprecated"): + _ = _table(identity.spiral_store_table_name(RESULT)) + assert {"keyed_table", "keyed_table_by_id", "create_keyed_table"} <= called.keys() From 1e9b9009a691e2e7872aecc2f5e37b57bd5f1730 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 16:04:50 -0800 Subject: [PATCH 26/50] fix(spiraldb): keep the keyed-table deprecation filter first; route the migration script through it (ITL-1837) The first matching warnings filter wins, so a filter added after Orcapod's first open (simplefilter("error"), pytest.warns, a recording catch_warnings) ranked ahead of Orcapod's and its later opens warned, or raised as a misleading connection error. The filter is now moved to the front before each open when it is not first; filterwarnings drops the older copy, so the list never grows. The schema migration script opened and created keyed tables directly, outside the filter. It now opens through _open_keyed_table and creates through a new connector helper, _create_keyed_table. The fake SDK warns as 0.16.80 does (rule "deprecated"), so the tests see the warning wherever Orcapod would. The plan notes that Python 3.14's context-aware warnings are untested. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1837-spiral-store-stage-a.md | 24 +++++++---- scripts/migrate_spiral_schemas.py | 19 ++++++-- src/orcapod/databases/spiraldb_connector.py | 41 +++++++++++++++--- tests/test_databases/fake_spiral_sdk.py | 29 +++++++++++-- .../test_migrate_spiral_schemas.py | 27 ++++++++++++ .../test_spiraldb_keyed_table_deprecation.py | 43 +++++++++++++++++++ 6 files changed, 162 insertions(+), 21 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md index 247ab8097..de7f31bdd 100644 --- a/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md +++ b/docs/dev/plans/2026-12-01-itl-1837-spiral-store-stage-a.md @@ -32,15 +32,23 @@ keyed tables deprecated: `Client.keyed_table`, `keyed_table_by_id` and `Project.create_keyed_table` each call `warn("Keyed tables are deprecated.", DeprecationWarning, stacklevel=3)`, so the warning is attributed to the module that calls the SDK. 0.16.80 changes nothing else Orcapod uses (it removes the duration types, which -the store already refuses). Orcapod's only module that opens keyed tables is -`orcapod.databases.spiraldb_connector`; before each open it installs, if missing, one -filter: action `ignore`, that exact message, `DeprecationWarning`, and that module only -(`_ignore_keyed_table_deprecation`). A user's own call to the SDK, another message and -another category still warn. It is installed before each open, not once at import, -because a `warnings.catch_warnings` block (pytest wraps every test in one) drops a filter -added inside it, and it uses no `catch_warnings` itself, which is not safe with threads. +the store already refuses). Orcapod's only module that opens or creates keyed tables is +`orcapod.databases.spiraldb_connector` (the schema migration script opens and creates +through its helpers `_open_keyed_table` and `_create_keyed_table`); before each open or +creation it puts one filter FIRST in the filter list: action `ignore`, that exact message, +`DeprecationWarning`, and that module only (`_ignore_keyed_table_deprecation`). First, not +merely present, because the first matching filter wins: a filter added after an earlier +open (`simplefilter("error")`, `pytest.warns`, a recording `catch_warnings`) would +otherwise rank ahead of it. `filterwarnings` removes the older copy before inserting, so +the list never grows. A user's own call to the SDK, another message and another category +still warn. It is installed before each open, not once at import, because a +`warnings.catch_warnings` block (pytest wraps every test in one) drops a filter added +inside it, and it uses no `catch_warnings` itself, which is not safe with threads. `tests/test_databases/test_spiraldb_keyed_table_deprecation.py` checks both sides with the -real SDK client over a stub native client. +real SDK client over a stub native client, and the fake SDK warns as 0.16.80 does (rule +`deprecated`). Not tested: Python 3.14's context-aware warnings (the default of the +free-threaded build), where `catch_warnings` filters are context-local; CI covers Python +3.11 to 3.13 only. The live conformance run on 0.16.80 (2026-12-01, as the agent workload, in the conformance dataset of the test project) found one measured rule change: a keyed-table diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 811de8d79..e7557892e 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -342,7 +342,10 @@ def require_unchanged( rows: list[Any], ) -> None: """Refuse unless every table of the dataset is as the plan found it.""" - from orcapod.databases.spiraldb_connector import _list_keyed_tables + from orcapod.databases.spiraldb_connector import ( + _list_keyed_tables, + _open_keyed_table, + ) from orcapod.databases.spiraldb_schema_table import ( compared_columns, describe_difference, @@ -358,8 +361,10 @@ def require_unchanged( f"{sorted(set(names) ^ set(planned))}" ) for table, row in zip(tables, rows): - handle = client.keyed_table(project, dataset, row.table_name) + handle = _open_keyed_table(client, project, dataset, row.table_name) where = f"{dataset}/{row.table_name}" + if handle is None: + raise MigrationError(f"{where} was removed since it was listed") if handle.resource_id != row.table_id: raise MigrationError(f"{where} is another table than in the dry run") if int(handle.version_id) != table["row"]["captured_version"]: @@ -459,6 +464,7 @@ def write(args: argparse.Namespace) -> None: import pyarrow as pa from orcapod.databases import spiraldb_schema_table as st + from orcapod.databases.spiraldb_connector import _create_keyed_table plan = read_plan(args.plan) require_scope(plan, args) @@ -499,8 +505,13 @@ def put(dataset: str, values: dict[str, Any]) -> None: # Created once, exclusively; the note is there before and after. write_note(args, dataset, CREATING) try: - handle = client.project(project).create_keyed_table( - dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=False + handle = _create_keyed_table( + client, + project, + dataset, + SCHEMA_TABLE, + st.KEY_SCHEMA, + exist_ok=False, ) except Exception as exc: if "status 409" not in str(exc): diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 402d43edc..7067b2daf 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -188,12 +188,15 @@ def _ignore_keyed_table_deprecation() -> None: """Ignore spiral-sdk's keyed-table deprecation for this module's own opens. Called before each open, not once at import: a ``warnings.catch_warnings`` block - (pytest wraps every test in one) drops a filter added inside it. Added only when it - is missing, so the filter list does not change in steady state. No - ``catch_warnings`` here: it swaps the process-wide filter list and is not safe with - threads. + (pytest wraps every test in one) drops a filter added inside it. The first matching + filter wins, so the filter is kept FIRST, not merely present: a filter added after + an earlier open (``simplefilter("error")``, ``pytest.warns``, a recording + ``catch_warnings``) would otherwise rank ahead of it. ``filterwarnings`` removes the + older copy before inserting at the front, so the list never grows; in steady state + the filter is already first and the list does not change. No ``catch_warnings`` + here: it swaps the process-wide filter list and is not safe with threads. """ - if _KEYED_TABLE_FILTER not in warnings.filters: + if not warnings.filters or warnings.filters[0] != _KEYED_TABLE_FILTER: warnings.filterwarnings( "ignore", message=_KEYED_TABLE_DEPRECATION, @@ -225,6 +228,34 @@ def _open_keyed_table( return None +def _create_keyed_table( + client: Any, + project_id: str, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool, +) -> Any: + """Create a keyed table and return it, with the SDK's errors as they are. + + The one place Orcapod creates a keyed table, so that its creation is attributed to + this module and covered by the same filter as its opens (ITL-1837). + + Args: + client: The spiral-sdk client. + project_id: The project. + dataset: The dataset. + name: The table. + key_schema: Its key columns, in key order. + exist_ok: Whether a table already there with these key columns is returned. + """ + _ignore_keyed_table_deprecation() + return client.project(project_id).create_keyed_table( + dataset, name, key_schema, exist_ok=exist_ok + ) + + def _warn_unrecorded(table: str, table_id: str) -> None: """Warn once per table and process that its schema is not recorded. diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 72b0c9f9c..c2c0cdba0 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -21,6 +21,7 @@ import types import urllib.parse import uuid +import warnings from collections.abc import Iterator from contextlib import contextmanager from dataclasses import dataclass @@ -69,6 +70,9 @@ "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", + "deprecated": "spiral-sdk 0.16.79 and later (read in the 0.16.80 wheel, December 1, " + "2026): keyed_table, keyed_table_by_id and create_keyed_table warn 'Keyed tables are " + "deprecated.' (DeprecationWarning, stacklevel=3: attributed to the calling module)", "unsupported": "interval, fixed-size binary, union, an empty struct and a null " "struct outside a list are refused; a duration is accepted and read back as given " "(spiral-sdk 0.16.80, December 1, 2026: a duration[s] column, which 0.16.78 refused)", @@ -1045,6 +1049,13 @@ def _open(store: _Store, table: dict[str, Any], asof: int | None) -> FakeKeyedTa return FakeKeyedTable(store, table, version) +def _warn_deprecated() -> None: + """Warn as spiral-sdk 0.16.79 and later do on every keyed-table open and creation + (``deprecated``): from a helper at ``stacklevel=3``, so the warning is attributed to + the module that called the SDK.""" + warnings.warn("Keyed tables are deprecated.", DeprecationWarning, stacklevel=3) + + class FakeProject: """Stands in for ``spiral.projects.Project``.""" @@ -1055,7 +1066,15 @@ def __init__(self, store: _Store, project: str) -> None: def create_keyed_table( self, dataset: str, name: str, key_schema: pa.Schema, *, exist_ok: bool = False ) -> FakeKeyedTable: - """Create a table (``create-409``, ``create-key-types``, ``names``).""" + """Create a table (``create-409``, ``create-key-types``, ``names``, + ``deprecated``).""" + _warn_deprecated() + return self._create(dataset, name, key_schema, exist_ok=exist_ok) + + def _create( + self, dataset: str, name: str, key_schema: pa.Schema, *, exist_ok: bool + ) -> FakeKeyedTable: + """Create a table, with no deprecation warning: the fake's own creations.""" if not dataset or not name: raise ValueError("dataset and table names must be nonempty") if len(name) > 255: @@ -1101,7 +1120,8 @@ def project(self, id: str) -> FakeProject: def keyed_table( self, project: str, dataset: str, name: str, *, asof: int | None = None ) -> FakeKeyedTable: - """Open a table by name (``missing``).""" + """Open a table by name (``missing``, ``deprecated``).""" + _warn_deprecated() table = self._store.find(project, dataset, name) if table is None: raise SpiralError(f"resource not found: {project}.{dataset}.{name}") @@ -1110,7 +1130,8 @@ def keyed_table( def keyed_table_by_id( self, table_id: str, *, asof: int | None = None ) -> FakeKeyedTable: - """Open a table by its id.""" + """Open a table by its id (``deprecated``).""" + _warn_deprecated() return _open(self._store, self._store.by_id(table_id), asof) @@ -1263,7 +1284,7 @@ def migrate( from orcapod.utils import arrow_utils store = _store() - handle = FakeProject(store, project).create_keyed_table( + handle = FakeProject(store, project)._create( dataset, SCHEMA_TABLE, st.KEY_SCHEMA, exist_ok=True ) stored = store.read(handle.resource_id, int(handle.version_id)) diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 655fd8fb9..125f922d6 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -9,6 +9,7 @@ import argparse import importlib.util import json +import warnings from collections.abc import Callable from pathlib import Path from types import ModuleType @@ -150,6 +151,32 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: assert schema.field("v").metadata == {b"unit": b"mV"} +def test_the_dry_run_reads_raise_no_keyed_table_deprecation( + tool: ModuleType, project: Any +) -> None: + """The dry run's reads of each table go through the connector, which ignores the + SDK's keyed-table deprecation for its own opens, after an earlier open too.""" + fake.migrate("p", dict.fromkeys(_TABLES, _WRITTEN), "one") + connector = SpiralDBConnector("p", "one") + _ = connector.lookup_table("trials") # an earlier open, before the error filter + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + for name in _TABLES: + described = tool.describe_table(connector, "p", "one", name) + assert described["row"]["table_name"] == name + + +def test_the_write_and_verify_raise_no_keyed_table_deprecation( + tool: ModuleType, args: argparse.Namespace +) -> None: + """The write opens each planned table and creates each schema table through the + connector's helpers, never the SDK directly, so neither warns.""" + with warnings.catch_warnings(): + warnings.simplefilter("error", DeprecationWarning) + tool.write(args) + tool.verify(args) + + @pytest.mark.parametrize("stop_after", [1, 2, 3, 4]) def test_an_interrupted_write_is_refused_by_reads_and_resumed( tool: ModuleType, args: argparse.Namespace, stop_after: int diff --git a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py index 77bfadade..48ce773b6 100644 --- a/tests/test_databases/test_spiraldb_keyed_table_deprecation.py +++ b/tests/test_databases/test_spiraldb_keyed_table_deprecation.py @@ -102,3 +102,46 @@ def test_a_direct_sdk_open_still_warns(connector: SpiralDBConnector) -> None: _ = client.keyed_table("p", "d", "t") with pytest.raises(DeprecationWarning, match=MESSAGE): _ = client.keyed_table_by_id("tbl_1", asof=1) + + +def test_an_error_filter_added_after_an_open_does_not_reach_orcapods_opens( + connector: SpiralDBConnector, +) -> None: + """The first matching filter wins: an error filter added after Orcapod's first open + ranks ahead of a filter that is merely present. Orcapod's later opens, by name and + by id, still raise no warning and no misleading connection error.""" + with warnings.catch_warnings(): + table = connector.lookup_table("t") # installs Orcapod's filter + warnings.simplefilter("error") + again = connector.lookup_table("t") + assert again.table_id == "tbl_1" + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + + +def test_a_pytest_warns_block_after_an_open_records_no_deprecation( + connector: SpiralDBConnector, +) -> None: + """``pytest.warns`` adds an "always" filter; Orcapod's opens inside it, after an + earlier open, record nothing of the SDK's deprecation.""" + with warnings.catch_warnings(): + table = connector.lookup_table("t") # installs Orcapod's filter + with pytest.warns(UserWarning, match="the block's own") as recorded: + _ = connector.lookup_table("t") + with pytest.raises(sp.SpiralError, match="no version 2"): + _ = table.arrow_schema(asof=2) + warnings.warn("the block's own", UserWarning, stacklevel=1) + assert [type(w.message) for w in recorded] == [UserWarning] + + +def test_the_filter_is_kept_once_however_often_orcapod_opens( + connector: SpiralDBConnector, +) -> None: + """Moved to the front rather than added again: the filter list never grows.""" + with warnings.catch_warnings(): + for _ in range(3): + _ = connector.lookup_table("t") + warnings.simplefilter("error") + _ = connector.lookup_table("t") + assert warnings.filters[0] == spiraldb_connector._KEYED_TABLE_FILTER + assert warnings.filters.count(spiraldb_connector._KEYED_TABLE_FILTER) == 1 From 7cf03b17261b622918a7e1a01619e71ae2f282ab Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 17:15:55 -0800 Subject: [PATCH 27/50] fix(spiraldb): the evaluation script lists its tables per job name and reports them after a failed scenario (ITL-1844) A listing of the whole dataset is refused when the dataset holds a table of another store format under a store table name; the script now lists under each of its job names only, and prints every table it made also when a scenario raises. Co-Authored-By: Claude Opus 5.5 --- docs/dev/scripts/itl_1844_store_evaluation.py | 41 +++++++++++++++---- 1 file changed, 32 insertions(+), 9 deletions(-) diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_store_evaluation.py index f5f5ae224..06e77cf39 100644 --- a/docs/dev/scripts/itl_1844_store_evaluation.py +++ b/docs/dev/scripts/itl_1844_store_evaluation.py @@ -70,6 +70,8 @@ "executed_at", "pipeline_run_id", } +# The job names are ``itl1844_eval__``. +JOB_SUFFIXES = ("sync", "run_async", "node_run", "results", "refused") CALLS: list[tuple[int, int]] = [] SENT: list[int] = [] @@ -175,12 +177,15 @@ def timed(report: dict[str, Any], label: str, run: Any) -> Any: return result -def evaluate(project: str, dataset: str, stamp: str, work: Path) -> dict[str, Any]: +def evaluate( + project: str, dataset: str, stamp: str, work: Path, report: dict[str, Any] +) -> None: + """Run every scenario, filling ``report`` as each one ends.""" + def store() -> ConnectorArrowDatabase: return ConnectorArrowDatabase(SpiralDBConnector(project, dataset, store=True)) delta = DeltaTableDatabase(work / "delta") - report: dict[str, Any] = {"stamp": stamp, "scenarios": {}} s = report["scenarios"] # 1. first run, sync. @@ -270,15 +275,25 @@ def store() -> ConnectorArrowDatabase: "nothing_written": store().list_table_paths((fresh,)) == [], } - # Every store table this evaluation wrote, by name and layout. - every = sorted(store().list_table_paths()) - report["store_tables"] = [ + report["ok"] = all(v.get("ok", True) for v in s.values()) and refused + + +def store_tables(project: str, dataset: str, stamp: str) -> list[dict[str, str]]: + """Every store table of this evaluation's jobs, by name and layout. + + Listed under each job name only: a listing of the whole dataset is refused when the + dataset holds a table of another store format under a store table name. + """ + store = ConnectorArrowDatabase(SpiralDBConnector(project, dataset, store=True)) + every = sorted( + path + for job_name in sorted({f"itl1844_eval_{stamp}_{x}" for x in JOB_SUFFIXES}) + for path in store.list_table_paths((job_name,)) + ) + return [ {"name": spiral_store_table_name(p), "layout": p[-1], "path": "/".join(p)} for p in every - if p[0].startswith(f"itl1844_eval_{stamp}") ] - report["ok"] = all(v.get("ok", True) for v in s.values()) and refused - return report def lease_tables(project: str, dataset: str) -> list[dict[str, str]]: @@ -316,7 +331,15 @@ def main() -> int: if args.mode == "fake": stack.enter_context(fake_service(work)) before = {t["name"] for t in lease_tables(args.project, args.dataset)} - report = evaluate(args.project, args.dataset, stamp, work) + report: dict[str, Any] = {"stamp": stamp, "scenarios": {}, "ok": False} + print(f"stamp {stamp}", file=sys.stderr) + try: + evaluate(args.project, args.dataset, stamp, work, report) + except Exception as exc: # reported with every table made so far + report["error"] = f"{type(exc).__name__}: {exc}" + report["ok"] = False + # Every table this run made, also after a failed scenario. + report["store_tables"] = store_tables(args.project, args.dataset, stamp) report["lease_tables_created"] = [ t for t in lease_tables(args.project, args.dataset) From 19e49f3ead0f9d6bf777f61210e0769638863543 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:18:26 -0800 Subject: [PATCH 28/50] fix(spiraldb): list a table of another store format as a marked path, not a refusal (ITL-1840) A table of another store format under the listed prefix refused the whole dataset listing, which blocked the stale-layout check of every node. It is now listed under its recorded path with the last component "/", which no path can hold (a component never contains "/"): the stale-layout check reports it, a side-effect node refuses, any other node reports and runs. Opening that path raises a ValueError saying what it is (store mode only). A partial, unreadable or renamed record still refuses the listing. No protocol method is added. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 7 +- .../databases/connector_arrow_database.py | 18 ++- .../databases/spiral_store_identity.py | 94 +++++++++++- .../databases/spiraldb_store_tables.py | 61 +++++--- .../test_spiraldb_store_mode.py | 134 +++++++++++++++++- 5 files changed, 288 insertions(+), 26 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index fab5f8bcf..ff84df73c 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -49,7 +49,12 @@ plain `SpiralDBConnector` included, the code paths are `main`'s. (store mode only), so one column has one form in the manifest. - Listing (`list_table_paths`, hence the stale-layout check of ITL-954): one listing of the dataset narrowed by the name prefix, then each candidate's recorded path, cached by table - id; a listed table whose record is of a path with another name is refused. + id; a listed table whose record is of a path with another name is refused, and so is a + partial or unreadable record. A table whose complete record names another store format + is listed under its recorded path with the last component `/`, + which no path can hold (a component never contains `/`): the stale-layout check reports + it (a side-effect node refuses, any other node reports and runs), and opening that path + raises a `ValueError` saying what it is. No protocol method is added (D4). ## The write rules of ITL-1386 diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 06a14c1f4..c9bf015b9 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -44,6 +44,7 @@ ) from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiral_store_identity import refuse_other_format_path from orcapod.databases.spiraldb_store_tables import ( StoreTables, declared_keeping_identifier, @@ -340,8 +341,10 @@ def _get_record_key(self, record_path: tuple[str, ...]) -> str: full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: if self._spiral_connector is not None: - # The one path domain of a SpiralDB store (its identity record and - # manifest apply it too). + # A path list_table_paths gives a table of another store format, + # then the one path domain of a SpiralDB store (its identity record + # and manifest apply it too). + refuse_other_format_path(full_path) _ = require_store_path_domain(full_path) return "/".join(full_path) self._validate_path_components(full_path) @@ -384,6 +387,8 @@ def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: def _validate_record_path(self, record_path: tuple[str, ...]) -> None: if not record_path: raise ValueError("record_path cannot be empty") + if self._spiral_connector is not None: + refuse_other_format_path(record_path) if len(self._path_prefix) + len(record_path) > self.max_hierarchy_depth: raise ValueError( f"record_path depth {len(record_path)} exceeds maximum " @@ -522,6 +527,15 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] catalog and pending batches. Other connectors list by sanitized names. No record table is read. + A SpiralDB store lists its tables by the paths their identity records hold. + A table whose record names another store format is listed with the last + component ``"/"``, which no layout and no store path + can equal (a component never holds ``/``): stale-layout detection reports it + as a table of another layout, and opening that path raises ``ValueError`` + saying what it is. A partial or unreadable record, or a record of a path + whose table has another name, refuses the whole listing + (``SpiralStoreTableCollisionError``). + Args: prefix: Leading path components, relative to ``self.base_path``. diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py index baae18c2b..9b14c3b60 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_store_identity.py @@ -174,13 +174,61 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord """ if not any(k in metadata for k in _RECORD_KEYS): return None - missing = [k for k in _RECORD_KEYS if k not in metadata] - if missing: - raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + _require_complete(metadata) if metadata[STORE_KEY] != STORE_FORMAT.encode(): raise SpiralStoreTableCollisionError( f"its format is {metadata[STORE_KEY]!r}, not {STORE_FORMAT!r}" ) + return _read_record(metadata) + + +def read_store_table_record_of_any_format( + metadata: Mapping[str, bytes], +) -> tuple[StoreTableRecord, str] | None: + """Return a table's record and the store format it names, whatever the format. + + For a listing only: it places a table of another store format by its recorded + path, so the listing can report it without reading it. Every check + ``read_store_table_metadata`` makes is made, except that the format must be this + store's; a table is never opened through what this returns. + + Args: + metadata: The table's metadata, as SpiralDB returns it. + + Returns: + The record and its format, or ``None`` when the table holds none of its + entries. + + Raises: + SpiralStoreTableCollisionError: If the record is partial or unreadable (its + format included). + """ + if not any(k in metadata for k in _RECORD_KEYS): + return None + _require_complete(metadata) + try: + store_format = metadata[STORE_KEY].decode() + except UnicodeDecodeError as exc: + raise SpiralStoreTableCollisionError( + f"its record cannot be read: {exc}" + ) from exc + return _read_record(metadata), store_format + + +def _require_complete(metadata: Mapping[str, bytes]) -> None: + """Refuse a record that lacks one of its entries.""" + missing = [k for k in _RECORD_KEYS if k not in metadata] + if missing: + raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + + +def _read_record(metadata: Mapping[str, bytes]) -> StoreTableRecord: + """The record of complete metadata, its format aside. + + Raises: + SpiralStoreTableCollisionError: If the record cannot be read, or its path, + layout or data context is not one a store table records. + """ try: path: object = json.loads(metadata[PATH_KEY].decode()) # pyright: ignore[reportAny] # checked below layout = metadata[LAYOUT_KEY].decode() @@ -211,6 +259,46 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord return StoreTableRecord(components, layout, data_context_key) +OTHER_FORMAT_SEPARATOR = "/" +"""Joins a recorded layout and a store format in the last component a listing gives a +table of another store format. No store path component holds it +(``require_store_path_domain``), so that component never names a layout or a path.""" + + +def other_format_last_component(record: StoreTableRecord, store_format: str) -> str: + """The last component a listing gives a table of another store format. + + Args: + record: The table's record. + store_format: The store format the record names. + + Returns: + ``"/"``. + """ + return f"{record.layout}{OTHER_FORMAT_SEPARATOR}{store_format}" + + +def refuse_other_format_path(path: Sequence[str]) -> None: + """Refuse a path a listing gives a table of another store format. + + Args: + path: A record path to open. + + Raises: + ValueError: If the path's last component is of the form + ``"/"`` (``other_format_last_component``). + """ + if not path or not isinstance(path[-1], str): + return + layout, separator, store_format = path[-1].partition(OTHER_FORMAT_SEPARATOR) + if separator and layout and store_format: + raise ValueError( + f"{list(path)} is how list_table_paths shows a table of another store " + f"format ({store_format!r}): it is not this store's table and cannot be " + "opened" + ) + + def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> None: """Refuse a store table whose record is of another path than ``path``. diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index e3086cb86..065ef92f7 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -185,7 +185,8 @@ def __init__( # manifest never change once it holds rows. Which table a name opens is asked # on every call (a table can be renamed, and another made under its name). self._found_by_id: dict[str, _Found] = {} - self._records_by_id: dict[str, identity.StoreTableRecord] = {} + # The record of a listed table and the store format it names, by its id. + self._records_by_id: dict[str, tuple[identity.StoreTableRecord, str]] = {} # Within one public operation (``operation``): what each name was judged, its # name opened once and its handle reused. Empty outside an operation. # Kept per thread: an operation is one thread's call, and no other operation @@ -276,10 +277,12 @@ def table_name(self, path: tuple[str, ...]) -> str: The table's name. Raises: - ValueError: If the path is outside the store path domain - (``store_table_names.require_store_path_domain``), which the table's - identity record and manifest apply too. + ValueError: If the path is how ``table_paths`` lists a table of another + store format (``identity.refuse_other_format_path``), or is outside the + store path domain (``store_table_names.require_store_path_domain``), + which the table's identity record and manifest apply too. """ + identity.refuse_other_format_path(path) components = require_store_path_domain(path) name = identity.spiral_store_table_name(components) self._paths[name] = components @@ -464,7 +467,16 @@ def table_paths( 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. + whose record is of a path with another name is refused, and so is a partial or + unreadable record. + + A table whose complete, readable record names another store format, with its + recorded path under ``prefix``, is listed as its recorded path with the last + component ``"/"`` + (``identity.other_format_last_component``): no layout and no store path has that + component, so the table is reported as one of another layout, and opening that + path is refused (``table_name``). Its name is not checked: another format may + name its tables otherwise. Args: prefix: The full path prefix. @@ -481,36 +493,49 @@ def table_paths( if not table_name.startswith(start): continue with self._about(table_name): - record = self._record_of(table_id, table_name) - if record is not None and record.path[: len(prefix)] == prefix: + read = self._record_of(table_id, table_name) + if read is None: + continue + record, store_format = read + if record.path[: len(prefix)] != prefix: + continue + if store_format == identity.STORE_FORMAT: found.add(record.path) + else: + last = identity.other_format_last_component(record, store_format) + found.add((*record.path[:-1], last)) return sorted(found) def _record_of( self, table_id: str, table_name: str - ) -> identity.StoreTableRecord | None: - """The record of a listed table, read once per id; ``None`` without one. + ) -> tuple[identity.StoreTableRecord, str] | None: + """The record of a listed table and the store format it names, read once per + id; ``None`` without one. - The name it is listed under now is checked against its record on every call, - the cached one included: a table renamed keeps its id. + For this store's format, the name it is listed under now is checked against its + record on every call, the cached one included: a table renamed keeps its id. Args: table_id: The listed table's id. table_name: The name it is listed under. """ - record = self._records_by_id.get(table_id) - if record is None: + read = self._records_by_id.get(table_id) + if read is None: with self._service_call("read the metadata of a store table"): metadata = self._open_table_by_id(table_id).get_metadata() - record = identity.read_store_table_metadata(metadata) - if record is None: + read = identity.read_store_table_record_of_any_format(metadata) + if read is None: return None # never kept: its record may be written later - self._records_by_id[table_id] = record - if identity.spiral_store_table_name(record.path) != table_name: + self._records_by_id[table_id] = read + record, store_format = read + if ( + store_format == identity.STORE_FORMAT + and identity.spiral_store_table_name(record.path) != table_name + ): raise SpiralStoreTableCollisionError( f"it records path {list(record.path)}, whose table has another name" ) - return record + return read # ── reading ────────────────────────────────────────────────────────────── diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 40e471dd4..3139368aa 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -18,7 +18,11 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.contexts.stored import tables_of_another_layout +from orcapod.contexts.stored import ( + account_for_stale_tables, + find_stale_tables, + tables_of_another_layout, +) from orcapod.core.operators import SelectDataColumns from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector @@ -26,7 +30,11 @@ from orcapod.databases import spiral_store_identity as identity from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError from orcapod.databases.spiraldb_store_tables import StoreTables -from orcapod.errors import InputValidationError, SpiralDBWriteNotSupportedError +from orcapod.errors import ( + InputValidationError, + SideEffectLogDataContextError, + SpiralDBWriteNotSupportedError, +) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource, DictSource @@ -711,6 +719,128 @@ def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) +OTHER_FORMAT = "orcapod.spiral_store.v1" +OTHER = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +OTHER_LISTED = (*OTHER[:-1], f"rdb_v1/{OTHER_FORMAT}") + + +def _make_other_format_table(path: tuple[str, ...]) -> None: + """A table of another store format, its record complete and readable.""" + metadata = { + **identity.store_table_metadata(path, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + } + _make_table(identity.spiral_store_table_name(path), metadata, with_rows=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["current_first", "other_first"]) +def test_a_table_of_another_store_format_is_listed_with_a_marked_last_component( + order: str, +) -> None: + """Only that table is marked; the listing of the others goes on.""" + current = ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") + outside = ("my_fnx", H, "rdb_v1") + db = ConnectorArrowDatabase(store()) + if order == "other_first": + _make_other_format_table(OTHER) + _make_other_format_table(outside) + db.add_records(current, rows(["r0"]), record_id_column="__record_id", flush=True) + if order == "current_first": + _make_other_format_table(OTHER) + _make_other_format_table(outside) + assert db.list_table_paths(("my_fn",)) == sorted([current, OTHER_LISTED]) + assert db.at("my_fn").list_table_paths((H,)) == sorted( + [current[1:], OTHER_LISTED[1:]] + ) + + +@pytest.mark.usefixtures("root") +def test_the_whole_store_lists_a_table_of_another_store_format() -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + db.add_records(PATHS[3], rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths() == sorted([OTHER_LISTED, PATHS[3]]) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_store_format_is_a_stale_table() -> None: + """A side-effect node refuses before acting; any other node reports and runs.""" + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [ + OTHER_LISTED + ] + found = find_stale_tables(db, name_path=("my_fn",), result_revision="rev1") + assert [t.record_path for t in found.tables] == [OTHER_LISTED] + with pytest.raises(SideEffectLogDataContextError): + account_for_stale_tables( + found, delivers_side_effects=True, current_context=CONTEXT + ) + account_for_stale_tables( + found, delivers_side_effects=False, current_context=CONTEXT + ) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_store_format_opened_by_its_path_is_refused() -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="format"): + _ = db.table_exists(OTHER) + with pytest.raises(SpiralStoreTableCollisionError, match="format"): + db.add_records(OTHER, rows(["r0"]), record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "open_", + [ + lambda db, path: db.table_exists(path), + lambda db, path: db.get_all_records(path), + lambda db, path: db.get_table_schema(path), + lambda db, path: db.add_records( + path, rows(["r0"]), record_id_column="__record_id" + ), + ], + ids=["table_exists", "get_all_records", "get_table_schema", "add_records"], +) +def test_a_listed_path_of_another_store_format_cannot_be_opened(open_: Any) -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + for listed in (db.list_table_paths(("my_fn",)), db.list_table_paths()): + assert listed == [OTHER_LISTED] + with pytest.raises(ValueError, match="another store format") as raised: + _ = open_(db, OTHER_LISTED) + assert OTHER_FORMAT in str(raised.value) + assert not isinstance(raised.value, SpiralStoreTableCollisionError) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "metadata", + [ + {identity.STORE_KEY: OTHER_FORMAT.encode()}, + { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + identity.PATH_KEY: b"[not json", + }, + { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: b"\xff\xfe", + }, + ], + ids=["partial", "unreadable_path", "undecodable_format"], +) +def test_a_doubtful_record_of_another_store_format_still_refuses_the_listing( + metadata: dict[str, bytes], +) -> None: + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + @pytest.mark.usefixtures("root") def test_a_table_listed_before_its_record_is_listed_after_it() -> None: _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) From 8c10bd571e4daa92b658531c678d42a33b534809 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:19:48 -0800 Subject: [PATCH 29/50] fix(spiraldb_lease): keep acquisition errors and wrap failed reopens - A failed reopen of a held lease (check, release) now raises LeaseError naming the table id, chained from the SDK error; the same-process check stays outside it. - An interruption (KeyboardInterrupt) while releasing a failed acquisition is recorded as a note naming the lease table id, and the acquisition's own error is raised, as a failed claim already does. - The changelog fragment states that orcapod_lease_v1_g table names are now reserved: such a table is no longer read or listed; rename it. Each fix has a regression test that fails without it. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1838.md | 4 ++ src/orcapod/databases/spiraldb_lease.py | 12 +++- tests/test_databases/test_spiral_lease.py | 82 ++++++++++++++++++++++- 3 files changed, 92 insertions(+), 6 deletions(-) diff --git a/changelog.d/ITL-1838.md b/changelog.d/ITL-1838.md index b92b306d1..67bb40e21 100644 --- a/changelog.d/ITL-1838.md +++ b/changelog.d/ITL-1838.md @@ -1,3 +1,7 @@ +### Breaking changes and migration + +- SpiralDB table names of the form `orcapod_lease_v1_g` (`N` a positive whole number without leading zeros) are now reserved for writer lease generations. A keyed table with such a name is no longer read or listed by the SpiralDB connector, and the connector refuses to create one. Rename the table before upgrading. + ### Added - Added internal SpiralDB writer leases based on generation tables, with manual recovery by table ID. diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 315fe637b..70f878447 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -314,9 +314,10 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le # row can be written even if reading the current lease state failed. try: _write_release(client, claimed, key) - except Exception as cleanup_error: + except BaseException as cleanup_error: exc.add_note( - f"Releasing the failed acquisition also failed: {cleanup_error}" + f"Releasing the failed acquisition also failed (writer lease table ID " + f"{lease.table_id!r}): {cleanup_error!r}" ) raise return lease @@ -325,7 +326,12 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le def _held_table(client: _Client, lease: Lease) -> _KeyedTable: """Reopen the lease by ID and verify that it belongs to this process and token.""" sdk.require_same_process(lease.pid) - table = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, lease.table_id)) + try: + table = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, lease.table_id)) + except Exception as exc: + raise LeaseError( + f"Could not reopen SpiralDB lease table ID {lease.table_id!r}" + ) from exc if table.resource_id != lease.table_id or _key(table) != lease.key: raise LeaseError(f"SpiralDB lease table ID {lease.table_id!r} changed identity") return table diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 8818beba7..8a5e40709 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -12,6 +12,7 @@ from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.spiraldb_lease import ( LeaseBusyError, + Lease, LeaseError, acquire, check, @@ -305,9 +306,16 @@ def lose_owner_reply( patch.setattr(fake.FakeKeyedTable, "scan", unavailable) if failed_call == "scan_after_write_error": patch.setattr(fake.FakeKeyedTable, "append", lose_owner_reply) - with pytest.raises(TimeoutError, match="verification unavailable") as caught: - _ = acquire(client, _PROJECT, _DATASET, owner="first") - assert caught.value is unavailable_error + if failed_call == "open": + with pytest.raises(LeaseError, match="Could not reopen") as reopened: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert reopened.value.__cause__ is unavailable_error + else: + with pytest.raises( + TimeoutError, match="verification unavailable" + ) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is unavailable_error check(client, acquire(client, _PROJECT, _DATASET, owner="next")) @@ -333,6 +341,74 @@ def unavailable(*_args: object) -> None: check(client, acquire(client, _PROJECT, _DATASET, owner="next")) +def test_release_reports_a_failed_reopen_as_a_lease_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + cause = TimeoutError("reopen unavailable") + + def unavailable(*_args: object, **_kwargs: object) -> None: + raise cause + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) + with pytest.raises(LeaseError, match=holder.table_id) as failed: + release(client, holder) + assert failed.value.__cause__ is cause + release(client, holder) + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +def test_release_from_another_process_is_refused_before_the_reopen( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + elsewhere = Lease(holder.table_id, holder.key, holder.pid + 1) + + def unexpected_open(*_args: object, **_kwargs: object) -> None: + raise AssertionError("the lease table was reopened") + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeClient, "keyed_table_by_id", unexpected_open) + with pytest.raises(RuntimeError) as refused: + release(client, elsewhere) + assert not isinstance(refused.value, LeaseError) + release(client, holder) + + +def test_interrupted_cleanup_keeps_the_acquisition_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + append = fake.FakeKeyedTable.append + verification_error = TimeoutError("verification unavailable") + + def interrupt_release( + table: fake.FakeKeyedTable, rows: pa.Table + ) -> fake.FakeKeyedTable: + if rows.column("owner").null_count == 0: + return append(table, rows) + raise KeyboardInterrupt + + def unavailable(*_args: object, **_kwargs: object) -> None: + raise verification_error + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "append", interrupt_release) + patch.setattr(fake.FakeKeyedTable, "scan", unavailable) + with pytest.raises(TimeoutError) as failed: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert failed.value is verification_error + with pytest.raises(LeaseBusyError) as refused: + _ = acquire(client, _PROJECT, _DATASET, owner="next") + assert any( + "Releasing the failed acquisition also failed" in note + and refused.value.table_id in note + and "KeyboardInterrupt" in note + for note in failed.value.__notes__ + ) + clear(client, refused.value.table_id, confirm_writer_stopped=True) + + @pytest.mark.parametrize("landed", [True, False]) def test_release_reply_lost( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, landed: bool From 29abfe869e78c1a172faaca03c8e2cfb1ce69f02 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:26:13 -0800 Subject: [PATCH 30/50] fix(databases): a stored table a lookup cannot read fails the run; list only tables that hold rows (ITL-1840) Four items from CodeRabbit's review of PR 693, each with a regression test: - M1: _get_committed_table turns a read failure into OrcapodDatabaseReadError in both branches (SpiralDB store scan and SQL iter_batches), re-raising an OrcapodDatabaseError as it is, as get_table_schema does. Under error_policy="continue" such a failure fails the run (sync and async) and is not reported as a crashed row. On SQL this changes main's behaviour: a failing read raised the connector's own error; job.run's contract says an unreadable stored table fails the run. - b1: a store table is recorded before its first append, so a failed first append left an empty recorded table that the listing reported (and the stale-layout check counted). A committed table is listed only when it holds rows; pending paths stay listed. - b2: the commit-time schema guard is given the recorded schema, field and schema metadata included (store.arrow_schema), as get_table_schema gives it. - b3: the fake's test asserts the staged zero-row encoded column's type for both encodings. Co-Authored-By: Claude Opus 5.5 --- .../databases/connector_arrow_database.py | 43 +++++-- .../databases/spiraldb_store_tables.py | 36 ++++-- tests/test_databases/test_fake_spiral_sdk.py | 5 + .../test_spiraldb_store_mode.py | 111 ++++++++++++++++++ .../test_sqlite_connector_integration.py | 25 +++- 5 files changed, 197 insertions(+), 23 deletions(-) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index c9bf015b9..c69ffb6b6 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -484,7 +484,14 @@ def _find_committed_table( def _get_committed_table( self, record_path: tuple[str, ...], *, schema: str | None ) -> pa.Table | None: - """Fetch all committed records for a path from the connector.""" + """Fetch all committed records for a path from the connector. + + Raises: + OrcapodDatabaseReadError: If the table exists and cannot be read, on + every connector: a lookup that cannot read the stored table fails + the run rather than one row (``job.run``'s contract for an + unreadable stored table), as ``get_table_schema`` does. + """ full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) @@ -492,17 +499,20 @@ def _get_committed_table( if table is None: return None schema, name = table - if (store := self._spiral) is not None: - batches = list(store.scan(name)) - return pa.Table.from_batches(batches) if batches else None - batches = list( - self._connector.iter_batches( - f"SELECT * FROM {sql_table_identifier(name, schema)}" - ) - ) - if not batches: - return None - return pa.Table.from_batches(batches) + try: + if (store := self._spiral) is not None: + batches = list(store.scan(name)) + else: + batches = list( + self._connector.iter_batches( + f"SELECT * FROM {sql_table_identifier(name, schema)}" + ) + ) + except OrcapodDatabaseError: + raise + except Exception as exc: + raise OrcapodDatabaseReadError(table_name, full_path) from exc + return pa.Table.from_batches(batches) if batches else None def _stored_conflicts( self, table: tuple[str | None, str], input_ids: set[bytes] @@ -1282,7 +1292,14 @@ def _write_ready_batch( existing = self._stored_columns(table_name, schema) if table_exists else None check = self._pending_commits.schema_check(record_key) if check is not None: - schema_now = pending.schema if existing is None else pa.schema(existing) + if existing is None: + schema_now = pending.schema + elif store is not None: + # As recorded: field and schema metadata included, as + # ``get_table_schema`` gives it. + schema_now = store.arrow_schema(table_name) + else: + schema_now = pa.schema(existing) if store is None: check(schema_now) else: diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 065ef92f7..645ae0263 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -185,7 +185,8 @@ def __init__( # manifest never change once it holds rows. Which table a name opens is asked # on every call (a table can be renamed, and another made under its name). self._found_by_id: dict[str, _Found] = {} - # The record of a listed table and the store format it names, by its id. + # The record of a listed table that holds rows and the store format it names, + # by its id (a table that holds rows never loses them). self._records_by_id: dict[str, tuple[identity.StoreTableRecord, str]] = {} # Within one public operation (``operation``): what each name was judged, its # name opened once and its handle reused. Empty outside an operation. @@ -432,7 +433,7 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: record = identity.read_store_table_metadata(metadata) if record is not None: identity.require_store_table_path(record, path) - if not _holds_rows(table, self._service_call): + if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]): # New: its first write records it, unless what it saw here changed. return _New(_seen_manifest(metadata, path)) try: @@ -468,7 +469,9 @@ def table_paths( 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, and so is a partial or - unreadable record. + unreadable record. A table with no rows is not listed (a first write that + stopped after recording the table and before its rows leaves one); a pending + path is listed all the same. A table whose complete, readable record names another store format, with its recorded path under ``prefix``, is listed as its recorded path with the last @@ -510,23 +513,25 @@ def _record_of( self, table_id: str, table_name: str ) -> tuple[identity.StoreTableRecord, str] | None: """The record of a listed table and the store format it names, read once per - id; ``None`` without one. + id; ``None`` without one, or when the table holds no rows. For this store's format, the name it is listed under now is checked against its record on every call, the cached one included: a table renamed keeps its id. + Whether it holds rows is asked until it does. Args: table_id: The listed table's id. table_name: The name it is listed under. """ read = self._records_by_id.get(table_id) + table: _KeyedTable | None = None if read is None: + table = self._open_table_by_id(table_id) with self._service_call("read the metadata of a store table"): - metadata = self._open_table_by_id(table_id).get_metadata() + metadata = table.get_metadata() read = identity.read_store_table_record_of_any_format(metadata) if read is None: return None # never kept: its record may be written later - self._records_by_id[table_id] = read record, store_format = read if ( store_format == identity.STORE_FORMAT @@ -535,6 +540,14 @@ def _record_of( raise SpiralStoreTableCollisionError( f"it records path {list(record.path)}, whose table has another name" ) + if table is not None: + # Another format's key column is its own: one row of every column. + columns = ( + [codec.KEY_COLUMN] if store_format == identity.STORE_FORMAT else None + ) + if not _holds_rows(table, self._service_call, columns): + return None # never kept: its rows may be written later + self._records_by_id[table_id] = read return read # ── reading ────────────────────────────────────────────────────────────── @@ -719,7 +732,9 @@ def _unchanged_since_judged( if record is not None: identity.require_store_table_path(record, path) now = _seen_manifest(metadata, path) - return _same_seen(now, seen) and not _holds_rows(table, self._service_call) + return _same_seen(now, seen) and not _holds_rows( + table, self._service_call, [codec.KEY_COLUMN] + ) def _require_same_manifest( self, table: _KeyedTable, path: tuple[str, ...], manifest: codec.StoreManifest @@ -950,16 +965,19 @@ def _require_key( def _holds_rows( - table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] + table: _KeyedTable, + service_call: Callable[[str], AbstractContextManager[None]], + columns: list[str] | None, ) -> bool: """Whether a keyed table has a row. Args: table: The table. service_call: The store's ``service_call``. + columns: The columns of the one row read (``None`` for all of them). """ with service_call("read a key of a store table"): - keys = table.scan([codec.KEY_COLUMN], limit=1).to_table() + keys = table.scan(columns, limit=1).to_table() return keys.num_rows > 0 diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py index c572d95e8..0e9131d9a 100644 --- a/tests/test_databases/test_fake_spiral_sdk.py +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -64,5 +64,10 @@ def test_an_encoded_column_with_no_chunk_is_written_as_no_rows( ) rows = pa.Table.from_batches([], schema=schema) assert rows.column("v").num_chunks == 0 + writer = table.writer() + writer.append(rows) + (staged,) = writer._parts # pyright: ignore[reportPrivateUsage] + assert staged.num_rows == 0 + assert staged.schema.field("v").type == pa.string() # its values' type written = table.append(rows) assert written.scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 3139368aa..e63172411 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -32,10 +32,12 @@ from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.errors import ( InputValidationError, + OrcapodDatabaseReadError, SideEffectLogDataContextError, SpiralDBWriteNotSupportedError, ) from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource, DictSource from orcapod.types import CacheMode @@ -2013,3 +2015,112 @@ def call(*args: Any, **kwargs: Any) -> Any: with pytest.raises(DeprecationWarning, match="Keyed tables are deprecated"): _ = _table(identity.spiral_store_table_name(RESULT)) assert called.keys() == {"_open_keyed_table_by_id", "_create_keyed_table"} + + +class _CrashRecorder(NoOpObserver): + """Records every row an orchestrator reports as crashed.""" + + def __init__(self) -> None: + self.crashed: list[Exception] = [] + + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + self.crashed.append(error) + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_stored_table_a_lookup_cannot_read_fails_a_continue_run( + orchestrator: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read failure is the run's, never one row's, under ``error_policy="continue"``.""" + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + + def build() -> Any: + job = PipelineJob(name=JOB, database=ConnectorArrowDatabase(store())) + with job: + source = DictSource( + data=SOURCE_ROWS, + tag_columns=["k"], + tag_only_columns=True, + source_id="src", + ) + _ = double.pod(source, label="dbl") + return job + + _ = build().run(orchestrator=run[orchestrator](error_policy="continue")) + calls.clear() + + def unreadable(self: StoreTables, table_name: str) -> Iterator[pa.RecordBatch]: + raise RuntimeError("the service could not read the table") + + monkeypatch.setattr(StoreTables, "scan", unreadable) + observer = _CrashRecorder() + with pytest.raises(OrcapodDatabaseReadError) as raised: + _ = build().run( + orchestrator=run[orchestrator](error_policy="continue"), observer=observer + ) + assert isinstance(raised.value.__cause__, RuntimeError) + assert observer.crashed == [] and calls == [] + + +@pytest.mark.usefixtures("root") +def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Recorded, then its first append failed: no rows, so nothing stored there.""" + db = ConnectorArrowDatabase(store()) + + def failing(self: StoreTables, table: Any, found: Any, encoded: pa.Table) -> None: + raise RuntimeError("the append failed") + + with monkeypatch.context() as patched: + patched.setattr(StoreTables, "_append", failing) + with pytest.raises(Exception, match="the append failed"): + db.add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + assert identity.spiral_store_table_name(RESULT) in [t["name"] for t in _tables()] + fresh = ConnectorArrowDatabase(store()) + assert fresh.list_table_paths(("my_fn",)) == [] + assert tables_of_another_layout(fresh, ("my_fn",), result_revision="rev1") == [] + # Pending rows are listed; once written, the table is listed by its rows. + fresh.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + assert fresh.list_table_paths(("my_fn",)) == [RESULT] + fresh.flush() + assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [RESULT] + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_of_another_store_format_is_not_listed() -> None: + metadata = { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + } + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=False) + assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [] + + +@pytest.mark.usefixtures("root") +def test_the_commit_guard_is_given_the_recorded_schema_with_its_metadata() -> None: + """The schema check at the commit sees field metadata, as ``get_table_schema``.""" + + def with_metadata(table: pa.Table) -> pa.Table: + fields = [ + f.with_metadata({b"unit": b"mm"}) if f.name == "a.b" else f + for f in table.schema + ] + return table.cast(pa.schema(fields)) + + db = ConnectorArrowDatabase(store()) + _add(db, with_metadata(rows(["r0"])), flush=True) + _add(db, with_metadata(rows(["r1"], offset=1))) + seen: list[pa.Schema] = [] + with db.guard_table_schema(RESULT, seen.append): + db.flush() + assert len(seen) == 1 + assert seen[0].field("a.b").metadata == {b"unit": b"mm"} + recorded = db.get_table_schema(RESULT) + assert recorded is not None + assert seen[0].equals(recorded, check_metadata=True) diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index a32332ddd..b90e9e2a0 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -11,7 +11,7 @@ from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector from orcapod.databases._sql_store import STORE_PATH_CATALOG -from orcapod.errors import OrcapodDatabaseError +from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseReadError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo @@ -539,3 +539,26 @@ def test_catalog_operation_helper_rejects_unknown_operation() -> None: pa.table({"value": [1]}), "flsuh", ) + + +@pytest.mark.parametrize("read", ["by_id", "all"]) +def test_a_stored_table_the_connector_cannot_read_raises_a_read_error( + read: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failing read is ``OrcapodDatabaseReadError``, which fails a run (ITL-1840).""" + path = ("fn", "test") + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + db.add_record(path, b"r1", pa.table({"x": [1]}), flush=True) + + def unreadable(query: str, params: object = None, batch_size: int = 1000): + raise sqlite3.OperationalError("disk I/O error") + + monkeypatch.setattr(connector, "iter_batches", unreadable) + with pytest.raises(OrcapodDatabaseReadError) as raised: + if read == "by_id": + _ = db.get_record_by_id(path, b"r1") + else: + _ = db.get_all_records(path) + assert raised.value.record_path == path + assert isinstance(raised.value.__cause__, sqlite3.OperationalError) From 33afff09308b48f29e869435c6ff1745314370c7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:28:43 -0800 Subject: [PATCH 31/50] fix(spiraldb): review round 1 for the store switch-on (ITL-1844) - A full run leases every database its flushes may write: the node views, the job's database and every attachment whose failed flush it retries. - One unwrap of ExtensionAwareDatabase views, used by lease discovery and by the store-mode check of PipelineJob.load. - The lease key keeps the service address the client was made for. - Every lease release is attempted, also after one is interrupted. - The write boundary is stated precisely: a store connector that no run holds is refused, also during a run. - Changelog fragments of ITL-1837 and ITL-1840 describe the released store; docstrings no longer call store mode private. - The evaluation script succeeds only on the recorded outcomes; its warning filter is set in main(). - Tests compare native values and Arrow types, count source checks in a refused run, and release every test lease in teardown. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1837.md | 12 +- changelog.d/ITL-1840.md | 9 +- changelog.d/ITL-1844.md | 10 +- docs/concepts/spiraldb-store.md | 13 +- docs/dev/scripts/itl_1844_store_evaluation.py | 26 ++- .../databases/connector_arrow_database.py | 10 +- .../databases/extension_aware_database.py | 18 ++ src/orcapod/databases/spiraldb_connector.py | 5 +- .../databases/spiraldb_store_tables.py | 15 +- src/orcapod/databases/spiraldb_write_scope.py | 17 +- src/orcapod/pipeline/job.py | 10 +- src/orcapod/pipeline/serialization.py | 5 +- .../test_spiraldb_store_mode.py | 19 +- .../test_spiraldb_store_runs.py | 205 +++++++++++++++++- .../test_itl_1844_store_evaluation.py | 62 ++++++ 15 files changed, 391 insertions(+), 45 deletions(-) create mode 100644 tests/test_dev_scripts/test_itl_1844_store_evaluation.py diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md index 4fa7f484e..d79e1a377 100644 --- a/changelog.d/ITL-1837.md +++ b/changelog.d/ITL-1837.md @@ -4,13 +4,11 @@ and writes a SpiralDB table's own metadata. spiral-sdk 0.16.79 and later mark the keyed tables Orcapod reads as deprecated and warn on every open; Orcapod ignores that one warning for its own opens only, so a direct call to spiral-sdk still warns. The move to - spiral-sdk's newer table format is ITL-1846. Orcapod still only reads SpiralDB. - (ITL-1837) + spiral-sdk's newer table format is ITL-1846. (ITL-1837) ### Known limitations -- Orcapod cannot yet use SpiralDB as a job's database: `SpiralDBConnector` still refuses - every write. The groundwork for it (the encoding of a stored table's columns and the - identity record kept in a table's metadata) is internal and its format is provisional: - outside the 0.4.0 freeze, it may change before the store is offered, and tables written - in it may then need to be written again. (ITL-1837) +- The SpiralDB store's table format (the encoding of a stored table's columns and the + identity record kept in a table's metadata) is provisional: outside the 0.4.0 freeze, it + may change in a later version, and tables written in it may then need to be written + again. (ITL-1837) diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md index ff7af217c..6b07dbc09 100644 --- a/changelog.d/ITL-1840.md +++ b/changelog.d/ITL-1840.md @@ -1,7 +1,6 @@ ### Known limitations -- Orcapod still cannot use SpiralDB as a job's database: a `SpiralDBConnector` refuses - every write. An internal store mode now writes and reads every stored table kind - through `ConnectorArrowDatabase` (one table per path, its identity and manifest in the - table's metadata), but nothing opens it publicly, it is not saved with a job, and its - format stays provisional, outside the 0.4.0 freeze. (ITL-1840) +- A SpiralDB store (`SpiralDBConnector(..., store=True)`, ITL-1844) keeps every stored + table kind through `ConnectorArrowDatabase`: one table per path, its identity and + manifest in the table's metadata. Its format is provisional, outside the 0.4.0 freeze. + (ITL-1840) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index bb0054013..c97513f7e 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -16,10 +16,12 @@ ### Known limitations -- Only a job run writes a SpiralDB store: a write outside a run (a cached source read - outside a run, a `ConnectorArrowDatabase` flushed directly) raises - `SpiralDBStoreLeaseRequiredError`. A way to hold the lease outside a run is later work - (ITL-1849). +- Only a job run writes a SpiralDB store, through the store connectors it holds the lease + with: a write through any other store connector (a cached source read outside a run, a + `ConnectorArrowDatabase` over a connector of its own flushed directly) raises + `SpiralDBStoreLeaseRequiredError`, also while a run holds the lease. A write through a + running job's own databases from outside the run is not told apart from the run's own. + A way to hold the lease outside a run is later work (ITL-1849). - The writer lease is refuse-only: no waiting, no takeover, no expiry. Each run leaves one small lease table in the dataset, which is kept. - A store reads a table's whole key column to tell which rows it holds, and whole tables diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md index 86663f086..fd873031e 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-store.md @@ -63,10 +63,15 @@ except LeaseBusyError as refused: # SpiralDB dataset 'pipeline_results' has a conflicting writer lease (owner ..., table ID ...). ... ``` -Only a job run writes a store. A write anywhere else (a cached source read outside a -run, a `ConnectorArrowDatabase` flushed directly) raises -`SpiralDBStoreLeaseRequiredError` before anything is written. A load-only run of a job -writes no node's table, so it takes a lease only for a cached source it reads. +Only a job run writes a store, through the store connectors it holds the lease with +(those of its databases and of the cached sources it reads). A write through any other +store connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a +connector of its own flushed directly) raises `SpiralDBStoreLeaseRequiredError` before +anything is written, also while a run holds the dataset's lease. A write through a +running job's own databases from outside the run (another thread, an observer) is not +told apart from the run's own: do not write through them while the job runs. A +load-only run of a job writes no node's table, so it takes a lease only for a cached +source it reads. ### A lease left behind diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_store_evaluation.py index ef0bf189f..02587f641 100644 --- a/docs/dev/scripts/itl_1844_store_evaluation.py +++ b/docs/dev/scripts/itl_1844_store_evaluation.py @@ -57,7 +57,6 @@ from orcapod.sources import ArrowTableSource # noqa: E402 from orcapod.types import CacheMode # noqa: E402 -warnings.filterwarnings("ignore") VOLATILE = { "__data_id", @@ -275,7 +274,29 @@ def store() -> ConnectorArrowDatabase: "nothing_written": store().list_table_paths((fresh,)) == [], } - report["ok"] = all(v.get("ok", True) for v in s.values()) and refused + report["ok"] = succeeded(s) + + +def succeeded(scenarios: dict[str, Any]) -> bool: + """Every scenario as expected: tables as on Delta and the recorded outcomes. + + The first run computes all six rows; the new row is the only one computed and + delivered; the store flag is saved; a refused writer wrote nothing. + """ + first, new = scenarios.get("first run", {}), scenarios.get("new row", {}) + saved, second = ( + scenarios.get("save and load", {}), + scenarios.get("second writer", {}), + ) + return ( + all(v.get("ok", True) for v in scenarios.values()) + and first.get("calls_on_store") == 6 + and new.get("calls_on_store") == 1 + and new.get("delivered_on_store") == 1 + and saved.get("store_flag_saved") is True + and second.get("refused") is True + and second.get("nothing_written") is True + ) def store_tables(project: str, dataset: str, stamp: str) -> list[dict[str, str]]: @@ -325,6 +346,7 @@ def main() -> int: parser.add_argument("--project", default="p") parser.add_argument("--dataset", default="d") args = parser.parse_args() + warnings.filterwarnings("ignore") # the report is the output stamp = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%S") with tempfile.TemporaryDirectory() as tmp, contextlib.ExitStack() as stack: work = Path(tmp) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 06a14c1f4..ac5744034 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -223,10 +223,12 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. - A ``SpiralDBConnector`` opened in store mode (private, ITL-1840) is read and - written through its store tables (``spiraldb_store_tables``): names computed from - the full path, identity and manifest in each table's metadata, rows through the - store codec. A plain ``SpiralDBConnector`` refuses every write, as before. + A SpiralDB store, ``SpiralDBConnector(..., store=True)`` (provisional in 0.4.0), is + read and written through its store tables (``spiraldb_store_tables``): names + computed from the full path, identity and manifest in each table's metadata, rows + through the store codec. Its writes need the writer lease a job run holds + (``spiraldb_write_scope``). A plain ``SpiralDBConnector`` refuses every write, as + before. Args: connector: A ``DBConnectorProtocol`` implementation providing the diff --git a/src/orcapod/databases/extension_aware_database.py b/src/orcapod/databases/extension_aware_database.py index bbb891f2e..cdd34b130 100644 --- a/src/orcapod/databases/extension_aware_database.py +++ b/src/orcapod/databases/extension_aware_database.py @@ -333,3 +333,21 @@ def from_config(cls, config: dict[str, Any]) -> ExtensionAwareDatabase: "TypeConverterProtocol", cast(object, get_default_type_converter()) ) return cls(database, converter) + + +def unwrap_database_views(database: object) -> object: + """The database under every ``ExtensionAwareDatabase`` wrapping ``database``. + + The one unwrap of the library's database views, for code that must see the + backend: which SpiralDB connector a database writes through (its writer lease) and + in which mode (a saved job's binding). + + Args: + database: Any database, wrapped or not. + + Returns: + The innermost database; ``database`` itself when it is not wrapped. + """ + while isinstance(database, ExtensionAwareDatabase): + database = database._db # pyright: ignore[reportPrivateUsage] # the wrapper's backend + return database diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 16e8d6cbd..01debdb95 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1001,6 +1001,9 @@ def __init__( self._project_id = project_id self._dataset = dataset self._overrides = overrides + # The address the client is made for, kept for the writer-lease key: a later + # change to the caller's ``overrides`` must not move the lease to another service. + self._service_url = _api_url(overrides) self._closed = False # One client per service address and sign-in in the process (ITL-1457). shared = _client_for(overrides) @@ -1063,7 +1066,7 @@ def _store_tables(self) -> StoreTables | None: def _writer_lease_key(self) -> tuple[str | None, str, str]: """The dataset a writer lease is taken for: service address, project, dataset.""" - return (_api_url(self._overrides), self._project_id, self._dataset) + return (self._service_url, self._project_id, self._dataset) def _writer_lease_target(self) -> tuple[Any, str, str]: """What ``spiraldb_write_scope`` takes the writer lease with: the SDK client, diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index e49d03bc6..e53ccdf39 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -1,7 +1,7 @@ """The tables of a SpiralDB pipeline store, one dataset's (ITL-1840). -What ``ConnectorArrowDatabase`` does with the tables of a ``SpiralDBConnector`` opened in -store mode (a private constructor argument: nothing about the store is public yet). The +What ``ConnectorArrowDatabase`` does with the tables of a SpiralDB store, +``SpiralDBConnector(..., store=True)`` (public and provisional in 0.4.0, ITL-1844). The design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried from PR 595 onto ``main``'s database structure. @@ -665,6 +665,11 @@ def let_go_of_lease(self, check: Callable[[], None]) -> None: def _require_lease(self) -> None: """Refuse a write unless a run holds the dataset's writer lease, and check it. + The lease is held by the store connectors of the run that took it: a write + through any other connector to the dataset is refused, also while that run + holds the lease. A write through the run's own connectors is the run's (its + databases, its cached sources); the lease does not tell its callers apart. + Raises: SpiralDBStoreLeaseRequiredError: If no run holds the lease. LeaseError: If the lease is no longer held (``spiraldb_lease.check``). @@ -672,10 +677,10 @@ def _require_lease(self) -> None: check = self._lease_check if check is None: raise SpiralDBStoreLeaseRequiredError( - f"no job run holds the writer lease of SpiralDB dataset " + f"this SpiralDB store connector holds no writer lease of dataset " f"{self._project_id}/{self._dataset}: a SpiralDB store is written only " - "within a job run (job.run(), job.run_async() or a job node's run()), " - "which takes the lease; nothing was written" + "through the connectors of a job run (job.run(), job.run_async() or a " + "job node's run()), which takes the lease; nothing was written" ) check() diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index ce1811c0f..07bbf07ed 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -29,15 +29,20 @@ def store_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: """The distinct SpiralDB store connectors under ``databases``, in the order met. Args: - databases: Databases a run may write; ``None`` entries are skipped. + databases: Databases a run may write, through ``ExtensionAwareDatabase`` + views too; ``None`` entries are skipped. Returns: Each store connector once (by object). """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.extension_aware_database import unwrap_database_views found: list[SpiralDBConnector] = [] - for database in databases: + for given in databases: + database = unwrap_database_views( + given + ) # a store under a library view is leased too if not isinstance(database, ConnectorArrowDatabase): continue connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the store's connector, read by the one module that leases it @@ -52,8 +57,10 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: Every lease is acquired before the body runs; a refused one releases those already taken and raises. Each lease is released when the body ends, also when it raises - (or is cancelled or interrupted). A release that fails after the body raised is - added as a note to the body's error; after a body that succeeded it raises. + (or is cancelled or interrupted). Every release is attempted, also after one fails + or is interrupted. A release that fails after the body raised is added as a note to + the body's error; after a body that succeeded the first failure (an interruption + included) raises. Args: databases: The databases the run may write. Nothing happens when none is a @@ -143,7 +150,7 @@ def _release_all( _tables(connector).let_go_of_lease(check) try: release() - except Exception as exc: # noqa: BLE001 # every lease is released; failures are reported below + except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below if error is not None: error.add_note( f"Releasing the SpiralDB writer lease also failed: {exc}" diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index a487d2605..b3e7e251a 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1785,7 +1785,15 @@ def _prepare_run( store_write_scope( list(exec_dag.nodes()), load_only=load_only, - databases=(pipeline_db, result_db), + # Every database a full run's flushes may write: its own, the + # node views and the attachments whose failed flush it retries. + databases=( + pipeline_db, + result_db, + *self._node_database_views, + self._database, + *(r.database for r in self._retry_attachment_flushes.values()), + ), owner=run_owner("/".join(self._name)), ) ) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index f7361d4ab..4ae9462f0 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -581,16 +581,19 @@ def spiraldb_store_mismatch(config: Any, given: Any) -> str | None: Args: config: The saved database configuration. - given: The database given to ``PipelineJob.load``. + given: The database given to ``PipelineJob.load``, wrapped in library views + (``ExtensionAwareDatabase``) or not. Returns: The reason, or ``None`` when they agree or either is not a SpiralDB database. """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase + from orcapod.databases.extension_aware_database import unwrap_database_views from orcapod.databases.spiraldb_connector import SpiralDBConnector if saved_connector_kind(config) != "spiraldb": return None + given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index d21cce767..45098d52d 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -52,9 +52,22 @@ def root(tmp_path: Path) -> Iterator[Path]: try: yield tmp_path finally: - for _, release in _test_leases.values(): - release() - _test_leases.clear() + _release_test_leases() + + +def _release_test_leases() -> None: + """Release every test lease, each attempted, and forget them all; then raise the + first failed release, so a later test never inherits a lease of this one.""" + leases = list(_test_leases.values()) + _test_leases.clear() + failure: BaseException | None = None + for _, release in leases: + try: + release() + except BaseException as exc: # noqa: BLE001 # every lease is released; the first failure is raised below + failure = failure or exc + if failure is not None: + raise failure def store( diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index e38275ce1..7d646c07b 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -27,11 +27,14 @@ DeltaTableDatabase, SpiralDBConnector, ) +from orcapod.contexts import get_default_context from orcapod.databases import spiraldb_lease -from orcapod.databases.spiraldb_write_scope import take_lease +from orcapod.databases.extension_aware_database import ExtensionAwareDatabase +from orcapod.databases.spiraldb_write_scope import store_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import SpiralDBStoreLeaseRequiredError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource from orcapod.types import CacheMode @@ -159,12 +162,20 @@ def _lease_tables(dataset: str = "d") -> list[str]: def _comparable(table: pa.Table) -> list[tuple[Any, ...]]: + """The rows, apart from the volatile columns, as native values in no row order + (sorted by their repr, so a null is never taken for the text ``"None"``).""" kept = [c for c in sorted(table.column_names) if c not in VOLATILE] return sorted( - (tuple(str(row[c]) for c in kept) for row in table.select(kept).to_pylist()) + (tuple(row[c] for c in kept) for row in table.select(kept).to_pylist()), + key=repr, ) +def _types(table: pa.Table) -> dict[str, pa.DataType]: + """The Arrow type of every column apart from the volatile ones.""" + return {f.name: f.type for f in table.schema if f.name not in VOLATILE} + + def _same_tables(store: Any, delta: Any) -> None: """Same paths, and in each the same rows, apart from the volatile columns.""" paths = sorted(store.list_table_paths()) @@ -174,6 +185,7 @@ def _same_tables(store: Any, delta: Any) -> None: on_delta = delta.get_all_records(path) assert on_store is not None and on_delta is not None, path assert on_store.schema.names == on_delta.schema.names, path + assert _types(on_store) == _types(on_delta), path assert _comparable(on_store) == _comparable(on_delta), path @@ -349,6 +361,21 @@ def test_the_store_flag_is_saved_without_credentials() -> None: # ------------------------------------------------------------------ the lease +def _count_source_checks(job: PipelineJob) -> list[None]: + """Record each ``check_for_new_data`` of the source the job holds for its slot.""" + source = job.nodes["trials"].bound_source + assert source is not None + checks: list[None] = [] + check = source.check_for_new_data + + def counted() -> bool: + checks.append(None) + return check() + + source.check_for_new_data = counted # pyright: ignore[reportAttributeAccessIssue] # counted on the instance the job holds + return checks + + def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: """Hold the dataset's lease as another writer would; returns its release.""" _, release = take_lease( @@ -365,15 +392,19 @@ def test_a_second_writer_is_refused_before_anything( ) -> None: release = _held_by_another_writer() job = _job(_store()) + checks = _count_source_checks(job) with pytest.raises(spiraldb_lease.LeaseBusyError, match="another writer"): _ = _run(job, entry, load_only=load_only) assert _store_tables() == [] assert calls == [] and delivered == [] + # Refused before any source was checked (a cached source writes its cache then). + assert checks == [] # Once the other writer releases, the run goes ahead. release() if not load_only: _ = _run(job, entry) assert len(calls) == 3 + assert checks != [] # the counter sees the checks a run makes @pytest.mark.usefixtures("root") @@ -460,7 +491,7 @@ def failing(client: Any, lease: Any) -> None: @pytest.mark.usefixtures("root") def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: store = _store() - with pytest.raises(SpiralDBStoreLeaseRequiredError, match="within a job run"): + with pytest.raises(SpiralDBStoreLeaseRequiredError, match="through the connectors of a job run"): _ = _cached(store, _rows()).as_table() store.add_records( ("t", "rdb_v1"), @@ -515,3 +546,171 @@ def test_the_lease_raises_no_keyed_table_deprecation() -> None: # The SDK itself still warns on an open Orcapod did not make. with pytest.warns(DeprecationWarning, match="Keyed tables are deprecated"): _ = fake.FakeClient().keyed_table("p", "d", _lease_tables()[0]) + + +# ------------------------------------------------ review round 1 (CodeRabbit, #693) + + +@pytest.mark.usefixtures("root") +def test_a_retried_attachment_flush_runs_under_its_dataset_lease() -> None: + """An attachment whose flush failed is retried by the next run, also after the node + was attached elsewhere; that run leases the old attachment's dataset too.""" + job = _job(_store()) + old = _store("a").at(JOB) + job.nodes["select"].attach_databases( + pipeline_database=old, cache_mode=CacheMode.LOG + ) + flush = old.flush + failures: list[None] = [] + + def failing_once() -> None: + if not failures: + failures.append(None) + raise RuntimeError("flush lost") + flush() + + old.flush = failing_once # pyright: ignore[reportAttributeAccessIssue] # this attachment's flush fails once + with pytest.raises(Exception, match="flush lost"): + _ = job.run() + assert _store_tables("a") == [] + job.nodes["select"].attach_databases( + pipeline_database=_store("b").at(JOB), cache_mode=CacheMode.LOG + ) + _ = job.run() + # The retry wrote the old attachment's operator cache, under a lease of its dataset. + assert [p[-1] for p in _store("a").list_table_paths()] == ["odb_v3"] + assert len(_lease_tables("a")) == 2 + + +def _wrapped(database: Any) -> ExtensionAwareDatabase: + """``database`` under the library's extension-aware view.""" + converter = get_default_context().type_converter + assert isinstance(converter, UniversalTypeConverter) + return ExtensionAwareDatabase(database, converter) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize(("saved_store", "given_store"), [(True, False), (False, True)]) +def test_load_refuses_a_wrapped_spiraldb_connector_of_the_other_kind( + root: Path, saved_store: bool, given_store: bool +) -> None: + """The mode check sees through an ``ExtensionAwareDatabase`` view.""" + saved = root / "job.json" + if saved_store: + _job(_store()).save(saved) + else: + _job(DeltaTableDatabase(root / "delta")).save(saved) + data = json.loads(saved.read_text()) + data["bindings"]["database"] = ConnectorArrowDatabase( + SpiralDBConnector("p", "d") + ).to_config() + saved.write_text(json.dumps(data)) + given = _wrapped( + ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=given_store)) + ) + with pytest.raises(ValueError, match="bindings.database.*store"): + _ = PipelineJob.load(saved, database=given) + + +@pytest.mark.usefixtures("root") +def test_a_wrapped_store_of_the_same_kind_loads(root: Path) -> None: + saved = root / "job.json" + _ = _job(_store()).run() + _job(_store()).save(saved) + loaded = PipelineJob.load(saved, database=_wrapped(_store())) + assert loaded.nodes["combine"].as_source().as_table().num_rows == 3 + + +@pytest.mark.usefixtures("root") +def test_a_job_on_a_wrapped_store_holds_its_lease_and_stores_as_on_delta( + root: Path, +) -> None: + """Lease discovery sees a store under an ``ExtensionAwareDatabase`` view: the run + takes the dataset's lease, writes every table kind, and a second writer waits on it.""" + store = _store() + delta = DeltaTableDatabase(root / "delta") + _ = _job(_wrapped(store)).run() + _ = _job(delta).run() + assert len(_lease_tables()) == 1 + _same_tables(store, delta) + release = _held_by_another_writer() + with pytest.raises(spiraldb_lease.LeaseBusyError): + _ = _job(_wrapped(_store())).run() + release() + + +@pytest.mark.usefixtures("root") +def test_the_lease_key_keeps_the_service_address_of_construction() -> None: + """Changing the caller's overrides after construction moves neither the client nor + the lease to another service.""" + overrides = {"server.url": "https://one.example"} + connector = SpiralDBConnector("p", "d", store=True, overrides=overrides) + key = connector._writer_lease_key() # pyright: ignore[reportPrivateUsage] + overrides["server.url"] = "https://two.example" + assert connector._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] + assert key[0] == "https://one.example" + + +@pytest.mark.usefixtures("root") +def test_a_write_through_another_connector_during_a_run_is_refused() -> None: + """While a run holds the dataset's lease, a store connector of its own (not one the + run holds) is still refused, and writes nothing.""" + seen: list[BaseException] = [] + + @function_pod(output_keys="z") + def write_elsewhere(x: int) -> int: + other = ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=True)) + row = pa.table( + { + "__data_context": pa.array(["std:v1:default"], pa.large_string()), + "v": pa.array([x], pa.int64()), + } + ) + other.add_record(("elsewhere",), b"r", row, flush=False) + try: + other.flush() + except SpiralDBStoreLeaseRequiredError as exc: + seen.append(exc) + return x + + store = _store() + job = PipelineJob(name=JOB, database=store) + with job: + write_elsewhere.pod(_cached(store, _rows()).select_data_columns(["x"])) + _ = job.run() + assert len(seen) == 3 + assert _store().list_table_paths(("elsewhere",)) == [] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("body_fails", [False, True]) +def test_an_interrupted_release_still_releases_every_other_lease( + monkeypatch: pytest.MonkeyPatch, body_fails: bool +) -> None: + """A release interrupted (KeyboardInterrupt) does not skip the other leases; after a + successful body it is raised, after a failed one it is a note on the body's error.""" + real = spiraldb_lease.release + interrupted: list[None] = [] + + def interrupt_first(client: Any, lease: Any) -> None: + if not interrupted: + interrupted.append(None) + raise KeyboardInterrupt + real(client, lease) + + monkeypatch.setattr(spiraldb_lease, "release", interrupt_first) + databases = [_store("d"), _store("r")] + if body_fails: + with pytest.raises(RuntimeError, match="body") as raised: + with store_writes(databases, owner="test"): + raise RuntimeError("body") + assert any("also failed" in n for n in getattr(raised.value, "__notes__", [])) + else: + with pytest.raises(KeyboardInterrupt): + with store_writes(databases, owner="test"): + pass + monkeypatch.undo() + # The lease released after the interruption (the first one taken, released last + # in reverse order) can be taken again. + _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") + again() diff --git a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py new file mode 100644 index 000000000..65c39fa10 --- /dev/null +++ b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py @@ -0,0 +1,62 @@ +"""The ITL-1844 store evaluation script reports success only for the expected outcomes.""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +from types import ModuleType +from typing import Any + +import pytest + +_SCRIPT = ( + Path(__file__).parents[2] + / "docs" + / "dev" + / "scripts" + / "itl_1844_store_evaluation.py" +) + + +@pytest.fixture(scope="module") +def script() -> ModuleType: + spec = importlib.util.spec_from_file_location("itl_1844_store_evaluation", _SCRIPT) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def _expected() -> dict[str, dict[str, Any]]: + return { + "first run": {"ok": True, "calls_on_store": 6}, + "new row": {"ok": True, "calls_on_store": 1, "delivered_on_store": 1}, + "replay": {"ok": True}, + "save and load": {"ok": True, "store_flag_saved": True}, + "second writer": {"refused": True, "nothing_written": True}, + } + + +def test_the_expected_outcomes_succeed(script: ModuleType) -> None: + assert script.succeeded(_expected()) + + +@pytest.mark.parametrize( + ("scenario", "key", "value"), + [ + ("first run", "calls_on_store", 5), + ("new row", "calls_on_store", 7), + ("new row", "delivered_on_store", 7), + ("save and load", "store_flag_saved", False), + ("second writer", "refused", False), + ("second writer", "nothing_written", False), + ("replay", "ok", False), + ], +) +def test_a_wrong_recorded_outcome_fails( + script: ModuleType, scenario: str, key: str, value: object +) -> None: + """Tables that match Delta do not make up for a wrong count or flag.""" + scenarios = _expected() + scenarios[scenario][key] = value + assert not script.succeeded(scenarios) From 26a0faa4356396190f1429eb8b72821605140d67 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:45:11 -0800 Subject: [PATCH 32/50] test(spiraldb): stage B's read-failure test lets the job take its lease; a release whose reopen fails after a run raises LeaseError (ITL-1844) Co-Authored-By: Claude Opus 5.5 --- .../test_spiraldb_store_mode.py | 2 +- .../test_spiraldb_store_runs.py | 32 +++++++++++++++++-- 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index 044e4d125..79a36ba3c 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -2074,7 +2074,7 @@ def test_a_stored_table_a_lookup_cannot_read_fails_a_continue_run( run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} def build() -> Any: - job = PipelineJob(name=JOB, database=ConnectorArrowDatabase(store())) + job = PipelineJob(name=JOB, database=ConnectorArrowDatabase(store(held=False))) with job: source = DictSource( data=SOURCE_ROWS, diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index 7d646c07b..363b7fea2 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -28,7 +28,7 @@ SpiralDBConnector, ) from orcapod.contexts import get_default_context -from orcapod.databases import spiraldb_lease +from orcapod.databases import spiraldb_connector, spiraldb_lease from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.spiraldb_write_scope import store_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name @@ -467,6 +467,32 @@ def failing(client: Any, lease: Any) -> None: _same_tables(fresh, delta) +@pytest.mark.usefixtures("root") +def test_a_release_whose_reopen_fails_after_a_run_raises_lease_error( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The service fails while the release reopens the lease table: the run raises + ``LeaseError`` (not the SDK's error), and its tables are complete.""" + real_release = spiraldb_lease.release + + def release_with_reopen_lost(client: Any, lease: Any) -> None: + def lost(*args: Any, **kwargs: Any) -> Any: + raise TimeoutError("the service did not answer") + + with monkeypatch.context() as patch: + patch.setattr(spiraldb_connector, "_open_keyed_table_by_id", lost) + real_release(client, lease) + + monkeypatch.setattr(spiraldb_lease, "release", release_with_reopen_lost) + with pytest.raises(spiraldb_lease.LeaseError) as raised: + _ = _job(_store()).run() + assert isinstance(raised.value.__cause__, TimeoutError) + monkeypatch.undo() + delta = DeltaTableDatabase(root / "delta") + _ = _job(delta).run() + _same_tables(_store(), delta) + + @pytest.mark.usefixtures("root") def test_a_failed_release_after_a_failed_run_is_noted_on_its_error( monkeypatch: pytest.MonkeyPatch, @@ -491,7 +517,9 @@ def failing(client: Any, lease: Any) -> None: @pytest.mark.usefixtures("root") def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: store = _store() - with pytest.raises(SpiralDBStoreLeaseRequiredError, match="through the connectors of a job run"): + with pytest.raises( + SpiralDBStoreLeaseRequiredError, match="through the connectors of a job run" + ): _ = _cached(store, _rows()).as_table() store.add_records( ("t", "rdb_v1"), From 291798da38c28c8b870ff90804ab5e96661f961c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 19:30:07 -0800 Subject: [PATCH 33/50] perf(spiraldb): a run walks for store leases only when a store connector exists, once per node; a release interruption raises after a failed run (ITL-1844) The lease scope of every run walked the whole graph again for each node, with list membership and concatenation (0.19 s at 401 nodes), also on jobs with no SpiralDB store. A store connector now registers itself in a process-wide weak set; with none, the scope holds nothing and walks nothing. The walk itself is one pass with id-keyed visited sets. An interruption of a lease release after a run that failed with an error is raised (chained from the run's error) once every release was attempted, instead of becoming a note on the run's error. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_connector.py | 3 + .../databases/spiraldb_store_registry.py | 32 +++++ src/orcapod/databases/spiraldb_write_scope.py | 24 +++- src/orcapod/pipeline/node_run.py | 86 ++++++++++---- .../test_spiraldb_store_runs.py | 110 +++++++++++++++++- 5 files changed, 220 insertions(+), 35 deletions(-) create mode 100644 src/orcapod/databases/spiraldb_store_registry.py diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 01debdb95..f56728845 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,6 +49,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_store_registry import register_store_connector from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( @@ -1028,6 +1029,8 @@ def __init__( self._store_mode = store self._store: StoreTables | None = None if store: + # A run looks for store leases only while a store connector exists. + register_store_connector(self) self._store = StoreTables( sp, project_id, diff --git a/src/orcapod/databases/spiraldb_store_registry.py b/src/orcapod/databases/spiraldb_store_registry.py new file mode 100644 index 000000000..b3f3e0251 --- /dev/null +++ b/src/orcapod/databases/spiraldb_store_registry.py @@ -0,0 +1,32 @@ +"""Which SpiralDB store connectors exist in this process (ITL-1844). + +A run takes the writer lease of every SpiralDB store it may write +(``spiraldb_write_scope.store_writes``), found by walking the run's graph. A store +database always holds its store connector, so when no store connector exists in the +process no run can write a store, and the run skips the walk (``any_store_connector``). +This module is a leaf: checking it imports nothing of SpiralDB. +""" + +from __future__ import annotations + +from weakref import WeakSet + +_store_connectors: WeakSet[object] = WeakSet() + + +def register_store_connector(connector: object) -> None: + """Record a store connector, for as long as it exists. + + Args: + connector: A ``SpiralDBConnector`` made with ``store=True``. + """ + _store_connectors.add(connector) + + +def any_store_connector() -> bool: + """Whether any SpiralDB store connector exists in this process (closed ones too). + + Returns: + ``False`` only when no run can hold a SpiralDB store database. + """ + return len(_store_connectors) > 0 diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 07bbf07ed..2d8642c11 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -58,9 +58,12 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: Every lease is acquired before the body runs; a refused one releases those already taken and raises. Each lease is released when the body ends, also when it raises (or is cancelled or interrupted). Every release is attempted, also after one fails - or is interrupted. A release that fails after the body raised is added as a note to - the body's error; after a body that succeeded the first failure (an interruption - included) raises. + or is interrupted. An interruption of a release (``KeyboardInterrupt``, + ``CancelledError``, ``SystemExit``) is never swallowed: it raises once every release + was attempted, after a body that raised too (chained from the body's error, which + is its ``__cause__``). A release that fails with an error after the body raised is + added as a note to the body's error; after a body that succeeded the first failure + raises. Args: databases: The databases the run may write. Nothing happens when none is a @@ -140,8 +143,12 @@ def _release_all( Args: held: The leases taken, with their connectors. - error: The body's error, which a failed release is noted on; ``None`` when the - body succeeded, and the first failed release then raises. + error: The body's error, which a release failing with an error is noted on; + ``None`` when the body succeeded, and the first failed release then raises. + + Raises: + BaseException: The first interruption of a release (chained from the body's + error, if any), or after a successful body the first failed release. """ failure: BaseException | None = None for connectors, check, release in reversed(held): @@ -151,7 +158,8 @@ def _release_all( try: release() except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below - if error is not None: + interrupted = not isinstance(exc, Exception) + if error is not None and not (interrupted and isinstance(error, Exception)): error.add_note( f"Releasing the SpiralDB writer lease also failed: {exc}" ) @@ -162,4 +170,8 @@ def _release_all( f"Releasing another SpiralDB writer lease failed: {exc}" ) if failure is not None: + if error is not None: + # An interruption of a release after a body that failed with an error: + # the interruption stops the program, with the body's error as its cause. + raise failure from error raise failure diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index c5576750f..d056ac55a 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -14,7 +14,10 @@ from __future__ import annotations +import contextlib +from collections import deque from collections.abc import Iterable, Iterator, Mapping, Sequence +from contextlib import AbstractContextManager from dataclasses import dataclass from typing import TYPE_CHECKING, Any @@ -132,7 +135,7 @@ def refuse_unloadable_inputs(node: Any) -> None: ) -def _databases(nodes: list[Any]) -> list[ArrowDatabaseProtocol]: +def _databases(nodes: Iterable[Any]) -> list[ArrowDatabaseProtocol]: """The distinct databases the given nodes write to, each node's results first. A function node's result database comes before its pipeline database, so the @@ -140,12 +143,14 @@ def _databases(nodes: list[Any]) -> list[ArrowDatabaseProtocol]: also when the results are in a separate database (ITL-1408). """ found: list[ArrowDatabaseProtocol] = [] + seen: set[int] = set() for node in nodes: pipeline_database = getattr(node, "_pipeline_database", None) cached_pod = getattr(node, "_cached_function_pod", None) result_database = getattr(cached_pod, "result_database", None) for database in (result_database, pipeline_database): - if database is not None and not any(database is d for d in found): + if database is not None and id(database) not in seen: + seen.add(id(database)) found.append(database) return found @@ -213,18 +218,20 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: def _cache_databases(streams: Iterable[Any]) -> list[Any]: """The databases of every ``CachedSource`` feeding ``streams`` (a cached source writes its cache when it is checked or read), through wrapped sources and streams. + + Each stream is visited once (linear in the size of the graph). """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource found: list[Any] = [] - visited: list[Any] = [] - pending = list(streams) + visited: set[int] = set() + pending = deque(streams) while pending: - stream = pending.pop(0) - if any(stream is seen for seen in visited): + stream = pending.popleft() + if id(stream) in visited: continue - visited.append(stream) + visited.add(id(stream)) if isinstance(stream, SourceJobNode): if stream.bound_source is not None: pending.append(stream.bound_source) @@ -237,34 +244,66 @@ def _cache_databases(streams: Iterable[Any]) -> list[Any]: return found -def _job_nodes_under(target: Any) -> list[Any]: - """``target`` and every job node it depends on.""" +def _job_nodes_under(targets: Iterable[Any]) -> list[Any]: + """Every job node among ``targets`` and the job nodes they depend on, once each. + + One walk shared by all targets (linear in the size of the graph). + """ found: list[Any] = [] - pending = [target] + visited: set[int] = set() + pending = list(targets) while pending: node = pending.pop() - if any(node is seen for seen in found) or not _is_job_node(node): + if id(node) in visited: + continue + visited.add(id(node)) + if not _is_job_node(node): continue found.append(node) pending.extend(getattr(node, "upstreams", ())) return found +def store_scope_databases( + streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = () +) -> list[Any]: + """The databases a run may write, for its writer leases (``store_write_scope``). + + A full run may write ``databases`` (a job's database and result database), the + databases of the job nodes in ``streams`` and of every job node they depend on, and + the cache of every ``CachedSource`` feeding them. A load-only run writes none of + the nodes' databases; it may still write a cached source's cache, which takes in + new rows when checked or read. Each node is visited once. + + Args: + streams: The nodes of the run, or the node whose ``run()`` it is. + load_only: Whether the run is load-only. + databases: The job's own databases, for a full run. + + Returns: + The databases, in the order met (repeats are left to ``store_writes``). + """ + written: list[Any] = [] + if not load_only: + written.extend(databases) + written.extend(_databases(_job_nodes_under(streams))) + written.extend(_cache_databases(streams)) + return written + + def store_write_scope( streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = (), owner: str | None = None, -) -> Any: +) -> AbstractContextManager[None]: """The writer leases a run holds on the SpiralDB stores it may write (ITL-1844). - A full run may write ``databases`` (a job's database and result database), the - databases of the job nodes in ``streams`` and of every job node they depend on, and - the cache of every ``CachedSource`` feeding them. A load-only run writes none of - the nodes' databases; it may still write a cached source's cache, which takes in - new rows when checked or read. Entered before the run checks its sources - (``spiraldb_write_scope.store_writes``). + The run may write the databases ``store_scope_databases`` lists. Entered before the + run checks its sources (``spiraldb_write_scope.store_writes``). When no SpiralDB + store connector exists in the process, no run can write a store: nothing is walked + and the scope holds nothing. Args: streams: The nodes of the run, or the node whose ``run()`` it is. @@ -276,14 +315,13 @@ def store_write_scope( Returns: The context manager that holds the leases. """ + from orcapod.databases.spiraldb_store_registry import any_store_connector + + if not any_store_connector(): + return contextlib.nullcontext() from orcapod.databases.spiraldb_write_scope import store_writes - written: list[Any] = [] - if not load_only: - written.extend(databases) - nodes = [n for stream in streams for n in _job_nodes_under(stream)] - written.extend(_databases(nodes)) - written.extend(_cache_databases(streams)) + written = store_scope_databases(streams, load_only=load_only, databases=databases) if owner is None: owner = run_owner(_job_name(streams[0]) if streams else "") return store_writes(written, owner=owner) diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index 363b7fea2..47581667e 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -12,6 +12,7 @@ import asyncio import json import warnings +import weakref from collections.abc import Callable, Iterator from pathlib import Path from typing import Any @@ -25,15 +26,22 @@ from orcapod.databases import ( ConnectorArrowDatabase, DeltaTableDatabase, + InMemoryArrowDatabase, SpiralDBConnector, ) from orcapod.contexts import get_default_context -from orcapod.databases import spiraldb_connector, spiraldb_lease +from orcapod.databases import ( + spiraldb_connector, + spiraldb_lease, + spiraldb_store_registry, + spiraldb_write_scope, +) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase from orcapod.databases.spiraldb_write_scope import store_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import SpiralDBStoreLeaseRequiredError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline import node_run from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource @@ -715,8 +723,9 @@ def write_elsewhere(x: int) -> int: def test_an_interrupted_release_still_releases_every_other_lease( monkeypatch: pytest.MonkeyPatch, body_fails: bool ) -> None: - """A release interrupted (KeyboardInterrupt) does not skip the other leases; after a - successful body it is raised, after a failed one it is a note on the body's error.""" + """A release interrupted (KeyboardInterrupt) does not skip the other leases, and the + interruption raises once every release was attempted: after a failed body too, + chained from the body's error (never only a note on it).""" real = spiraldb_lease.release interrupted: list[None] = [] @@ -729,10 +738,11 @@ def interrupt_first(client: Any, lease: Any) -> None: monkeypatch.setattr(spiraldb_lease, "release", interrupt_first) databases = [_store("d"), _store("r")] if body_fails: - with pytest.raises(RuntimeError, match="body") as raised: + with pytest.raises(KeyboardInterrupt) as raised: with store_writes(databases, owner="test"): raise RuntimeError("body") - assert any("also failed" in n for n in getattr(raised.value, "__notes__", [])) + cause = raised.value.__cause__ + assert isinstance(cause, RuntimeError) and str(cause) == "body" else: with pytest.raises(KeyboardInterrupt): with store_writes(databases, owner="test"): @@ -742,3 +752,93 @@ def interrupt_first(client: Any, lease: Any) -> None: # in reverse order) can be taken again. _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") again() + + +def test_a_job_with_no_store_connector_in_the_process_takes_no_lease_and_walks_nothing( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """With no SpiralDB store connector in the process, a run builds no lease scope and + walks no graph for one: every entry (sync, async, node run, load-only) on a job with + a cached source, a function node, a logged operator node and a sink.""" + monkeypatch.setattr(spiraldb_store_registry, "_store_connectors", weakref.WeakSet()) + walks: list[None] = [] + real_walk = node_run.store_scope_databases + + def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: + walks.append(None) + return real_walk(*args, **kwargs) + + def no_lease(*args: Any, **kwargs: Any) -> Any: + raise AssertionError("a lease scope was built") + + monkeypatch.setattr(node_run, "store_scope_databases", counting_walk) + monkeypatch.setattr(spiraldb_write_scope, "store_writes", no_lease) + calls.clear() + delivered.clear() + job = _job(InMemoryArrowDatabase()) + assert job.run().ok + job.run(orchestrator=AsyncPipelineOrchestrator()) + asyncio.run(job.run_async()) + job.nodes["select"].clear_cache() + job.nodes["select"].run() + job.run(load_only=True) + assert walks == [] + assert calls != [] + + +def test_a_store_connector_in_the_process_makes_the_run_walk_for_leases( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The early return is only for a process without a store connector: with one, the + run walks its graph (and takes the store's lease, as the other tests show).""" + walks: list[None] = [] + real_walk = node_run.store_scope_databases + + def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: + walks.append(None) + return real_walk(*args, **kwargs) + + monkeypatch.setattr(node_run, "store_scope_databases", counting_walk) + store = _store() + assert spiraldb_store_registry.any_store_connector() + _ = _job(store).run() + assert len(walks) == 1 + assert len(_lease_tables()) == 1 + + +def _select_chain(n: int, database: Any) -> PipelineJob: + job = PipelineJob(name="chain", database=database) + with job: + stream: Any = ArrowTableSource( + _rows(), tag_columns=["unit", "trial"], tag_only_columns=True, source_id="t" + ) + for i in range(n): + names = ["x", "y"] if i % 2 == 0 else ["y", "x"] + stream = SelectDataColumns(names)(stream, label=f"s{i}") + return job + + +@pytest.mark.parametrize("load_only", [False, True]) +def test_the_lease_walk_visits_each_node_a_bounded_number_of_times( + monkeypatch: pytest.MonkeyPatch, load_only: bool +) -> None: + """The walk for a run's leases is linear in the graph: its attribute reads per node + stay the same from a 51-node chain to a 401-node one (it was quadratic).""" + + def reads_per_node(n: int) -> float: + job = _select_chain(n, InMemoryArrowDatabase()) + job.run() + nodes = list(job.nodes.values()) + counted: list[None] = [] + + def counting_getattr(obj: Any, name: str, *default: Any) -> Any: + counted.append(None) + return getattr(obj, name, *default) + + with monkeypatch.context() as patch: + patch.setattr(node_run, "getattr", counting_getattr, raising=False) + node_run.store_scope_databases(nodes, load_only=load_only) + return len(counted) / len(nodes) + + small, large = reads_per_node(50), reads_per_node(400) + assert large <= small * 1.1 + 0.5 From edc30710da760ab1dadcd94466dabcc2cfa76d2f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:20:30 -0800 Subject: [PATCH 34/50] fix(spiraldb): finding a stored table is a read; a changed identity record is never recorded over; an empty store format is malformed (ITL-1840) - _get_committed_table covers finding the table as well as scanning it: a failure becomes OrcapodDatabaseReadError on every connector, as in get_table_schema; an invalid path and a table collision keep their own errors. - A first write over an empty table also compares the identity record its judgment saw; a record changed since goes through the manifest and data-context checks. - A record naming an empty store format refuses the listing. - Docs: the no-overwrite claim covers keys the write's fresh key read shows; the plan states the read-error change for plain connectors; SDK protocol docstrings. - Tests: the peer judgment's outcome is checked; the snapshot test asserts every table kind it compares. Co-Authored-By: Claude Opus 5.5 --- ...026-12-01-itl-1840-spiral-store-stage-b.md | 8 +- .../databases/connector_arrow_database.py | 37 ++++--- .../databases/spiral_store_identity.py | 4 +- .../databases/spiraldb_store_tables.py | 67 ++++++++---- .../test_spiraldb_store_mode.py | 102 +++++++++++++++++- 5 files changed, 182 insertions(+), 36 deletions(-) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md index ff84df73c..af817cf75 100644 --- a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -30,7 +30,13 @@ refuses every write (`SpiralDBWriteNotSupportedError`). is a store-mode `SpiralDBConnector`. `DBConnectorProtocol` is unchanged. The branch is taken only for a store-mode connector. For every other connector, the -plain `SpiralDBConnector` included, the code paths are `main`'s. +plain `SpiralDBConnector` included, the code paths are `main`'s, with one exception: a +lookup of committed rows (`get_record_by_id`, `get_all_records` and the reads built on +them) now raises `OrcapodDatabaseReadError` on every connector when finding or reading +the stored table fails, as `get_table_schema` already did. For example, a SQLite +`iter_batches` failure, or a failing catalog query, reaches the caller as +`OrcapodDatabaseReadError` (its cause the driver's error), no longer as +`sqlite3.OperationalError`; a table refused as another path's keeps its own error. ## Rules carried over diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index c69ffb6b6..94a20a9ce 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -44,7 +44,10 @@ ) from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiral_store_identity import refuse_other_format_path +from orcapod.databases.spiral_store_identity import ( + SpiralStoreTableCollisionError, + refuse_other_format_path, +) from orcapod.databases.spiraldb_store_tables import ( StoreTables, declared_keeping_identifier, @@ -487,19 +490,26 @@ def _get_committed_table( """Fetch all committed records for a path from the connector. Raises: - OrcapodDatabaseReadError: If the table exists and cannot be read, on - every connector: a lookup that cannot read the stored table fails - the run rather than one row (``job.run``'s contract for an - unreadable stored table), as ``get_table_schema`` does. + OrcapodDatabaseReadError: If the table cannot be found or read, on + every connector (finding it reads the store too): a lookup that + cannot read the stored table fails the run rather than one row + (``job.run``'s contract for an unreadable stored table), as + ``get_table_schema`` does. + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. """ full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) + # Outside the ``try``: an invalid path is no table, so its refusal must + # not be reported as a stored table that could not be read. self._require_table_name(table_name) - table = self._find_committed_table(table_name, full_path, schema=schema) - if table is None: - return None - schema, name = table try: + # Finding the table reads the store too (a SpiralDB table's metadata, a + # SQL catalog): a failure there is a read error, as in ``get_table_schema``. + table = self._find_committed_table(table_name, full_path, schema=schema) + if table is None: + return None + schema, name = table if (store := self._spiral) is not None: batches = list(store.scan(name)) else: @@ -508,7 +518,8 @@ def _get_committed_table( f"SELECT * FROM {sql_table_identifier(name, schema)}" ) ) - except OrcapodDatabaseError: + except (OrcapodDatabaseError, SpiralStoreTableCollisionError): + # A table that is not this path's is refused as such, never as unreadable. raise except Exception as exc: raise OrcapodDatabaseReadError(table_name, full_path) from exc @@ -1343,8 +1354,10 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # Another writer can commit an ID after it was checked at add time. # Use the connector's atomic insert-if-missing for both modes. if store is not None: - # Writes only the keys the table does not hold: a stored row is never - # overwritten (SpiralDB's append replaces a row of the same key). + # Writes only the keys the write's fresh key read does not show: a row + # visible then is never overwritten (SpiralDB's append replaces a row of + # the same key). A key another writer stores after that read can still + # be replaced until the one-writer lease (ITL-1452). store.write(table_name, pending) elif self._sql_store is None: self._connector.create_table_if_not_exists( diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py index 9b14c3b60..bc0521355 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_store_identity.py @@ -201,7 +201,7 @@ def read_store_table_record_of_any_format( Raises: SpiralStoreTableCollisionError: If the record is partial or unreadable (its - format included). + format included, or empty). """ if not any(k in metadata for k in _RECORD_KEYS): return None @@ -212,6 +212,8 @@ def read_store_table_record_of_any_format( raise SpiralStoreTableCollisionError( f"its record cannot be read: {exc}" ) from exc + if not store_format: + raise SpiralStoreTableCollisionError("its record names no store format") return _read_record(metadata), store_format diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py index 645ae0263..303213446 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -63,7 +63,9 @@ class _Scan(Protocol): """The part of spiral-sdk's scan the store uses.""" - def to_table(self) -> pa.Table: ... + def to_table(self) -> pa.Table: + """The rows the scan reads, as one Arrow table.""" + ... class _KeyedTable(Protocol): @@ -77,9 +79,13 @@ def key_columns(self) -> tuple[str, ...]: ... def schema(self) -> pa.Schema: ... - def get_metadata(self) -> dict[str, bytes]: ... + def get_metadata(self) -> dict[str, bytes]: + """The table's metadata entries, as stored.""" + ... - def set_metadata(self, metadata: dict[str, bytes]) -> None: ... + def set_metadata(self, metadata: dict[str, bytes]) -> None: + """Record metadata entries (an upsert of the given keys).""" + ... def scan( self, @@ -87,9 +93,15 @@ def scan( *, filter: Any = None, # pyright: ignore[reportExplicitAny] # an SDK expression limit: int | None = None, - ) -> _Scan: ... + ) -> _Scan: + """A read of the table's current snapshot: only ``columns`` when given (every + column otherwise), the rows ``filter`` keeps, at most ``limit`` rows.""" + ... - def append(self, data: pa.Table) -> _KeyedTable: ... + def append(self, data: pa.Table) -> _KeyedTable: + """Write rows; a row whose key the table holds replaces that row. The returned + table is not used: the store opens the table by name again.""" + ... @dataclass(frozen=True) @@ -134,9 +146,12 @@ class _New: Attributes: seen: What it recorded when it was judged (``_seen_manifest``): its first write records it only as it was then. + record: The identity record it held when it was judged, if any: compared with + ``seen`` before the first write records over it. """ seen: _Seen + record: identity.StoreTableRecord | None _Judgment = _Opened | _New | None @@ -435,7 +450,7 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: identity.require_store_table_path(record, path) if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]): # New: its first write records it, unless what it saw here changed. - return _New(_seen_manifest(metadata, path)) + return _New(_seen_manifest(metadata, path), record) try: manifest = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: @@ -701,11 +716,15 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: return table def _unchanged_since_judged( - self, table: _KeyedTable, path: tuple[str, ...], seen: _Seen + self, + table: _KeyedTable, + path: tuple[str, ...], + seen: _Seen, + seen_record: identity.StoreTableRecord | None, ) -> bool: - """Whether a table opened to be recorded is still as it was judged new: an - equivalent manifest (or none; compared by name, never by order or bytes) and no - rows. + """Whether a table opened to be recorded is still as it was judged new: the same + identity record (or none), an equivalent manifest (or none; compared by name, + never by order or bytes) and no rows. Read immediately before the manifest is written, so a record that read shows is never overwritten. It narrows, and cannot close, the window in which two @@ -717,6 +736,7 @@ def _unchanged_since_judged( table: The table, opened under its name. path: The full record path the name was computed from. seen: What the table recorded when it was judged new. + seen_record: The identity record it held then, if any. Returns: Whether it is unchanged. @@ -732,8 +752,10 @@ def _unchanged_since_judged( if record is not None: identity.require_store_table_path(record, path) now = _seen_manifest(metadata, path) - return _same_seen(now, seen) and not _holds_rows( - table, self._service_call, [codec.KEY_COLUMN] + return ( + record == seen_record + and _same_seen(now, seen) + and not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]) ) def _require_same_manifest( @@ -773,9 +795,12 @@ def _require_same_manifest( def write(self, table_name: str, records: pa.Table) -> None: """Write rows whose keys the table does not hold yet; the first write creates the table and records its identity and manifest. Every check runs before anything is - created or written. A stored row is never overwritten: ``ConnectorArrowDatabase`` - refuses a stored id when the rows are added (unless asked to skip it), and a key - another writer stored since is left as that writer stored it. + created or written. A row the write's fresh key read shows is never overwritten: + ``ConnectorArrowDatabase`` refuses a stored id when the rows are added (unless + asked to skip it), and a key another writer stored before that read is left as + that writer stored it. A key another writer stores after that read can still be + replaced (SpiralDB's append replaces a row of the same key) until the one-writer + lease (ITL-1452). What a table records is kept only once an append to it succeeded; a write that fails forgets it, so the next call judges the table again as the service has it @@ -807,8 +832,11 @@ def write(self, table_name: str, records: pa.Table) -> None: if not isinstance(opened, _Opened): # Compared with what this write's own judgment saw, never with what # another call judged since. - seen = opened.seen if isinstance(opened, _New) else ("none", None) - self._write_first(table_name, path, context, records, seen) + if isinstance(opened, _New): + seen, seen_record = opened.seen, opened.record + else: + seen, seen_record = ("none", None), None + self._write_first(table_name, path, context, records, seen, seen_record) return found = opened.found _require_data_context(found, context) @@ -844,6 +872,7 @@ def _write_first( context: str, records: pa.Table, seen: _Seen, + seen_record: identity.StoreTableRecord | None, ) -> None: """The first write of a table judged absent or new (``write``). @@ -854,6 +883,8 @@ def _write_first( records: The rows, record id column included. seen: What the table recorded when this write judged it (``_seen_manifest``; ``("none", None)`` when it was absent). + seen_record: The identity record it held then (``None`` when absent or + unrecorded): a changed record is never recorded over. """ manifest = codec.new_manifest(path, path[-1], records.schema) metadata = { @@ -866,7 +897,7 @@ def _write_first( self._forget_opened(table_name) table = self._create_or_open(table_name) _require_key(table, self._service_call) - if self._unchanged_since_judged(table, path, seen): + if self._unchanged_since_judged(table, path, seen, seen_record): with self._service_call("record a store table"): table.set_metadata(metadata) recorded = _Found( diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index e63172411..aa43dfc05 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1172,6 +1172,9 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( p: database.get_all_records(p, record_id_column="__rid") for p in database.list_table_paths() } + # Every table kind of the job is in the snapshot, the operator cache included: a + # kind missing here would never be compared below. + assert sorted(p[-1] for p in before) == sorted(k for k in LAYOUTS if k != "sdb_v2") calls.clear() delivered.clear() fresh = ConnectorArrowDatabase(store()) @@ -1932,7 +1935,7 @@ def test_a_first_writer_compares_the_table_with_its_own_observation( another manifest and a second thread then judges it; the first write refuses it and keeps that manifest (it used to take the second thread's judgment as its own and record over it).""" - import threading + from concurrent.futures import ThreadPoolExecutor first_seen = rows(["x"]).drop_columns(["s"]) _make_table( @@ -1962,9 +1965,9 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: **codec.manifest_entries(peers_manifest), } ) - judge = threading.Thread(target=lambda: tables.has_table(name)) - judge.start() - judge.join() + # The peer's judgment must succeed: ``result()`` raises what it raised. + with ThreadPoolExecutor(max_workers=1) as peer: + assert peer.submit(tables.has_table, name).result() is False return new_manifest(*args, **kwargs) monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) @@ -2124,3 +2127,94 @@ def with_metadata(table: pa.Table) -> pa.Table: recorded = db.get_table_schema(RESULT) assert recorded is not None assert seen[0].equals(recorded, check_metadata=True) + + +# ------------------------------------- review round 7 (PR 692): CodeRabbit, final head + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("lookup", ["by_id", "all"]) +def test_a_table_whose_metadata_cannot_be_read_fails_the_lookup_as_a_read_error( + lookup: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Finding the table is a read too: a fresh reader whose metadata read fails + raises ``OrcapodDatabaseReadError``, as a failing scan does, never the service's + own error.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + + def unreadable(self: Any) -> dict[str, bytes]: + raise RuntimeError("the service could not read the metadata") + + monkeypatch.setattr(fake.FakeKeyedTable, "get_metadata", unreadable) + fresh = ConnectorArrowDatabase(store()) + with pytest.raises(OrcapodDatabaseReadError) as raised: + if lookup == "by_id": + _ = fresh.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") + else: + _ = fresh.get_all_records(RESULT, record_id_column="__record_id") + assert isinstance(raised.value.__cause__, RuntimeError) + + +@pytest.mark.usefixtures("root") +def test_a_lookup_of_a_table_that_is_not_this_paths_still_raises_a_collision() -> None: + """A collision found while finding the table keeps its own type.""" + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError): + _ = ConnectorArrowDatabase(store()).get_all_records(RESULT) + + +@pytest.mark.usefixtures("root") +def test_a_record_with_an_empty_store_format_refuses_the_listing() -> None: + """An empty format is a malformed record, not another format to list.""" + metadata = { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: b"", + } + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError, match="no store format"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +@pytest.mark.usefixtures("root") +def test_a_first_write_refuses_an_empty_table_recorded_meanwhile_under_another_context( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An empty table judged with manifest M under context A, then recorded by another + writer with M under context B before the write: the write refuses it and keeps B's + record (it used to see the same manifest and record A over it).""" + other_context = "std:v1:other" + written = rows(["r0"]) + manifest_entries = codec.manifest_entries( + codec.new_manifest(RESULT, "rdb_v1", written.schema) + ) + _make_table( + identity.spiral_store_table_name(RESULT), + {**identity.store_table_metadata(RESULT, CONTEXT), **manifest_entries}, + with_rows=False, + ) + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + new_manifest = codec.new_manifest + interfered: list[bool] = [] + + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + if not interfered: + interfered.append(True) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, other_context), + **manifest_entries, + } + ) + return new_manifest(*args, **kwargs) + + monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) + with tables.operation(): + with pytest.raises(InputValidationError): + tables.write(name, written) + assert interfered == [True] + kept = identity.read_store_table_metadata(_table(name).get_metadata()) + assert kept is not None and kept.data_context_key == other_context + assert _table(name).scan().to_table().num_rows == 0 From dc4accfe838f6cea2c4c2c4fa799451205cb8109 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:23:06 -0800 Subject: [PATCH 35/50] fix(spiraldb_lease): clear only the newest generation; dry run refuses reserved-name tables - clear(client, project_id, dataset, table_id, ...) finds the dataset's newest generation by its reserved name and refuses, writing nothing, any other table ID (a user table with a lease-shaped key, an older or another dataset's generation); a failed lookup is a chained LeaseError. The refusal message shows the new call. - A failure reading the state before a release marker is a chained LeaseError naming the table ID; interruptions propagate. - The cleanup note of an interrupted create names the claimed table ID and the repr of the cleanup error. - An interruption after the claim is confirmed releases it. - The migration dry run reports writer lease generations as skipped and refuses tables under reserved names whose key is not a lease signature. - Changelog: rename before migrating; known limitation ITL-1860. - Docstrings on every lease and migration test. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1838.md | 8 +- docs/dev/plans/itl-1838-spiraldb-lease.md | 7 +- scripts/migrate_spiral_schemas.py | 57 +++- src/orcapod/databases/spiraldb_lease.py | 87 +++++-- .../test_migrate_spiral_schemas.py | 119 ++++++++- tests/test_databases/test_spiral_lease.py | 246 ++++++++++++++++-- 6 files changed, 469 insertions(+), 55 deletions(-) diff --git a/changelog.d/ITL-1838.md b/changelog.d/ITL-1838.md index 67bb40e21..e49f6ffeb 100644 --- a/changelog.d/ITL-1838.md +++ b/changelog.d/ITL-1838.md @@ -1,7 +1,11 @@ ### Breaking changes and migration -- SpiralDB table names of the form `orcapod_lease_v1_g` (`N` a positive whole number without leading zeros) are now reserved for writer lease generations. A keyed table with such a name is no longer read or listed by the SpiralDB connector, and the connector refuses to create one. Rename the table before upgrading. +- SpiralDB table names of the form `orcapod_lease_v1_g` (`N` a positive whole number without leading zeros) are now reserved for writer lease generations. A keyed table with such a name is no longer read or listed by the SpiralDB connector, and the connector refuses to create one. Rename such a table before upgrading, and before migrating its dataset with `scripts/migrate_spiral_schemas.py`: the migration's dry run refuses a table with a reserved name that is not a writer lease generation. ### Added -- Added internal SpiralDB writer leases based on generation tables, with manual recovery by table ID. +- Added internal SpiralDB writer leases based on generation tables, with manual recovery of the newest generation by table ID. + +### Known limitations + +- In a SpiralDB dataset already migrated with `scripts/migrate_spiral_schemas.py`, a table with a reserved writer lease name cannot be read after the upgrade, renamed or not: its row in `__orcapod_schemas__` keeps the old name, and the connector refuses a table whose row names another name. No supported step updates that row yet (ITL-1860). diff --git a/docs/dev/plans/itl-1838-spiraldb-lease.md b/docs/dev/plans/itl-1838-spiraldb-lease.md index e61d073b7..0c2b7c5e0 100644 --- a/docs/dev/plans/itl-1838-spiraldb-lease.md +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -40,8 +40,11 @@ returns generations in its pages, and the connector skips them by name. A refusal identifies the blocking table ID. To clear a stale lease, first stop the previous writer and ensure all outstanding writes have settled. Then call -`spiraldb_lease.clear(client, table_id, confirm_writer_stopped=True)` on the same -service. Clearing a live writer can admit another writer while an earlier +`spiraldb_lease.clear(client, project_id, dataset, table_id, +confirm_writer_stopped=True)` on the same service. Only the dataset's newest +generation can block acquisition, and only it can be cleared: `clear` finds it by +its reserved name (a table opened by ID has no name) and refuses, writing nothing, +any other table ID. Clearing a live writer can admit another writer while an earlier write is still in flight. The lease has no time limit. Keep every generation table, including released ones. Deleting a numbered generation by hand breaks the contiguous sequence and can admit a second holder while a newer generation diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 8cf066ed1..a608a4a8e 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -35,8 +35,9 @@ from typing import Any SCHEMA_TABLE = "__orcapod_schemas__" -# The legacy dry-run environment predates the lease name helper. +# The legacy dry-run environment predates the lease name and key helpers. LEASE_TABLE_PATTERN = re.compile(r"orcapod_lease_v1_g[1-9][0-9]*") +LEASE_KEY_PATTERN = re.compile(r"orcapod_lease_v1_[0-9a-f]{32}") PLAN_FORMAT = "orcapod.spiral_migration" PLAN_VERSION = 1 ROW_FORMAT = "orcapod.table_schema" @@ -189,6 +190,30 @@ def first_rows_digest(connector: Any, name: str) -> str | None: return get_default_context().arrow_hasher.hash_table(rows).to_string() +def table_key_columns(connector: Any, name: str) -> list[str]: + """Return a table's key columns as the dry run's connector reads them. + + Args: + connector: The connector of the table's dataset. + name: The table. + """ + return list(connector.lookup_table(name).key_columns) + + +def is_lease_generation(key_columns: list[str]) -> bool: + """Return whether a table under a reserved name is a writer lease generation. + + A generation has exactly one key column, carrying the lease signature. + + Args: + key_columns: The table's key columns. + """ + return ( + len(key_columns) == 1 + and LEASE_KEY_PATTERN.fullmatch(key_columns[0]) is not None + ) + + def describe_table( connector: Any, project: str, dataset: str, name: str ) -> dict[str, Any]: @@ -236,24 +261,46 @@ def dry_run(args: argparse.Namespace) -> None: ) project = client.project(args.project) tables: dict[str, list[str]] = {} + reserved: dict[str, list[str]] = {} schema_tables: dict[str, str] = {} for found in project.list_tables(): if found.table == SCHEMA_TABLE: schema_tables[found.dataset] = found.id - elif not LEASE_TABLE_PATTERN.fullmatch(found.table): + elif LEASE_TABLE_PATTERN.fullmatch(found.table): + reserved.setdefault(found.dataset, []).append(found.table) + else: tables.setdefault(found.dataset, []).append(found.table) if missing := [d for d in args.dataset if d not in tables]: raise MigrationError( f"no table in dataset(s) {missing}; the project has {sorted(tables)}" ) + connectors = { + dataset: SpiralDBConnector(args.project, dataset) + for dataset in sorted(set(args.dataset)) + } + # A reserved name holds a writer lease generation, which is not migrated, or a + # table the upgraded connector no longer reads: refuse before planning anything. + generations: dict[str, list[str]] = {} + collisions: list[str] = [] + for dataset, connector in connectors.items(): + for name in sorted(reserved.get(dataset, [])): + if is_lease_generation(table_key_columns(connector, name)): + generations.setdefault(dataset, []).append(name) + else: + collisions.append(f"{args.project}/{dataset}/{name}") + if collisions: + raise MigrationError( + f"table(s) {collisions} have names reserved for writer lease generations " + "but are not lease generations; Orcapod on spiral-sdk does not read them. " + "Rename them, then run the dry run again" + ) plan: dict[str, Any] = { "format": PLAN_FORMAT, "version": PLAN_VERSION, "project": args.project, "datasets": {}, } - for dataset in sorted(set(args.dataset)): - connector = SpiralDBConnector(args.project, dataset) + for dataset, connector in connectors.items(): described = [] for name in sorted(tables[dataset]): described.append(describe_table(connector, args.project, dataset, name)) @@ -262,6 +309,8 @@ def dry_run(args: argparse.Namespace) -> None: present = schema_tables.get(dataset) plan["datasets"][dataset] = {"schema_table": present, "tables": described} print(f"{dataset}: {len(described)} table rows and 1 completion marker") + if skipped := generations.get(dataset): + print(f" skipped {len(skipped)} writer lease generation(s): {skipped}") print( f" {SCHEMA_TABLE}: " + ("absent, as expected" if present is None else f"EXISTS ({present})") diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 70f878447..21c1232b5 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -2,7 +2,8 @@ Generation discovery requires a contiguous sequence. Deleting a generation table by hand can admit a second holder while a newer generation is still -held. Keep every generation table and use ``clear`` by ID to release stale leases. +held. Keep every generation table and use ``clear`` by ID to release a stale +newest generation. """ from __future__ import annotations @@ -97,11 +98,18 @@ class LeaseBusyError(LeaseError): table_id: str def __init__( - self, dataset: str, table_id: str, owner: str | None, *, released: bool = False + self, + project_id: str, + dataset: str, + table_id: str, + owner: str | None, + *, + released: bool = False, ) -> None: """Identify the conflicting generation and explain how to proceed. Args: + project_id: Project containing the dataset. dataset: Dataset where acquisition was refused. table_id: Immutable ID of the conflicting generation. owner: Owner details if recorded. @@ -110,7 +118,8 @@ def __init__( self.table_id = table_id description = f"owner {owner!r}" if owner is not None else "owner unknown" how_to_clear = ( - f"spiraldb_lease.clear(client, {table_id!r}, confirm_writer_stopped=True)" + f"spiraldb_lease.clear(client, {project_id!r}, {dataset!r}, {table_id!r}, " + "confirm_writer_stopped=True)" ) conflict = f"SpiralDB dataset {dataset!r} has a conflicting writer lease" recovery = ( @@ -246,17 +255,24 @@ def _claim_generation( return found state = _state(found, found_key) raise LeaseBusyError( - dataset, found.resource_id, state.owner, released=state.released + project_id, dataset, found.resource_id, state.owner, released=state.released ) from exc except BaseException as exc: + claimed_id: str | None = None try: found = _open(client, project_id, dataset, generation) if found is not None and spiral_lease_key_column(found.key_columns) == key: + claimed_id = found.resource_id _write_release(client, found, key) except BaseException as cleanup_error: + where = ( + f"writer lease table ID {claimed_id!r}" + if claimed_id is not None + else f"generation {generation}" + ) exc.add_note( - f"Reconciling interrupted writer lease creation at generation " - f"{generation} also failed: {cleanup_error}" + f"Reconciling interrupted writer lease creation ({where}) also " + f"failed: {cleanup_error!r}" ) raise @@ -288,15 +304,16 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le if latest is not None: state = _state(latest, _key(latest)) if not state.released: - raise LeaseBusyError(dataset, latest.resource_id, state.owner) + raise LeaseBusyError(project_id, dataset, latest.resource_id, state.owner) key = f"{SPIRAL_LEASE_KEY_PREFIX}{uuid4().hex}" row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) claimed = _claim_generation(client, project_id, dataset, generation + 1, key) - lease = Lease(claimed.resource_id, key, os.getpid()) - # Owner details and release are different keys. An operator's release survives - # even if this write publishes after it. + # From here the claim is confirmed as this caller's: every exit but a verified + # lease releases it. Owner details and release are different keys, so an + # operator's release survives even if the owner write publishes after it. try: + lease = Lease(claimed.resource_id, key, os.getpid()) try: _ = claimed.append(row) except Exception as exc: @@ -317,7 +334,7 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le except BaseException as cleanup_error: exc.add_note( f"Releasing the failed acquisition also failed (writer lease table ID " - f"{lease.table_id!r}): {cleanup_error!r}" + f"{claimed.resource_id!r}): {cleanup_error!r}" ) raise return lease @@ -381,7 +398,15 @@ def _write_release(client: _Client, table: _KeyedTable, key: str) -> None: def _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: """Write a release marker if this snapshot does not already show one.""" - if not _state(table, key).released: + try: + released = _state(table, key).released + except LeaseError: + raise + except Exception as exc: + raise LeaseError( + f"Could not read the state of SpiralDB lease table ID {table.resource_id!r}" + ) from exc + if not released: _write_release(client, table, key) @@ -399,24 +424,48 @@ def release(client: _Client, lease: Lease) -> None: _mark_released(client, _held_table(client, lease), lease.key) -def clear(client: _Client, table_id: str, *, confirm_writer_stopped: bool) -> None: - """Manually release a stale generation by immutable table ID. +def clear( + client: _Client, + project_id: str, + dataset: str, + table_id: str, + *, + confirm_writer_stopped: bool, +) -> None: + """Manually release a stale newest generation, named by its immutable table ID. + + Only the newest generation of a dataset can block acquisition, so only it can be + cleared. It is found by its reserved name, which proves that the table is a lease + generation (a table opened by ID has no name); a table ID that is not the newest + generation of the dataset is refused and nothing is written. Args: client: SDK client for the service holding the generation table. + project_id: Project containing the dataset. + dataset: Dataset reported in the refusal. table_id: Immutable ID reported in the refusal. confirm_writer_stopped: Whether the previous writer and all pending writes have stopped. Raises: ValueError: If the operator did not confirm the writer has stopped. - LeaseError: If the generation's identity or release cannot be verified. + LeaseError: If the table is not the dataset's newest generation, or the + generation's identity, state or release cannot be verified. """ if confirm_writer_stopped is not True: raise ValueError( "Confirm that the writer has stopped before clearing its lease" ) - table = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, table_id)) - if table.resource_id != table_id: - raise LeaseError(f"Could not verify SpiralDB lease table ID {table_id!r}") - _mark_released(client, table, _key(table)) + try: + _, newest = _newest(client, project_id, dataset) + except Exception as exc: + raise LeaseError( + f"Could not look up the writer lease generations of SpiralDB dataset " + f"{dataset!r} to verify table ID {table_id!r}" + ) from exc + if newest is None or newest.resource_id != table_id: + raise LeaseError( + f"SpiralDB table ID {table_id!r} is not the newest writer lease " + f"generation of dataset {dataset!r}; nothing was cleared" + ) + _mark_released(client, newest, _key(newest)) diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index c3c4e9071..442a253b2 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -17,7 +17,9 @@ from orcapod.databases import SpiralDBConnector from orcapod.databases import spiraldb_schema_table as st from orcapod.databases.store_table_names import ( + SPIRAL_LEASE_KEY_PREFIX, is_spiral_lease_table_name, + spiral_lease_key_column, spiral_lease_table_name, store_table_name, ) @@ -153,6 +155,7 @@ def test_write_then_verify(tool: ModuleType, args: argparse.Namespace) -> None: def test_lease_name_recognizers_agree(tool: ModuleType) -> None: + """The script's reserved-name and lease-key patterns agree with the library's.""" cases = [ ("orcapod_lease_v1_g1", True), ("orcapod_lease_v1_g10", True), @@ -175,11 +178,35 @@ def test_lease_name_recognizers_agree(tool: ModuleType) -> None: name ) assert is_spiral_lease_table_name(name) == expected, repr(name) + keys = [ + (f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}", True), + (f"{SPIRAL_LEASE_KEY_PREFIX}{'A' * 32}", False), + (f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 31}", False), + (f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 33}", False), + ("k", False), + ] + for key, expected in keys: + assert tool.is_lease_generation([key]) == expected, repr(key) + assert (spiral_lease_key_column([key]) is not None) == expected, repr(key) + lease_key = keys[0][0] + assert not tool.is_lease_generation([lease_key, "k"]) + assert spiral_lease_key_column([lease_key, "k"]) is None -def test_dry_run_and_write_skip_lease_generations( - tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch -) -> None: +def _legacy_listing( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + reserved: list[tuple[str, str, list[str]]], +) -> tuple[dict[str, Any], list[str]]: + """List the planned tables and ``reserved`` (dataset, name, key columns) as the + pyspiral client would, and return the plan and the reserved names opened. + + Each reserved name is used in one dataset only. + + The tables under reserved names are made on the fake; the dry run's table + descriptions are the plan's, and the key columns it reads are recorded. + """ plan = tool.read_plan(args.plan) descriptions = { (dataset, table["row"]["table_name"]): table @@ -191,15 +218,21 @@ def test_dry_run_and_write_skip_lease_generations( for (dataset, name), table in descriptions.items() ] project = fake.FakeClient().project(args.project) - for generation in (1, 2): - name = spiral_lease_table_name(generation) - dataset = args.dataset[0] - lease = project.create_keyed_table( - dataset, name, pa.schema([pa.field("k", pa.large_string(), False)]) - ) - listed.append( - SimpleNamespace(dataset=dataset, table=name, id=lease.resource_id) + keys: dict[str, list[str]] = {} + for dataset, name, key_columns in reserved: + made = project.create_keyed_table( + dataset, + name, + pa.schema([pa.field(k, pa.large_string(), False) for k in key_columns]), ) + assert name not in keys, "reserved names are distinct across datasets here" + keys[name] = key_columns + listed.append(SimpleNamespace(dataset=dataset, table=name, id=made.resource_id)) + opened: list[str] = [] + + def key_columns_of(_connector: Any, name: str) -> list[str]: + opened.append(name) + return keys[name] legacy = SimpleNamespace( authn=SimpleNamespace(token=lambda: None), @@ -213,14 +246,74 @@ def test_dry_run_and_write_skip_lease_generations( "describe_table", lambda _connector, _project, dataset, name: descriptions[dataset, name], ) + monkeypatch.setattr(tool, "table_key_columns", key_columns_of) + return plan, opened + + +def _lease_key(n: int) -> list[str]: + """Return the key columns of a writer lease generation with a synthetic token.""" + return [f"{SPIRAL_LEASE_KEY_PREFIX}{n:032x}"] + +def test_dry_run_and_write_skip_lease_generations( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """Writer lease generations (lease-signature keys) in selected datasets are + skipped and reported; the plan, the write and the verify are unchanged.""" + first, second = args.dataset[:2] + plan, opened = _legacy_listing( + tool, + args, + monkeypatch, + [ + (first, spiral_lease_table_name(2), _lease_key(2)), + (second, spiral_lease_table_name(3), _lease_key(3)), + (first, spiral_lease_table_name(1), _lease_key(1)), + ], + ) tool.dry_run(args) - recorded = tool.read_plan(args.plan) - assert recorded == plan + assert tool.read_plan(args.plan) == plan + assert sorted(opened) == [spiral_lease_table_name(n) for n in (1, 2, 3)] + printed = capsys.readouterr().out + assert "skipped 2 writer lease generation(s)" in printed + assert "skipped 1 writer lease generation(s)" in printed tool.write(args) tool.verify(args) +def test_dry_run_refuses_a_reserved_name_table_without_a_lease_key( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """A table under a reserved name whose key is not a lease signature, in a selected + dataset, refuses the dry run, naming every such table, and no plan is written; + one in a dataset that is not selected is neither opened nor reported.""" + first, second = args.dataset[:2] + before = Path(args.plan).read_text() + _, opened = _legacy_listing( + tool, + args, + monkeypatch, + [ + (second, spiral_lease_table_name(3), ["k"]), + (first, spiral_lease_table_name(1), _lease_key(1)), + (first, spiral_lease_table_name(2), ["k", "j"]), + ("unselected", spiral_lease_table_name(4), ["k"]), + ], + ) + with pytest.raises(tool.MigrationError, match="Rename them") as refused: + tool.dry_run(args) + message = str(refused.value) + assert f"{args.project}/{first}/{spiral_lease_table_name(2)}" in message + assert f"{args.project}/{second}/{spiral_lease_table_name(3)}" in message + assert spiral_lease_table_name(1) not in message + assert spiral_lease_table_name(4) not in opened + assert spiral_lease_table_name(4) not in message + assert Path(args.plan).read_text() == before + + def test_the_dry_run_reads_raise_no_keyed_table_deprecation( tool: ModuleType, project: Any ) -> None: diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 8a5e40709..3cbc46c7a 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -9,6 +9,7 @@ import pyarrow as pa import pytest +from orcapod.databases import spiraldb_lease from orcapod.databases.spiraldb_connector import SpiralDBConnector from orcapod.databases.spiraldb_lease import ( LeaseBusyError, @@ -40,6 +41,7 @@ def client(tmp_path: Path) -> Iterator[fake.FakeClient]: def test_take_check_release_and_retake(client: fake.FakeClient) -> None: + """A released lease can be released again, and a new acquire takes the next generation.""" first = acquire(client, _PROJECT, _DATASET, owner="first run") check(client, first) release(client, first) @@ -55,9 +57,12 @@ def test_take_check_release_and_retake(client: fake.FakeClient) -> None: def test_lease_operations_raise_no_keyed_table_deprecation( client: fake.FakeClient, ) -> None: - """Every keyed-table open and create of a lease goes through the connector's - helpers, which ignore the SDK's keyed-table deprecation for their own calls, also - after an earlier open made before the error filter.""" + """Lease operations raise no keyed-table deprecation warning. + + Every keyed-table open and create of a lease goes through the connector's helpers, + which ignore the SDK's keyed-table deprecation for their own calls, also after an + earlier open made before the error filter. + """ earlier = acquire(client, _PROJECT, _DATASET, owner="earlier run") release(client, earlier) with warnings.catch_warnings(): @@ -65,12 +70,13 @@ def test_lease_operations_raise_no_keyed_table_deprecation( lease = acquire(client, _PROJECT, _DATASET, owner="checked run") check(client, lease) release(client, lease) - clear(client, lease.table_id, confirm_writer_stopped=True) + clear(client, _PROJECT, _DATASET, lease.table_id, confirm_writer_stopped=True) with pytest.raises(LeaseError, match="released"): check(client, lease) def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) -> None: + """A held lease refuses others, naming the clear call, until it is cleared by ID.""" first = acquire(client, _PROJECT, _DATASET, owner="same owner") other = fake.FakeClient() for _ in range(2): @@ -80,13 +86,17 @@ def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) assert _DATASET in message assert first.table_id in message assert "same owner" in message - assert "confirm_writer_stopped=True" in message + assert ( + f"spiraldb_lease.clear(client, {_PROJECT!r}, {_DATASET!r}, " + f"{first.table_id!r}, confirm_writer_stopped=True)" + ) in message with pytest.raises(ValueError, match="stopped"): - clear(other, first.table_id, confirm_writer_stopped=False) + clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=False) check(client, first) - clear(other, first.table_id, confirm_writer_stopped=True) + clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=True) second = acquire(other, _PROJECT, _DATASET, owner="next run") - clear(other, first.table_id, confirm_writer_stopped=True) + with pytest.raises(LeaseError, match="not the newest"): + clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=True) check(other, second) with pytest.raises(LeaseError, match="released"): check(client, first) @@ -96,6 +106,8 @@ def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) def test_two_writers_that_observed_the_same_generation( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, winner_releases: bool ) -> None: + """Two writers racing for one generation: the loser is refused, told to retry if + the winner already released.""" create = fake.FakeProject.create_keyed_table attempted: list[str] = [] @@ -129,6 +141,7 @@ def racing_create( def test_crash_between_create_and_owner_record(client: fake.FakeClient) -> None: + """A bare claim with no owner row refuses others until it is cleared.""" # A process that stops after exclusive creation leaves only its claim key. key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" _ = client.project(_PROJECT).create_keyed_table( @@ -138,13 +151,19 @@ def test_crash_between_create_and_owner_record(client: fake.FakeClient) -> None: ) with pytest.raises(LeaseBusyError, match="owner unknown") as refused: _ = acquire(client, _PROJECT, _DATASET, owner="second") - clear(client, refused.value.table_id, confirm_writer_stopped=True) + clear( + client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True + ) check(client, acquire(client, _PROJECT, _DATASET, owner="third")) def test_stale_clear_cannot_be_overwritten_by_late_owner_record( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """A clear that lands before the owner row keeps the lease released. + + The hook runs before the owner write commits; that write then commits. + """ append = fake.FakeKeyedTable.append ids: list[str] = [] @@ -153,7 +172,13 @@ def clear_before_append( ) -> fake.FakeKeyedTable: if not ids: ids.append(table.resource_id) - clear(client, table.resource_id, confirm_writer_stopped=True) + clear( + client, + _PROJECT, + _DATASET, + table.resource_id, + confirm_writer_stopped=True, + ) next_lease = acquire(client, _PROJECT, _DATASET, owner="next") ids.append(next_lease.table_id) return append(table, rows) @@ -170,6 +195,10 @@ def clear_before_append( def test_create_reply_reconciles_the_callers_token( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reply: str ) -> None: + """A create whose reply is lost (timeout) or answered 409 is the caller's claim. + + ``lose_reply`` commits the create before it raises or creates again. + """ create = fake.FakeProject.create_keyed_table def lose_reply( @@ -193,6 +222,7 @@ def lose_reply( def test_create_reply_reports_an_unexpected_claim_token( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """A create that returns a table with another claim key is refused.""" create = fake.FakeProject.create_keyed_table other_key = f"{SPIRAL_LEASE_KEY_PREFIX}{'a' * 32}" @@ -216,6 +246,8 @@ def return_another_claim( def test_create_interruption_releases_only_the_callers_claim( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, own_claim: bool ) -> None: + """An interrupted create releases the generation only when it carries the caller's + key. ``interrupt_create`` commits the create before it raises.""" create = fake.FakeProject.create_keyed_table interrupted = KeyboardInterrupt("create reply interrupted") @@ -252,6 +284,10 @@ def interrupt_create( def test_acquire_recovers_or_releases_after_owner_write_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, owner_reply: str ) -> None: + """A failed owner write releases the claim; a lost reply that committed holds. + + ``fail_owner_write`` commits the owner row before raising only for ``lost``. + """ append = fake.FakeKeyedTable.append def fail_owner_write( @@ -285,6 +321,10 @@ def fail_owner_write( def test_acquire_releases_after_verification_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, failed_call: str ) -> None: + """A verification failure after the claim releases it and keeps the error. + + ``lose_owner_reply`` commits the owner row before it raises. + """ append = fake.FakeKeyedTable.append unavailable_error = TimeoutError("verification unavailable") @@ -322,6 +362,9 @@ def lose_owner_reply( def test_acquire_reports_cleanup_failure_with_generation_id( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """When the release after a failed acquire also fails, the note names the table ID. + No write commits.""" + def unavailable(*_args: object) -> None: raise TimeoutError("writes unavailable") @@ -337,13 +380,16 @@ def unavailable(*_args: object) -> None: and refused.value.table_id in note for note in failed.value.__notes__ ) - clear(client, refused.value.table_id, confirm_writer_stopped=True) + clear( + client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True + ) check(client, acquire(client, _PROJECT, _DATASET, owner="next")) def test_release_reports_a_failed_reopen_as_a_lease_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """A failed reopen on release is a chained ``LeaseError`` naming the table ID.""" holder = acquire(client, _PROJECT, _DATASET, owner="holder") cause = TimeoutError("reopen unavailable") @@ -362,6 +408,7 @@ def unavailable(*_args: object, **_kwargs: object) -> None: def test_release_from_another_process_is_refused_before_the_reopen( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """Another process's release is refused before the table is reopened.""" holder = acquire(client, _PROJECT, _DATASET, owner="holder") elsewhere = Lease(holder.table_id, holder.key, holder.pid + 1) @@ -379,6 +426,10 @@ def unexpected_open(*_args: object, **_kwargs: object) -> None: def test_interrupted_cleanup_keeps_the_acquisition_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """An interrupted release after a failed acquire keeps the acquisition error. + + ``interrupt_release`` commits the owner row and raises before the release commits. + """ append = fake.FakeKeyedTable.append verification_error = TimeoutError("verification unavailable") @@ -406,13 +457,19 @@ def unavailable(*_args: object, **_kwargs: object) -> None: and "KeyboardInterrupt" in note for note in failed.value.__notes__ ) - clear(client, refused.value.table_id, confirm_writer_stopped=True) + clear( + client, _PROJECT, _DATASET, refused.value.table_id, confirm_writer_stopped=True + ) @pytest.mark.parametrize("landed", [True, False]) def test_release_reply_lost( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, landed: bool ) -> None: + """A release whose reply is lost holds if it committed and raises if it did not. + + ``lose_reply`` commits the release before raising only when ``landed``. + """ holder = acquire(client, _PROJECT, _DATASET, owner="holder") append = fake.FakeKeyedTable.append @@ -439,6 +496,8 @@ def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTabl def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reverse: bool ) -> None: + """Generations are hidden from listings; store and look-alike tables stay visible + and cannot be cleared.""" holder = acquire(client, _PROJECT, _DATASET, owner="holder") lease_name = spiral_lease_table_name(1) full_path = [lease_name, "records"] @@ -456,7 +515,13 @@ def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( assert not is_spiral_lease_table_name(name) data = client.project(_PROJECT).create_keyed_table(_DATASET, name, key_schema) with pytest.raises(LeaseError, match=data.resource_id): - clear(client, data.resource_id, confirm_writer_stopped=True) + clear( + client, + _PROJECT, + _DATASET, + data.resource_id, + confirm_writer_stopped=True, + ) _ = client.project(_PROJECT).create_keyed_table(_DATASET, lookalike, key_schema) monkeypatch.setattr(fake, "list_page_size", 1) @@ -472,10 +537,11 @@ def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( def test_release_and_clear_keep_the_generation_sequence_contiguous( client: fake.FakeClient, ) -> None: + """Release and clear keep every generation, so the sequence stays contiguous.""" first = acquire(client, _PROJECT, _DATASET, owner="first") release(client, first) second = acquire(client, _PROJECT, _DATASET, owner="second") - clear(client, second.table_id, confirm_writer_stopped=True) + clear(client, _PROJECT, _DATASET, second.table_id, confirm_writer_stopped=True) third = acquire(client, _PROJECT, _DATASET, owner="third") assert [ client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(i)).resource_id @@ -488,6 +554,8 @@ def test_release_and_clear_keep_the_generation_sequence_contiguous( def test_connector_reserves_generation_names_even_without_a_claim_key( client: fake.FakeClient, ) -> None: + """The connector reserves generation names; a non-lease table under one blocks + acquire and cannot be cleared.""" name = spiral_lease_table_name(1) with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: with pytest.raises(ValueError, match="reserved"): @@ -504,7 +572,9 @@ def test_connector_reserves_generation_names_even_without_a_claim_key( with pytest.raises(LeaseError, match=table.resource_id): _ = acquire(client, _PROJECT, _DATASET, owner="writer") with pytest.raises(LeaseError, match=table.resource_id): - clear(client, table.resource_id, confirm_writer_stopped=True) + clear( + client, _PROJECT, _DATASET, table.resource_id, confirm_writer_stopped=True + ) assert client.keyed_table_by_id(table.resource_id).version_id == table.version_id @@ -512,6 +582,7 @@ def test_connector_reserves_generation_names_even_without_a_claim_key( def test_listing_skips_generations_without_any_sdk_table_opens( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, past_generations: int ) -> None: + """A listing skips generations by name without opening any table.""" for _ in range(past_generations): release(client, acquire(client, _PROJECT, _DATASET, owner="past")) name = store_table_name(["records"], hint_length=96, digest_length=64) @@ -532,6 +603,7 @@ def unexpected_open(*_args: object, **_kwargs: object) -> None: def test_manual_deletion_can_admit_a_second_holder( client: fake.FakeClient, dropped_generation: int ) -> None: + """Dropping a generation by hand breaks the sequence and admits a second holder.""" for _ in range(3): release(client, acquire(client, _PROJECT, _DATASET, owner="past")) first = acquire(client, _PROJECT, _DATASET, owner="first") @@ -544,6 +616,7 @@ def test_manual_deletion_can_admit_a_second_holder( def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None: + """Each dataset has its own generation sequence.""" first = acquire(client, _PROJECT, _DATASET, owner="first") second = acquire(client, _PROJECT, "other", owner="second") assert first.table_id != second.table_id @@ -555,6 +628,10 @@ def test_other_datasets_have_independent_leases(client: fake.FakeClient) -> None def test_create_that_arrives_after_timeout_never_grants_a_second_lease( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, late_create_wins: bool ) -> None: + """A create that commits after its timeout never yields two holders. + + ``delay_create`` commits nothing; the test commits the pending create later. + """ create = fake.FakeProject.create_keyed_table pending: list[tuple[fake.FakeProject, str, str, pa.Schema]] = [] @@ -590,6 +667,7 @@ def delay_create( def test_generation_search_uses_logarithmic_probes( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """Finding the newest of 19 generations takes a logarithmic number of opens.""" for _ in range(19): release(client, acquire(client, _PROJECT, _DATASET, owner="past")) open_by_name = fake.FakeClient.keyed_table @@ -618,6 +696,8 @@ def count_open( def test_lookup_error_never_licenses_creation( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch ) -> None: + """A failed generation lookup never leads to a create.""" + def unavailable(*_args: object) -> fake.FakeKeyedTable: raise fake.SpiralError("remote service returned an unknown error (status 404)") @@ -628,3 +708,139 @@ def never_create(*_args: object, **_kwargs: object) -> fake.FakeKeyedTable: monkeypatch.setattr(fake.FakeProject, "create_keyed_table", never_create) with pytest.raises(fake.SpiralError, match="404"): _ = acquire(client, _PROJECT, _DATASET, owner="writer") + + +def test_interrupted_create_cleanup_failure_names_the_table_id( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """A second interruption during the cleanup of an interrupted create keeps the + first and notes the claimed table ID. ``interrupt_create`` commits the create + before it raises; ``interrupt_release`` commits nothing.""" + create = fake.FakeProject.create_keyed_table + interrupted = KeyboardInterrupt("create reply interrupted") + + def interrupt_create( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) + raise interrupted + + def interrupt_release(*_args: object) -> fake.FakeKeyedTable: + raise KeyboardInterrupt + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeProject, "create_keyed_table", interrupt_create) + patch.setattr(fake.FakeKeyedTable, "append", interrupt_release) + with pytest.raises(KeyboardInterrupt) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is interrupted + claimed = client.keyed_table(_PROJECT, _DATASET, spiral_lease_table_name(1)) + assert any( + "Reconciling interrupted writer lease creation" in note + and claimed.resource_id in note + and "KeyboardInterrupt" in note + for note in caught.value.__notes__ + ) + + +def test_interrupt_after_the_claim_releases_it( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """An interruption after the claim is confirmed, before the owner write, releases + the claim, so the next writer is not refused.""" + interrupted = KeyboardInterrupt("interrupted after the claim") + + def interrupt(*_args: object) -> Lease: + raise interrupted + + with monkeypatch.context() as patch: + patch.setattr(spiraldb_lease, "Lease", interrupt) + with pytest.raises(KeyboardInterrupt) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is interrupted + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +@pytest.mark.parametrize("operation", ["release", "clear"]) +def test_a_failed_state_read_before_release_is_a_lease_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, operation: str +) -> None: + """An ordinary failure reading the state before a release marker is a chained + ``LeaseError`` naming the table ID; an interruption propagates unchanged.""" + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + cause = TimeoutError("scan unavailable") + interrupted = KeyboardInterrupt("scan interrupted") + + def run() -> None: + if operation == "release": + release(client, holder) + else: + clear( + client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True + ) + + def unavailable(*_args: object, **_kwargs: object) -> None: + raise cause + + def interrupt(*_args: object, **_kwargs: object) -> None: + raise interrupted + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeKeyedTable, "scan", unavailable) + with pytest.raises(LeaseError, match=holder.table_id) as failed: + run() + patch.setattr(fake.FakeKeyedTable, "scan", interrupt) + with pytest.raises(KeyboardInterrupt) as caught: + run() + assert failed.value.__cause__ is cause + assert caught.value is interrupted + check(client, holder) + + +def test_clear_reports_a_failed_lookup_as_a_lease_error( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failed lookup in ``clear`` is a chained ``LeaseError`` and writes nothing.""" + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + cause = TimeoutError("lookup unavailable") + + def unavailable(*_args: object, **_kwargs: object) -> None: + raise cause + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeClient, "keyed_table", unavailable) + patch.setattr(fake.FakeClient, "keyed_table_by_id", unavailable) + with pytest.raises(LeaseError, match=holder.table_id) as failed: + clear( + client, _PROJECT, _DATASET, holder.table_id, confirm_writer_stopped=True + ) + assert failed.value.__cause__ is cause + check(client, holder) + + +def test_clear_refuses_a_table_that_is_not_the_newest_generation( + client: fake.FakeClient, +) -> None: + """``clear`` refuses, writing nothing, a user table with a lease-shaped key, an + older generation and a generation of another dataset.""" + older = acquire(client, _PROJECT, _DATASET, owner="older") + release(client, older) + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + elsewhere = acquire(client, _PROJECT, "other", owner="elsewhere") + key = f"{SPIRAL_LEASE_KEY_PREFIX}{'b' * 32}" + user = client.project(_PROJECT).create_keyed_table( + _DATASET, "example", pa.schema([pa.field(key, pa.large_string(), False)]) + ) + for table_id in (user.resource_id, older.table_id, elsewhere.table_id): + before = client.keyed_table_by_id(table_id).version_id + with pytest.raises(LeaseError, match="not the newest") as refused: + clear(client, _PROJECT, _DATASET, table_id, confirm_writer_stopped=True) + assert table_id in str(refused.value) + assert client.keyed_table_by_id(table_id).version_id == before + check(client, holder) + check(client, elsewhere) From 0a71291797f08b7789de19a0b7a4fa1ae34c897c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:24:33 -0800 Subject: [PATCH 36/50] fix(spiraldb): review of 291798da3 for the store switch-on (ITL-1844) - share_client registers a store connector's copy, and a run holds the lease once per store object, so a copy works alone and beside its original. - Releasing the run's leases: an interrupted local let-go still releases every lease remotely, and an interruption outranks an ordinary release error. - The lease scope covers a function pod's own result databases (result_database, pod_cache_database); the end-of-run commit is unchanged. - Evaluation script: Arrow types and native values compared, result tables compared by path, replay needs its seven rows, the load-only run is bound and checked, and the JSON report survives a failing inventory. - Concept page and PipelineJob.load docstring wording. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/spiraldb-store.md | 9 +- docs/dev/scripts/itl_1844_store_evaluation.py | 160 +++++++++++++----- src/orcapod/databases/spiraldb_connector.py | 11 +- src/orcapod/databases/spiraldb_write_scope.py | 90 ++++++---- src/orcapod/pipeline/job.py | 13 +- src/orcapod/pipeline/node_run.py | 38 ++++- .../test_spiraldb_store_runs.py | 120 +++++++++++++ .../test_itl_1844_store_evaluation.py | 81 ++++++++- 8 files changed, 432 insertions(+), 90 deletions(-) diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md index fd873031e..ab1371062 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-store.md @@ -48,7 +48,9 @@ are on one dataset takes one lease. While one run holds the lease, a second writer, in this process or another, is refused when its run starts, with `LeaseBusyError`. Nothing of its run has happened then: no -source was checked, nothing computed, no table made. The error names the lease's table +source was checked, nothing computed, no store data table made. (A run that writes +several datasets takes their leases one after another, so a dataset whose lease it took +before the refusal may hold a new lease table, released.) The error names the lease's table id and who holds it. The lease is refuse-only: the second writer does not wait and never takes the lease over, and a lease does not expire. @@ -90,6 +92,11 @@ spiraldb_lease.clear( ) ``` +`spiral.Client()` connects to the default service. When the job's connector was made +for another service address (`SpiralDBConnector(..., overrides={"server.url": ...})`), +make the client for that same address, with a sign-in allowed to update the dataset: +a client of another service does not find the table id. + Clearing the lease of a writer that is still running lets a second writer in while the first is still writing. Each lease is a small keyed table of the dataset; keep every one, also released ones: removing one by hand can let two writers in. diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_store_evaluation.py index 02587f641..a574dda8e 100644 --- a/docs/dev/scripts/itl_1844_store_evaluation.py +++ b/docs/dev/scripts/itl_1844_store_evaluation.py @@ -30,7 +30,7 @@ import tempfile import time import warnings -from collections.abc import Iterator +from collections.abc import Callable, Iterator from datetime import datetime, timezone from pathlib import Path from typing import Any @@ -106,6 +106,20 @@ def rows(n: int) -> pa.Table: ) +def trials(name: str, database: Any, *, n: int) -> CachedSource: + """The job's input: ``n`` rows, cached in ``database`` (slot ``trials``).""" + return CachedSource( + ArrowTableSource( + rows(n), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ), + cache_database=database.at(name, "cache"), + ) + + def build( name: str, database: Any, @@ -117,17 +131,7 @@ def build( """The evaluated job: every table kind.""" job = PipelineJob(name=name, database=database, result_database=result_database) with job: - source = CachedSource( - ArrowTableSource( - rows(n), - tag_columns=["unit", "trial"], - tag_only_columns=True, - source_id="trials", - record_id_columns=["unit", "trial"], - ), - cache_database=database.at(name, "cache"), - ) - out = combine.pod(source, label="combine") + out = combine.pod(trials(name, database, n=n), label="combine") SelectDataColumns(["total", "ratio"])(out, label="select") sink = sink_pod(deliver) assert isinstance(sink, SideEffectPod) @@ -138,26 +142,50 @@ def build( return job -def comparable(table: pa.Table) -> list[tuple[str, ...]]: +def comparable(table: pa.Table) -> tuple[dict[str, str], list[tuple[Any, ...]]]: + """The Arrow type of every kept column, and the rows as native values in no row + order (sorted by their repr, so values of differing types still sort); the + volatile columns are left out.""" kept = [c for c in sorted(table.column_names) if c not in VOLATILE] - return sorted( - tuple(str(r[c]) for c in kept) for r in table.select(kept).to_pylist() + types = {c: str(table.schema.field(c).type) for c in kept} + values = sorted( + (tuple(r[c] for c in kept) for r in table.select(kept).to_pylist()), key=repr + ) + return types, values + + +def same_table(a: pa.Table | None, b: pa.Table | None) -> bool: + """Both present, with the same column names, kept column types and rows.""" + return ( + a is not None + and b is not None + and a.schema.names == b.schema.names + and comparable(a) == comparable(b) ) def compare(store: Any, delta: Any, prefix: tuple[str, ...]) -> dict[str, Any]: """Every table under ``prefix``: the same paths and rows on both.""" + return compare_paths( + store, [(p, delta, p) for p in delta.list_table_paths(prefix)], prefix + ) + + +def compare_paths( + store: Any, + expected: list[tuple[tuple[str, ...], Any, tuple[str, ...]]], + prefix: tuple[str, ...], +) -> dict[str, Any]: + """The store's tables under ``prefix`` against ``expected``: each store path with + the database and path it must equal there.""" paths = sorted(store.list_table_paths(prefix)) - other = sorted(delta.list_table_paths(prefix)) - report: dict[str, Any] = {"same_paths": paths == other, "tables": {}} - for path in paths: - a, b = store.get_all_records(path), delta.get_all_records(path) - same = ( - a is not None - and b is not None - and a.schema.names == b.schema.names - and comparable(a) == comparable(b) - ) + report: dict[str, Any] = { + "same_paths": paths == sorted(p for p, _, _ in expected), + "tables": {}, + } + for path, database, other in sorted(expected, key=lambda e: e[0]): + a = store.get_all_records(path) if path in paths else None + same = same_table(a, database.get_all_records(other)) report["tables"]["/".join(path)] = { "layout": path[-1], "rows": None if a is None else a.num_rows, @@ -217,7 +245,11 @@ def store() -> ConnectorArrowDatabase: job = build(name, database, n=7, cache_mode=CacheMode.REPLAY) _ = job.run() replayed.append(comparable(job.nodes["select"].as_table())) - s["replay"] = {"ok": replayed[0] == replayed[1], "rows": len(replayed[0])} + # The incremental run stored seven rows: an empty replay on both is no success. + s["replay"] = { + "ok": replayed[0] == replayed[1] and len(replayed[0][1]) == 7, + "rows": len(replayed[0][1]), + } # 4. run_async and 5. node runs, on fresh names. for label, run in ( @@ -234,13 +266,9 @@ def store() -> ConnectorArrowDatabase: results_delta = DeltaTableDatabase(work / "delta_results") _ = build(fresh, store(), n=6, result_database=store().at(fresh, "results")).run() _ = build(fresh, delta, n=6, result_database=results_delta).run() - stored = sorted(store().list_table_paths((fresh,))) - s["separate results"] = { - "ok": len(stored) - == len(delta.list_table_paths((fresh,))) - + len(results_delta.list_table_paths()), - "tables": len(stored), - } + s["separate results"] = compare_paths( + store(), separate_results_expected(fresh, delta, results_delta), (fresh,) + ) # 7. save, load with the store, read back, load-only run. saved = work / "job.json" @@ -250,10 +278,14 @@ def store() -> ConnectorArrowDatabase: k: loaded.nodes[k].as_source().as_table().num_rows for k in ("combine", "select") } + # The cached source is not rebuilt on load: bind its slot, so the load-only run + # loads the whole branch. + loaded.bind(sources={"trials": trials(name, store(), n=7)}) _ = loaded.run(load_only=True) s["save and load"] = { "store_flag_saved": '"store": true' in saved.read_text(), "rows_read": read, + "load_only_rows": loaded.nodes["select"].as_table().num_rows, "ok": read == {"combine": 7, "select": 7}, } @@ -277,11 +309,24 @@ def store() -> ConnectorArrowDatabase: report["ok"] = succeeded(s) +def separate_results_expected( + name: str, delta: Any, results_delta: Any +) -> list[tuple[tuple[str, ...], Any, tuple[str, ...]]]: + """Where each store table of the separate-results job must equal a Delta table: + a result table (under ``/results``) the same path in ``results_delta``, any + other the same path in ``delta``.""" + return [(p, delta, p) for p in delta.list_table_paths((name,))] + [ + ((name, "results", *p), results_delta, p) + for p in results_delta.list_table_paths() + ] + + def succeeded(scenarios: dict[str, Any]) -> bool: """Every scenario as expected: tables as on Delta and the recorded outcomes. The first run computes all six rows; the new row is the only one computed and - delivered; the store flag is saved; a refused writer wrote nothing. + delivered; the store flag is saved; the load-only run loads seven rows; a refused + writer wrote nothing. """ first, new = scenarios.get("first run", {}), scenarios.get("new row", {}) saved, second = ( @@ -294,6 +339,7 @@ def succeeded(scenarios: dict[str, Any]) -> bool: and new.get("calls_on_store") == 1 and new.get("delivered_on_store") == 1 and saved.get("store_flag_saved") is True + and saved.get("load_only_rows") == 7 and second.get("refused") is True and second.get("nothing_written") is True ) @@ -332,6 +378,20 @@ def lease_tables(project: str, dataset: str) -> list[dict[str, str]]: generation += 1 +def inventory( + report: dict[str, Any], label: str, listing: Callable[[], list[dict[str, str]]] +) -> list[dict[str, str]] | None: + """``listing()``, or ``None`` with its error recorded under ``inventory_errors`` + (the evaluation's own error, if any, stays in ``error``).""" + try: + return listing() + except Exception as exc: # best-effort: the report is printed whatever fails here + report.setdefault("inventory_errors", {})[label] = ( + f"{type(exc).__name__}: {exc}" + ) + return None + + @contextlib.contextmanager def fake_service(work: Path) -> Iterator[None]: from tests.test_databases import fake_spiral_sdk as fake @@ -352,21 +412,37 @@ def main() -> int: work = Path(tmp) if args.mode == "fake": stack.enter_context(fake_service(work)) - before = {t["name"] for t in lease_tables(args.project, args.dataset)} report: dict[str, Any] = {"stamp": stamp, "scenarios": {}, "ok": False} print(f"stamp {stamp}", file=sys.stderr) + before = inventory( + report, + "lease tables before", + lambda: lease_tables(args.project, args.dataset), + ) try: evaluate(args.project, args.dataset, stamp, work, report) except Exception as exc: # reported with every table made so far report["error"] = f"{type(exc).__name__}: {exc}" report["ok"] = False - # Every table this run made, also after a failed scenario. - report["store_tables"] = store_tables(args.project, args.dataset, stamp) - report["lease_tables_created"] = [ - t - for t in lease_tables(args.project, args.dataset) - if t["name"] not in before - ] + # Every table this run made, also after a failed scenario; an inventory that + # fails (the service still down) is reported apart and never hides the report. + report["store_tables"] = inventory( + report, + "store tables", + lambda: store_tables(args.project, args.dataset, stamp), + ) + after = inventory( + report, + "lease tables after", + lambda: lease_tables(args.project, args.dataset), + ) + if before is not None and after is not None: + known = {t["name"] for t in before} + report["lease_tables_created"] = [ + t for t in after if t["name"] not in known + ] + if "inventory_errors" in report: # the tables made are not all known + report["ok"] = False report["mode"] = args.mode print(json.dumps(report, indent=2, sort_keys=True)) return 0 if report["ok"] else 1 diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index f56728845..8f066eca1 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1090,9 +1090,16 @@ def _refuse_in_store_mode(self) -> None: ) def share_client(self) -> SpiralDBConnector: - """Return an independently closable connector in the same SDK client scope.""" + """Return an independently closable connector in the same SDK client scope. + + A store connector's copy is a store connector too, registered as one, so a + run on it takes the dataset's writer lease also after the original is gone. + """ self._require_open() - return copy(self) + shared = copy(self) + if self._store_mode: + register_store_connector(shared) + return shared def _qualified(self, table_name: str) -> str: """Return ``"//
"``, the table as errors name it.""" diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 2d8642c11..85f377e74 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -58,9 +58,10 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: Every lease is acquired before the body runs; a refused one releases those already taken and raises. Each lease is released when the body ends, also when it raises (or is cancelled or interrupted). Every release is attempted, also after one fails - or is interrupted. An interruption of a release (``KeyboardInterrupt``, - ``CancelledError``, ``SystemExit``) is never swallowed: it raises once every release - was attempted, after a body that raised too (chained from the body's error, which + or is interrupted (also while letting go of the lease locally). An interruption of + a release (``KeyboardInterrupt``, ``CancelledError``, ``SystemExit``) is never + swallowed: it raises once every release was attempted, ahead of any ordinary + release failure, after a body that raised too (chained from the body's error, which is its ``__cause__``). A release that fails with an error after the body raised is added as a note to the body's error; after a body that succeeded the first failure raises. @@ -80,15 +81,19 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: groups: dict[tuple[str | None, str, str], list[SpiralDBConnector]] = {} for connector in store_connectors(databases): groups.setdefault(connector._writer_lease_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - held: list[ - tuple[list[SpiralDBConnector], Callable[[], None], Callable[[], None]] - ] = [] + held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # StoreTables try: for connectors in groups.values(): check, release = take_lease(connectors[0], owner) - held.append((connectors, check, release)) + # The store tables holding this lease: once each, as two connectors can + # share one (``SpiralDBConnector.share_client``). + holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # StoreTables + held.append((holding, check, release)) for connector in connectors: - _tables(connector).hold_lease(check) + tables = _tables(connector) + if not any(tables is t for t in holding): + tables.hold_lease(check) + holding.append(tables) except BaseException as error: _release_all(held, error) raise @@ -136,42 +141,53 @@ def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExpli def _release_all( - held: list[tuple[list[SpiralDBConnector], Callable[[], None], Callable[[], None]]], + held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]], # pyright: ignore[reportExplicitAny] # StoreTables error: BaseException | None, ) -> None: - """Let go of and release every lease in ``held``. + """Let go of and release every lease in ``held``, each attempted whatever failed. Args: - held: The leases taken, with their connectors. - error: The body's error, which a release failing with an error is noted on; - ``None`` when the body succeeded, and the first failed release then raises. + held: The leases taken, with the store tables that hold each. + error: The body's error, ``None`` when the body succeeded. Raises: - BaseException: The first interruption of a release (chained from the body's - error, if any), or after a successful body the first failed release. + BaseException: The first interruption (``KeyboardInterrupt``, + ``CancelledError``, ``SystemExit``) of a let-go or release, chained from + the body's error when the body failed with an error; otherwise, after a + successful body, the first failed release. Any other failure is a note on + the error raised (on the body's error when the body failed and nothing + was interrupted, or when the body was itself interrupted). """ - failure: BaseException | None = None - for connectors, check, release in reversed(held): - for connector in connectors: - with contextlib.suppress(RuntimeError): # closed: holds nothing any more - _tables(connector).let_go_of_lease(check) + failures: list[BaseException] = [] + for holding, check, release in reversed(held): + for tables in holding: + try: + tables.let_go_of_lease(check) + except BaseException as exc: # noqa: BLE001 # an interruption too: the remote release is still attempted + failures.append(exc) try: release() except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below - interrupted = not isinstance(exc, Exception) - if error is not None and not (interrupted and isinstance(error, Exception)): - error.add_note( - f"Releasing the SpiralDB writer lease also failed: {exc}" - ) - elif failure is None: - failure = exc - else: - failure.add_note( - f"Releasing another SpiralDB writer lease failed: {exc}" - ) - if failure is not None: - if error is not None: - # An interruption of a release after a body that failed with an error: - # the interruption stops the program, with the body's error as its cause. - raise failure from error - raise failure + failures.append(exc) + if not failures: + return + interruptions = [f for f in failures if not isinstance(f, Exception)] + if error is not None and (not interruptions or not isinstance(error, Exception)): + # The body's error is raised by the caller; every failure is a note on it. + for failure in failures: + error.add_note( + f"Releasing the SpiralDB writer lease also failed: {failure}" + ) + return + # An interruption outranks an ordinary failure: it stops the program. + primary = interruptions[0] if interruptions else failures[0] + for failure in failures: + if failure is not primary: + primary.add_note( + f"Releasing another SpiralDB writer lease failed: {failure}" + ) + if error is not None: + # An interruption after a body that failed with an error: the body's error is + # its cause. + raise primary from error + raise primary diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index b3e7e251a..3cae2a67e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2311,11 +2311,13 @@ def load( path: Path to the JSON file produced by ``save()``. database: Optional database override. When provided, takes precedence over any database configuration in the file. Required when the file's - database is a connector database. + database is a connector database. A SpiralDB database must be of the + saved kind (store or plain); any other database may be given. result_database: Optional override of the separate function-result database (ITL-1408), required when the file names a connector database. When provided, it is used whatever the file - says. Otherwise the one the file names is rebuilt from its saved + says, except that a SpiralDB database must be of the saved kind + (store or plain). Otherwise the one the file names is rebuilt from its saved configuration, as the job's database is; a file that names none keeps the results in the job's database (``/_result``). When the file names one that cannot be rebuilt, the function nodes get no @@ -2342,8 +2344,11 @@ def load( the argument that gives it is missing: a connector is not rebuilt from a file. The message names each such binding. Also if a SpiralDB database was saved on a store - (``SpiralDBConnector(..., store=True)``) and the one given is not, - or the other way round (ITL-1844). + (``SpiralDBConnector(..., store=True)``) and the one given is a + plain SpiralDB connector database, or the other way round + (ITL-1844). Only a SpiralDB database of the other kind is refused: + a database that is not a SpiralDB one may stand for a saved + SpiralDB database. """ import json as _json import os diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index d056ac55a..a737ed97f 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -155,6 +155,32 @@ def _databases(nodes: Iterable[Any]) -> list[ArrowDatabaseProtocol]: return found +def _pod_result_databases(node: Any) -> list[Any]: + """The result databases a function node's own pod writes on a cache miss. + + The result database of each pod the node's function pod is or wraps + (``@function_pod(pod_cache_database=...)``) and of each data function under them + (``@function_pod(result_database=...)``). Not the job's result database + (``_databases``); not committed at the end of a run, only leased. + """ + found: list[Any] = [] + pods: list[Any] = [getattr(node, "_function_pod", None)] + visited: set[int] = set() + while pods: + pod = pods.pop(0) + if pod is None or id(pod) in visited: + continue + visited.add(id(pod)) + found.append(getattr(pod, "result_database", None)) + pods.append(getattr(pod, "_function_pod", None)) # a wrapping pod's inner pod + function = getattr(pod, "data_function", None) + while function is not None and id(function) not in visited: + visited.add(id(function)) + found.append(getattr(function, "result_database", None)) + function = getattr(function, "_data_function", None) # a wrapper's inner + return found + + def _job_name(node: Any) -> str: """The name of the job ``node`` belongs to: its pipeline database's location.""" database = getattr(node, "_pipeline_database", None) @@ -270,8 +296,9 @@ def store_scope_databases( """The databases a run may write, for its writer leases (``store_write_scope``). A full run may write ``databases`` (a job's database and result database), the - databases of the job nodes in ``streams`` and of every job node they depend on, and - the cache of every ``CachedSource`` feeding them. A load-only run writes none of + databases of the job nodes in ``streams`` and of every job node they depend on + (a function pod's own result databases included), and the cache of every + ``CachedSource`` feeding them. A load-only run writes none of the nodes' databases; it may still write a cached source's cache, which takes in new rows when checked or read. Each node is visited once. @@ -286,7 +313,12 @@ def store_scope_databases( written: list[Any] = [] if not load_only: written.extend(databases) - written.extend(_databases(_job_nodes_under(streams))) + nodes = _job_nodes_under(streams) + written.extend(_databases(nodes)) + # A function pod's own result databases are written on a cache miss too. + written.extend( + db for node in nodes for db in _pod_result_databases(node) if db is not None + ) written.extend(_cache_databases(streams)) return written diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index 47581667e..8caf4a877 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -842,3 +842,123 @@ def counting_getattr(obj: Any, name: str, *default: Any) -> Any: small, large = reads_per_node(50), reads_per_node(400) assert large <= small * 1.1 + 0.5 + + +# ------------------------------------------------- review of 291798da3 (ITL-1844) + + +def test_a_job_on_a_shared_store_connector_takes_the_lease_after_its_original_is_gone( + root: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A store connector's ``share_client`` copy is a registered store connector: with + the original closed and collected (and no other store connector in the process), + a job on the copy still takes the lease and stores as on Delta.""" + import gc + + monkeypatch.setattr(spiraldb_store_registry, "_store_connectors", weakref.WeakSet()) + original = SpiralDBConnector("p", "d", store=True) + shared = original.share_client() + original.close() + del original + _ = gc.collect() + store = ConnectorArrowDatabase(shared) + delta = DeltaTableDatabase(root / "delta") + assert _job(store).run().ok + assert _job(delta).run().ok + _same_tables(store, delta) + + +@pytest.mark.usefixtures("root") +def test_a_job_on_a_store_connector_and_its_shared_copy_runs() -> None: + """Two connectors sharing one store (``share_client``) bound in one run hold the + dataset's one lease once: the run is not refused when it starts.""" + connector = SpiralDBConnector("p", "d", store=True) + store = ConnectorArrowDatabase(connector) + results = ConnectorArrowDatabase(connector.share_client()) + assert _job(store, result_database=results.at("results")).run().ok + assert results.list_table_paths(("results",)) != [] + # Released at the end: another writer can take the lease. + _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") + again() + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("body_fails", [False, True]) +def test_an_interrupted_let_go_still_releases_every_lease( + monkeypatch: pytest.MonkeyPatch, body_fails: bool +) -> None: + """An interruption while a lease is let go of locally does not skip its remote + release nor the other leases': every lease can be taken again, and the + interruption raises (chained from a failed body's error).""" + from orcapod.databases.spiraldb_store_tables import StoreTables + + real = StoreTables.let_go_of_lease + interrupted: list[None] = [] + + def interrupt_first(self: Any, check: Any) -> None: + if not interrupted: + interrupted.append(None) + raise KeyboardInterrupt + real(self, check) + + monkeypatch.setattr(StoreTables, "let_go_of_lease", interrupt_first) + databases = [_store("d"), _store("r")] + with pytest.raises(KeyboardInterrupt) as raised: + with store_writes(databases, owner="test"): + if body_fails: + raise RuntimeError("body") + if body_fails: + cause = raised.value.__cause__ + assert isinstance(cause, RuntimeError) and str(cause) == "body" + monkeypatch.undo() + for dataset in ("d", "r"): + _, again = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + again() + + +@pytest.mark.usefixtures("root") +def test_a_release_interruption_outranks_an_earlier_release_error( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """After a successful body, a release that fails with an error and a later one + interrupted raise the interruption, with the error as a note on it.""" + real = spiraldb_lease.release + seen: list[None] = [] + + def fail_then_interrupt(client: Any, lease: Any) -> None: + seen.append(None) + real(client, lease) + if len(seen) == 1: + raise spiraldb_lease.LeaseError("first release failed") + raise KeyboardInterrupt + + monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) + with pytest.raises(KeyboardInterrupt) as raised: + with store_writes([_store("d"), _store("r")], owner="test"): + pass + assert len(seen) == 2 + assert any("first release failed" in note for note in raised.value.__notes__) + + +def test_a_decorator_result_database_on_a_store_is_leased(root: Path) -> None: + """A function pod's own result database (``@function_pod(result_database=...)``) + on a store is written under the run's lease on a cache miss, and a pod cache + database (``pod_cache_database``) too.""" + on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) + pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", store=True)) + + @function_pod( + output_keys=("total",), + result_database=on_store.at("decorator"), + pod_cache_database=pod_cache.at("pod"), + ) + def add(x: int, y: int) -> int: + return x + y + + store = _store() + job = PipelineJob(name=JOB, database=store) + with job: + add.pod(_cached(store, _rows()), label="add") + assert job.run().ok + assert on_store.list_table_paths(("decorator",)) != [] + assert pod_cache.list_table_paths(("pod",)) != [] diff --git a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py index 65c39fa10..056ecc65e 100644 --- a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py +++ b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py @@ -3,10 +3,13 @@ from __future__ import annotations import importlib.util +import json +import sys from pathlib import Path from types import ModuleType from typing import Any +import pyarrow as pa import pytest _SCRIPT = ( @@ -32,7 +35,8 @@ def _expected() -> dict[str, dict[str, Any]]: "first run": {"ok": True, "calls_on_store": 6}, "new row": {"ok": True, "calls_on_store": 1, "delivered_on_store": 1}, "replay": {"ok": True}, - "save and load": {"ok": True, "store_flag_saved": True}, + "separate results": {"ok": True}, + "save and load": {"ok": True, "store_flag_saved": True, "load_only_rows": 7}, "second writer": {"refused": True, "nothing_written": True}, } @@ -48,6 +52,8 @@ def test_the_expected_outcomes_succeed(script: ModuleType) -> None: ("new row", "calls_on_store", 7), ("new row", "delivered_on_store", 7), ("save and load", "store_flag_saved", False), + ("save and load", "load_only_rows", 0), + ("separate results", "ok", False), ("second writer", "refused", False), ("second writer", "nothing_written", False), ("replay", "ok", False), @@ -60,3 +66,76 @@ def test_a_wrong_recorded_outcome_fails( scenarios = _expected() scenarios[scenario][key] = value assert not script.succeeded(scenarios) + + +def test_a_column_of_another_arrow_type_is_not_comparable_equal( + script: ModuleType, +) -> None: + """Values that print alike but differ in Arrow type (int32 against int64) or in + native type (the text "1" against the integer 1) do not compare equal.""" + as_int64 = pa.table({"trial": pa.array([1, 2], pa.int64())}) + assert script.same_table( + as_int64, pa.table({"trial": pa.array([2, 1], pa.int64())}) + ) + assert not script.same_table( + as_int64, pa.table({"trial": pa.array([1, 2], pa.int32())}) + ) + assert not script.same_table( + pa.table({"v": pa.array(["1"], pa.large_string())}), + pa.table({"v": pa.array([1], pa.int64())}), + ) + + +class _Listing: + def __init__(self, tables: dict[tuple[str, ...], pa.Table]) -> None: + self.tables = tables + + def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: + return [p for p in self.tables if p[: len(prefix)] == prefix] + + def get_all_records(self, path: tuple[str, ...]) -> pa.Table | None: + return self.tables.get(path) + + +def test_separate_results_are_compared_table_by_table(script: ModuleType) -> None: + """Each store result table (under ``/results``) is compared with the same + path in the result database, and every other table with Delta: a wrong row in one + result table fails the scenario even when the table count matches.""" + one = pa.table({"v": pa.array([1], pa.int64())}) + other = pa.table({"v": pa.array([2], pa.int64())}) + delta = _Listing({("j", "pdb_v2"): one}) + results = _Listing({("f", "rdb_v1"): one}) + right = _Listing({("j", "pdb_v2"): one, ("j", "results", "f", "rdb_v1"): one}) + wrong = _Listing({("j", "pdb_v2"): one, ("j", "results", "f", "rdb_v1"): other}) + expected = script.separate_results_expected("j", delta, results) + assert script.compare_paths(right, expected, ("j",))["ok"] + assert not script.compare_paths(wrong, expected, ("j",))["ok"] + + +def test_a_failing_inventory_still_prints_the_report( + script: ModuleType, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + """With the service down (every inventory raises after a scenario failed), the + JSON report is printed with the scenario's error and the inventory errors apart.""" + + def down(*args: object) -> list[dict[str, str]]: + raise ConnectionError("service down") + + def failing(*args: object) -> None: + raise ConnectionError("scenario failed") + + monkeypatch.setattr(script, "lease_tables", down) + monkeypatch.setattr(script, "store_tables", down) + monkeypatch.setattr(script, "evaluate", failing) + monkeypatch.setattr(sys, "argv", ["itl_1844_store_evaluation.py", "fake"]) + assert script.main() == 1 + report = json.loads(capsys.readouterr().out) + assert report["ok"] is False + assert report["error"] == "ConnectionError: scenario failed" + assert set(report["inventory_errors"]) == { + "lease tables before", + "store tables", + "lease tables after", + } From 9bdd52367966591a4bdc0e2db577b463f77add01 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:32:35 -0800 Subject: [PATCH 37/50] docs(spiraldb): clear() names the project and dataset of the lease (ITL-1844) #690 changed spiraldb_lease.clear to take the project and dataset: the concept page, the changelog fragment and the store-run test use the new call. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1844.md | 3 ++- docs/concepts/spiraldb-store.md | 12 +++++++++--- tests/test_databases/test_spiraldb_store_runs.py | 6 +++++- 3 files changed, 16 insertions(+), 5 deletions(-) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index c97513f7e..e6d6dd92b 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -10,7 +10,8 @@ take the dataset's writer lease before checking a source or writing anything, and release it when they end, also when they fail. A second writer is refused then with `LeaseBusyError`, before anything of its run happens. A stale lease is cleared by its - table id with `spiraldb_lease.clear(..., confirm_writer_stopped=True)`. + project, dataset and table id with + `spiraldb_lease.clear(client, project_id, dataset, table_id, confirm_writer_stopped=True)`. - A job saved on a store records `store: true` and no credential; `PipelineJob.load` takes the connector again and refuses a SpiralDB connector of the other kind. diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md index ab1371062..5eb50b48f 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-store.md @@ -79,7 +79,8 @@ source it reads. A process that stops in the middle of a run (killed, or a lost connection) leaves its lease held, and every later run is refused. Once you are sure that writer has stopped, -and every write it sent has settled, clear the lease by the table id the refusal named: +and every write it sent has settled, clear the lease by the project, dataset and table +id the refusal named (its message spells out the call): ```python @@ -88,14 +89,19 @@ import spiral from orcapod.databases import spiraldb_lease spiraldb_lease.clear( - spiral.Client(), "
", confirm_writer_stopped=True + spiral.Client(), + "", + "", + "
", + confirm_writer_stopped=True, ) ``` `spiral.Client()` connects to the default service. When the job's connector was made for another service address (`SpiralDBConnector(..., overrides={"server.url": ...})`), make the client for that same address, with a sign-in allowed to update the dataset: -a client of another service does not find the table id. +a client of another service does not find the table id. Only the dataset's newest lease +table can be cleared: any other table id is refused and nothing is written. Clearing the lease of a writer that is still running lets a second writer in while the first is still writing. Each lease is a small keyed table of the dataset; keep every diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index 8caf4a877..b2fb290eb 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -574,7 +574,11 @@ def test_the_lease_raises_no_keyed_table_deprecation() -> None: with pytest.raises(spiraldb_lease.LeaseBusyError) as refused: _ = take_lease(connector, "second") spiraldb_lease.clear( - fake.FakeClient(), refused.value.table_id, confirm_writer_stopped=True + fake.FakeClient(), + "p", + "d", + refused.value.table_id, + confirm_writer_stopped=True, ) _, again = take_lease(connector, "third") again() From f8399f75b0c72536c863bbe8df4d39f3e65111f6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:43:54 -0800 Subject: [PATCH 38/50] docs(changelog): limit the ITL-1838 known limitation to tables with a schema-table row Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1838.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.d/ITL-1838.md b/changelog.d/ITL-1838.md index e49f6ffeb..9a52ae348 100644 --- a/changelog.d/ITL-1838.md +++ b/changelog.d/ITL-1838.md @@ -8,4 +8,4 @@ ### Known limitations -- In a SpiralDB dataset already migrated with `scripts/migrate_spiral_schemas.py`, a table with a reserved writer lease name cannot be read after the upgrade, renamed or not: its row in `__orcapod_schemas__` keeps the old name, and the connector refuses a table whose row names another name. No supported step updates that row yet (ITL-1860). +- A table with a reserved writer lease name that has a row in `__orcapod_schemas__` (its dataset was migrated with `scripts/migrate_spiral_schemas.py` while the table had that name) cannot be read after the upgrade, renamed or not: the row keeps the old name, and the connector refuses a table whose row names another name. No supported step updates that row yet (ITL-1860). A renamed table with no row is read with the schema SpiralDB reports, with the usual warning. From e1581afe9a04a4ac912c6eeccd3bd5049fc733f4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 23:08:11 -0800 Subject: [PATCH 39/50] fix(spiraldb): a shared copy has its own store tables; a let-go is completed; bound pod streams are leased (ITL-1844) - share_client gives a store connector's copy its own StoreTables, so a write through the copy outside the run is refused; a run on both takes one lease and attaches it to both. - An interrupted let-go of a lease is completed, so the next run on the same databases is not refused at hold_lease. - The lease walk through bound sources also collects the result databases of a function pod stream built outside the job (result_database and pod_cache_database). Co-Authored-By: Claude Opus 5.5 --- docs/concepts/spiraldb-store.md | 2 +- src/orcapod/databases/spiraldb_connector.py | 45 ++++++---- src/orcapod/databases/spiraldb_write_scope.py | 6 ++ src/orcapod/pipeline/node_run.py | 28 +++--- .../test_spiraldb_store_runs.py | 87 ++++++++++++++++++- 5 files changed, 135 insertions(+), 33 deletions(-) diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md index 5eb50b48f..fc023f936 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-store.md @@ -68,7 +68,7 @@ except LeaseBusyError as refused: Only a job run writes a store, through the store connectors it holds the lease with (those of its databases and of the cached sources it reads). A write through any other store connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a -connector of its own flushed directly) raises `SpiralDBStoreLeaseRequiredError` before +connector of its own or over a `share_client()` copy, flushed directly) raises `SpiralDBStoreLeaseRequiredError` before anything is written, also while a run holds the dataset's lease. A write through a running job's own databases from outside the run (another thread, an observer) is not told apart from the run's own: do not write through them while the job runs. A diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 8f066eca1..41df46be6 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -1031,22 +1031,28 @@ def __init__( if store: # A run looks for store leases only while a store connector exists. register_store_connector(self) - self._store = StoreTables( - sp, - project_id, - dataset, - lambda name: _open_keyed_table( - client, project_id, dataset, name, health - ), - lambda table_id: _open_keyed_table_by_id(client, table_id), - lambda name, key: _create_keyed_table( - client, project_id, dataset, name, key, exist_ok=False - ), - lambda: _list_keyed_tables(client, project_id, dataset), - lambda doing: _service_call( - f"{doing} of {project_id}/{dataset}", health - ), - ) + self._store = self._new_store_tables() + + def _new_store_tables(self) -> StoreTables: + """The store's tables of this connector's dataset, over its SDK client. + + Each store connector has its own, so the writer lease a run attaches to one + connector's tables never lets another connector write (``share_client`` too). + """ + client, health = self._client, self._health + project_id, dataset = self._project_id, self._dataset + return StoreTables( + sp, + project_id, + dataset, + lambda name: _open_keyed_table(client, project_id, dataset, name, health), + lambda table_id: _open_keyed_table_by_id(client, table_id), + lambda name, key: _create_keyed_table( + client, project_id, dataset, name, key, exist_ok=False + ), + lambda: _list_keyed_tables(client, project_id, dataset), + lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), + ) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" @@ -1093,11 +1099,14 @@ def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope. A store connector's copy is a store connector too, registered as one, so a - run on it takes the dataset's writer lease also after the original is gone. + run on it takes the dataset's writer lease also after the original is gone. It + has its own store tables: a run's lease held through one of the two never lets + the other write. """ self._require_open() shared = copy(self) if self._store_mode: + shared._store = shared._new_store_tables() # pyright: ignore[reportPrivateUsage] # a copy of this class register_store_connector(shared) return shared @@ -1520,7 +1529,7 @@ def close(self) -> None: del self._shared del self._schemas # The store's tables hold the client too; a connector from - # ``share_client`` keeps its own reference to them. + # ``share_client`` has its own. self._store = None def __enter__(self) -> SpiralDBConnector: diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 85f377e74..27cb897e2 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -165,6 +165,12 @@ def _release_all( tables.let_go_of_lease(check) except BaseException as exc: # noqa: BLE001 # an interruption too: the remote release is still attempted failures.append(exc) + # Let go again (idempotent), so the next run on these tables is not + # refused for a lease still attached. + try: + tables.let_go_of_lease(check) + except BaseException as again: # noqa: BLE001 # reported with the others + failures.append(again) try: release() except BaseException as exc: # noqa: BLE001 # an interrupted release too: every lease is released; failures are reported below diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index a737ed97f..185785cb5 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -241,11 +241,15 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found -def _cache_databases(streams: Iterable[Any]) -> list[Any]: - """The databases of every ``CachedSource`` feeding ``streams`` (a cached source - writes its cache when it is checked or read), through wrapped sources and streams. - - Each stream is visited once (linear in the size of the graph). +def _source_side_databases(streams: Iterable[Any]) -> list[Any]: + """The databases written by what feeds ``streams`` from outside the job's nodes, + through bound sources, wrapped sources and streams. + + The cache of every ``CachedSource`` (written when it is checked or read), and the + result databases of every function pod stream met (a stream built outside the job + and bound to a slot computes, and writes its pod's caches, when the run reads it; + ``_pod_result_databases``). Each stream is visited once (linear in the size of the + graph). """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource @@ -264,6 +268,8 @@ def _cache_databases(streams: Iterable[Any]) -> list[Any]: continue if isinstance(stream, CachedSource): found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the store a run must hold the lease of + if not _is_job_node(stream): # a job node's pods: ``store_scope_databases`` + found.extend(db for db in _pod_result_databases(stream) if db is not None) inputs = getattr(stream, "live_source_inputs", None) pending.extend(inputs or ()) pending.extend(getattr(stream, "upstreams", ())) @@ -297,10 +303,12 @@ def store_scope_databases( A full run may write ``databases`` (a job's database and result database), the databases of the job nodes in ``streams`` and of every job node they depend on - (a function pod's own result databases included), and the cache of every - ``CachedSource`` feeding them. A load-only run writes none of - the nodes' databases; it may still write a cached source's cache, which takes in - new rows when checked or read. Each node is visited once. + (a function pod's own result databases included), and what feeds them from + outside the job's nodes: the cache of every ``CachedSource`` and the result + databases of a function pod stream bound to a slot (``_source_side_databases``). + A load-only run writes none of the nodes' databases; it may still write a cached + source's cache, which takes in new rows when checked or read (it refuses a + function pod stream). Each node is visited once. Args: streams: The nodes of the run, or the node whose ``run()`` it is. @@ -319,7 +327,7 @@ def store_scope_databases( written.extend( db for node in nodes for db in _pod_result_databases(node) if db is not None ) - written.extend(_cache_databases(streams)) + written.extend(_source_side_databases(streams)) return written diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index b2fb290eb..e234344c6 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -873,14 +873,31 @@ def test_a_job_on_a_shared_store_connector_takes_the_lease_after_its_original_is @pytest.mark.usefixtures("root") -def test_a_job_on_a_store_connector_and_its_shared_copy_runs() -> None: - """Two connectors sharing one store (``share_client``) bound in one run hold the - dataset's one lease once: the run is not refused when it starts.""" +def test_a_job_on_a_store_connector_and_its_shared_copy_runs( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A connector and its ``share_client`` copy bound in one run: the run takes ONE + lease of the dataset and attaches it to the store tables of both.""" + from orcapod.databases.spiraldb_store_tables import StoreTables + connector = SpiralDBConnector("p", "d", store=True) store = ConnectorArrowDatabase(connector) - results = ConnectorArrowDatabase(connector.share_client()) + shared = connector.share_client() + results = ConnectorArrowDatabase(shared) + held: list[tuple[object, object]] = [] + real_hold = StoreTables.hold_lease + + def recording_hold(self: Any, check: Any) -> None: + held.append((self, check)) + real_hold(self, check) + + monkeypatch.setattr(StoreTables, "hold_lease", recording_hold) assert _job(store, result_database=results.at("results")).run().ok assert results.list_table_paths(("results",)) != [] + assert len(_lease_tables()) == 1 + tables = [connector._store_tables(), shared._store_tables()] # pyright: ignore[reportPrivateUsage] + assert len(held) == 2 and held[0][1] is held[1][1] + assert {id(t) for t, _ in held} == {id(t) for t in tables} # Released at the end: another writer can take the lease. _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") again() @@ -918,6 +935,9 @@ def interrupt_first(self: Any, check: Any) -> None: for dataset in ("d", "r"): _, again = take_lease(SpiralDBConnector("p", dataset, store=True), "after") again() + # The same databases run again: no lease was left attached to their tables. + with store_writes(databases, owner="next run"): + pass @pytest.mark.usefixtures("root") @@ -966,3 +986,62 @@ def add(x: int, y: int) -> int: assert job.run().ok assert on_store.list_table_paths(("decorator",)) != [] assert pod_cache.list_table_paths(("pod",)) != [] + + +@pytest.mark.usefixtures("root") +def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: + """A ``share_client`` copy is another connector: while a run holds the lease + through the original, a write through the copy (not part of the run) is refused + and nothing is written.""" + connector = SpiralDBConnector("p", "d", store=True) + outside = ConnectorArrowDatabase(connector.share_client()) + row = pa.table( + { + "__data_context": pa.array(["std:v1:default"], pa.large_string()), + "v": pa.array([1], pa.int64()), + } + ) + with store_writes([ConnectorArrowDatabase(connector)], owner="run"): + outside.add_record(("elsewhere",), b"r", row, flush=False) + with pytest.raises(SpiralDBStoreLeaseRequiredError): + outside.flush() + assert _store().list_table_paths(("elsewhere",)) == [] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +@pytest.mark.parametrize("cache", ["result_database", "pod_cache_database"]) +def test_a_bound_function_pod_stream_built_outside_the_job_is_leased( + entry: str, cache: str +) -> None: + """A function pod stream built outside the job (it becomes a bound slot) whose + pod caches on a store (``result_database``, or a ``CachedFunctionPod`` through + ``pod_cache_database``) writes under the run's lease.""" + on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) + + def add(x: int, y: int) -> int: + return x + y + + if cache == "result_database": + pod = function_pod( + output_keys=("total",), result_database=on_store.at("outside") + )(add) + else: + pod = function_pod( + output_keys=("total",), pod_cache_database=on_store.at("outside") + )(add) + + outside = pod.pod( + ArrowTableSource( + _rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ) + ) + job = PipelineJob(name=JOB, database=_store()) + with job: + SelectDataColumns(["total"])(outside, label="select") + _ = _run(job, entry) + assert on_store.list_table_paths(("outside",)) != [] From c688296ee4a05af20fdafcc030b161fe8bbdbb51 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 23:45:02 -0800 Subject: [PATCH 40/50] test(spiraldb): a shared copy holds the test's lease on its own store tables (ITL-1844) A share_client copy now has its own store tables (e1581afe9), so the closed- connector test attaches its lease to the copy before writing through it. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_write_scope.py | 4 ++-- tests/test_databases/test_spiraldb_store_mode.py | 4 +++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index 27cb897e2..bc864916b 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -85,8 +85,8 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: try: for connectors in groups.values(): check, release = take_lease(connectors[0], owner) - # The store tables holding this lease: once each, as two connectors can - # share one (``SpiralDBConnector.share_client``). + # The store tables holding this lease, each once (every store connector has + # its own, ``share_client`` copies too; a repeat is skipped all the same). holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # StoreTables held.append((holding, check, release)) for connector in connectors: diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py index a711f12d0..7a054b8e9 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -1087,7 +1087,9 @@ def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() - ): with pytest.raises(RuntimeError, match="closed"): _ = call() - # the connector sharing its client keeps its own reference + # the connector sharing its client keeps its own reference; it has its own store + # tables, so the test's lease is attached to them too (as a run attaches it) + tables_of(shared).hold_lease(_test_leases[("p", "d")][0]) other = ConnectorArrowDatabase(shared) other.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert other.table_exists(RESULT) From fcf67d5ee2a2a282eb35195fa2a59203bc9a731e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 23:57:07 -0800 Subject: [PATCH 41/50] fix(spiraldb_lease): guard token verification; name both clear prerequisites - An interruption or error while the created claim's token is verified releases the claim after a fresh lookup confirms the caller's token; acquire now calls _claim_generation inside its guarded block, and its docstring names the one remaining unguarded point. - The stale-lease refusal asks to confirm that the writer has stopped and all its pending writes have settled before calling clear. - The migration dry run's refusal says to rename before migrating, and for a dataset that already has a schema table, that a rename does not update a row it holds (ITL-1860). Co-Authored-By: Claude Opus 5.5 --- scripts/migrate_spiral_schemas.py | 22 ++++-- src/orcapod/databases/spiraldb_lease.py | 76 +++++++++++++------ .../test_migrate_spiral_schemas.py | 34 ++++++++- tests/test_databases/test_spiral_lease.py | 26 ++++++- 4 files changed, 127 insertions(+), 31 deletions(-) diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index a608a4a8e..6d15163b8 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -281,19 +281,29 @@ def dry_run(args: argparse.Namespace) -> None: # A reserved name holds a writer lease generation, which is not migrated, or a # table the upgraded connector no longer reads: refuse before planning anything. generations: dict[str, list[str]] = {} - collisions: list[str] = [] + collisions: dict[str, list[str]] = {} for dataset, connector in connectors.items(): for name in sorted(reserved.get(dataset, [])): if is_lease_generation(table_key_columns(connector, name)): generations.setdefault(dataset, []).append(name) else: - collisions.append(f"{args.project}/{dataset}/{name}") + collisions.setdefault(dataset, []).append(name) if collisions: - raise MigrationError( - f"table(s) {collisions} have names reserved for writer lease generations " - "but are not lease generations; Orcapod on spiral-sdk does not read them. " - "Rename them, then run the dry run again" + named = [ + f"{args.project}/{d}/{n}" for d, names in collisions.items() for n in names + ] + message = ( + f"table(s) {named} have names reserved for writer lease generations but " + "are not lease generations; Orcapod on spiral-sdk does not read them. " + "Rename them before migrating" ) + if migrated := [d for d in collisions if d in schema_tables]: + message += ( + f". Dataset(s) {migrated} already have {SCHEMA_TABLE}: renaming does not " + "update a row it holds for such a table, and no supported step does " + "yet (ITL-1860)" + ) + raise MigrationError(message) plan: dict[str, Any] = { "format": PLAN_FORMAT, "version": PLAN_VERSION, diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 21c1232b5..b5d4063a2 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -125,7 +125,10 @@ def __init__( recovery = ( "The conflicting lease was released. Retry acquisition." if released - else f"If the lease is stale, confirm the writer has stopped and call {how_to_clear}." + else ( + "If the lease is stale, confirm that the writer has stopped and all " + f"its pending writes have settled, then call {how_to_clear}." + ) ) super().__init__( f"{conflict} ({description}, table ID {table_id!r}). {recovery}" @@ -258,29 +261,51 @@ def _claim_generation( project_id, dataset, found.resource_id, state.owner, released=state.released ) from exc except BaseException as exc: - claimed_id: str | None = None - try: - found = _open(client, project_id, dataset, generation) - if found is not None and spiral_lease_key_column(found.key_columns) == key: - claimed_id = found.resource_id - _write_release(client, found, key) - except BaseException as cleanup_error: - where = ( - f"writer lease table ID {claimed_id!r}" - if claimed_id is not None - else f"generation {generation}" - ) - exc.add_note( - f"Reconciling interrupted writer lease creation ({where}) also " - f"failed: {cleanup_error!r}" - ) + _release_if_claimed(client, project_id, dataset, generation, key, exc) raise - if _key(claimed) != key: + try: + verified = _key(claimed) == key + except BaseException as exc: + _release_if_claimed(client, project_id, dataset, generation, key, exc) + raise + if not verified: raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") return claimed +def _release_if_claimed( + client: _Client, + project_id: str, + dataset: str, + generation: int, + key: str, + interrupted: BaseException, +) -> None: + """Release the generation if a fresh lookup shows the caller's token. + + Used when creating or verifying a claim stops part way. A generation that + carries another token is left untouched. A failure of this cleanup is noted on + ``interrupted``, which the caller re-raises. + """ + claimed_id: str | None = None + try: + found = _open(client, project_id, dataset, generation) + if found is not None and spiral_lease_key_column(found.key_columns) == key: + claimed_id = found.resource_id + _write_release(client, found, key) + except BaseException as cleanup_error: + where = ( + f"writer lease table ID {claimed_id!r}" + if claimed_id is not None + else f"generation {generation}" + ) + interrupted.add_note( + f"Reconciling interrupted writer lease creation ({where}) also " + f"failed: {cleanup_error!r}" + ) + + def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Lease: """Claim a dataset for one writer or raise before any store data can be written. @@ -298,7 +323,9 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le LeaseError: If the claim or its state cannot be verified. TimeoutError: If an SDK operation times out and the error propagates. Other SDK transport errors can also propagate unchanged. After claiming, - acquisition attempts release before re-raising. + acquisition attempts release before re-raising. The one unguarded point + is between the claim's return and its assignment: an interruption there + leaves the generation held until it is cleared. """ generation, latest = _newest(client, project_id, dataset) if latest is not None: @@ -308,11 +335,12 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le key = f"{SPIRAL_LEASE_KEY_PREFIX}{uuid4().hex}" row = _row(key, _CLAIM, owner, datetime.now(timezone.utc).isoformat()) - claimed = _claim_generation(client, project_id, dataset, generation + 1, key) - # From here the claim is confirmed as this caller's: every exit but a verified - # lease releases it. Owner details and release are different keys, so an - # operator's release survives even if the owner write publishes after it. + claimed: _KeyedTable | None = None + # Once the claim is confirmed as this caller's, every exit but a verified lease + # releases it. Owner details and release are different keys, so an operator's + # release survives even if the owner write publishes after it. try: + claimed = _claim_generation(client, project_id, dataset, generation + 1, key) lease = Lease(claimed.resource_id, key, os.getpid()) try: _ = claimed.append(row) @@ -327,6 +355,8 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le else: check(client, lease) except BaseException as exc: + if claimed is None: + raise # The claim token was verified and no store writes could start. The release # row can be written even if reading the current lease state failed. try: diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 442a253b2..39f8137e3 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -198,11 +198,13 @@ def _legacy_listing( args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch, reserved: list[tuple[str, str, list[str]]], + schema_tables: tuple[str, ...] = (), ) -> tuple[dict[str, Any], list[str]]: """List the planned tables and ``reserved`` (dataset, name, key columns) as the pyspiral client would, and return the plan and the reserved names opened. - Each reserved name is used in one dataset only. + Each reserved name is used in one dataset only. ``schema_tables`` names the + datasets whose listing also holds a schema table. The tables under reserved names are made on the fake; the dry run's table descriptions are the plan's, and the key columns it reads are recorded. @@ -228,6 +230,10 @@ def _legacy_listing( assert name not in keys, "reserved names are distinct across datasets here" keys[name] = key_columns listed.append(SimpleNamespace(dataset=dataset, table=name, id=made.resource_id)) + listed.extend( + SimpleNamespace(dataset=dataset, table=st.SCHEMA_TABLE, id=f"schemas-{dataset}") + for dataset in schema_tables + ) opened: list[str] = [] def key_columns_of(_connector: Any, name: str) -> list[str]: @@ -306,6 +312,8 @@ def test_dry_run_refuses_a_reserved_name_table_without_a_lease_key( with pytest.raises(tool.MigrationError, match="Rename them") as refused: tool.dry_run(args) message = str(refused.value) + assert "run the dry run again" not in message + assert "ITL-1860" not in message assert f"{args.project}/{first}/{spiral_lease_table_name(2)}" in message assert f"{args.project}/{second}/{spiral_lease_table_name(3)}" in message assert spiral_lease_table_name(1) not in message @@ -645,3 +653,27 @@ def test_the_principal_is_named_and_the_token_is_not(tool: ModuleType) -> None: body = base64.urlsafe_b64encode(b'{"sub": "work_1"}').decode().rstrip("=") assert tool.principal_of(f"head.{body}.secret") == "work_1" + + +def test_dry_run_refusal_names_the_existing_schema_row_limitation( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """When a dataset with a colliding table already has a schema table, the refusal + says that a rename does not update a row it holds (ITL-1860), naming only that + dataset.""" + first, second = args.dataset[:2] + _ = _legacy_listing( + tool, + args, + monkeypatch, + [ + (first, spiral_lease_table_name(1), ["k"]), + (second, spiral_lease_table_name(2), ["k"]), + ], + schema_tables=(second,), + ) + with pytest.raises(tool.MigrationError, match="ITL-1860") as refused: + tool.dry_run(args) + message = str(refused.value) + assert "Rename them before migrating" in message + assert f"Dataset(s) {[second]!r} already have {st.SCHEMA_TABLE}" in message diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 3cbc46c7a..55c9c7ebe 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -3,7 +3,7 @@ from __future__ import annotations import warnings -from collections.abc import Iterator +from collections.abc import Iterator, Sequence from pathlib import Path import pyarrow as pa @@ -90,6 +90,7 @@ def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) f"spiraldb_lease.clear(client, {_PROJECT!r}, {_DATASET!r}, " f"{first.table_id!r}, confirm_writer_stopped=True)" ) in message + assert "all its pending writes have settled" in message with pytest.raises(ValueError, match="stopped"): clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=False) check(client, first) @@ -844,3 +845,26 @@ def test_clear_refuses_a_table_that_is_not_the_newest_generation( assert client.keyed_table_by_id(table_id).version_id == before check(client, holder) check(client, elsewhere) + + +def test_interrupt_during_token_verification_releases_the_claim( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """An interruption while the created claim's token is verified releases the claim + after a fresh lookup confirms the token, and the interruption propagates.""" + recognize = spiraldb_lease.spiral_lease_key_column + interrupted = KeyboardInterrupt("interrupted during token verification") + calls: list[int] = [] + + def interrupt_first(keys: Sequence[str]) -> str | None: + calls.append(1) + if len(calls) == 1: + raise interrupted + return recognize(keys) + + with monkeypatch.context() as patch: + patch.setattr(spiraldb_lease, "spiral_lease_key_column", interrupt_first) + with pytest.raises(KeyboardInterrupt) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is interrupted + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) From 551440700bbf756e2b0640e81cac1002bc86d74e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 00:08:43 -0800 Subject: [PATCH 42/50] fix(spiraldb_lease): reconcile every exit of a claim before it is returned _claim_generation now wraps the whole create-and-verify step: any error or interruption before the claim is returned (the create, a lost-reply lookup, the token check) releases the generation after a fresh lookup by name, only if that table carries the caller's token. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_lease.py | 32 +++++++++------ tests/test_databases/test_spiral_lease.py | 48 +++++++++++++++++++++++ 2 files changed, 68 insertions(+), 12 deletions(-) diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index b5d4063a2..61065b20e 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -230,7 +230,24 @@ def _row( def _claim_generation( client: _Client, project_id: str, dataset: str, generation: int, key: str ) -> _KeyedTable: - """Make one exclusive create attempt and reconcile a lost reply by token.""" + """Make one exclusive create attempt and reconcile a lost reply by token. + + Any exit other than returning the caller's claim, by an error or an + interruption at any step (the create, a lost-reply lookup, the token check), + releases the generation after a fresh lookup by name, and only if that table + carries the caller's token. Another writer's claim is left untouched. + """ + try: + return _create_and_verify(client, project_id, dataset, generation, key) + except BaseException as exc: + _release_if_claimed(client, project_id, dataset, generation, key, exc) + raise + + +def _create_and_verify( + client: _Client, project_id: str, dataset: str, generation: int, key: str +) -> _KeyedTable: + """Create the generation exclusively and confirm it carries the caller's token.""" name = spiral_lease_table_name(generation) key_schema = pa.schema([pa.field(key, pa.large_string(), nullable=False)]) try: @@ -260,16 +277,7 @@ def _claim_generation( raise LeaseBusyError( project_id, dataset, found.resource_id, state.owner, released=state.released ) from exc - except BaseException as exc: - _release_if_claimed(client, project_id, dataset, generation, key, exc) - raise - - try: - verified = _key(claimed) == key - except BaseException as exc: - _release_if_claimed(client, project_id, dataset, generation, key, exc) - raise - if not verified: + if _key(claimed) != key: raise LeaseError(f"Unexpected claim token in table ID {claimed.resource_id!r}") return claimed @@ -284,7 +292,7 @@ def _release_if_claimed( ) -> None: """Release the generation if a fresh lookup shows the caller's token. - Used when creating or verifying a claim stops part way. A generation that + Used when claiming a generation stops before the claim is returned. A generation that carries another token is left untouched. A failure of this cleanup is noted on ``interrupted``, which the caller re-raises. """ diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 55c9c7ebe..83574bf9a 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -868,3 +868,51 @@ def interrupt_first(keys: Sequence[str]) -> str | None: _ = acquire(client, _PROJECT, _DATASET, owner="first") assert caught.value is interrupted check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +def test_interrupted_lost_reply_lookup_releases_the_claim( + client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch +) -> None: + """A create that commits but loses its reply, followed by an interruption during + the lost-reply lookup, releases the claim after a fresh lookup confirms the + caller's token; the interruption propagates. ``lose_reply`` commits the create + before it raises.""" + create = fake.FakeProject.create_keyed_table + open_by_name = fake.FakeClient.keyed_table + interrupted = KeyboardInterrupt("lost-reply lookup interrupted") + created: list[str] = [] + lookups: list[str] = [] + + def lose_reply( + project: fake.FakeProject, + dataset: str, + name: str, + key_schema: pa.Schema, + *, + exist_ok: bool = False, + ) -> fake.FakeKeyedTable: + _ = create(project, dataset, name, key_schema, exist_ok=exist_ok) + created.append(name) + raise TimeoutError("lost reply") + + def interrupt_first_lookup( + instance: fake.FakeClient, + project: str, + dataset: str, + name: str, + *, + asof: int | None = None, + ) -> fake.FakeKeyedTable: + if created and not lookups: + lookups.append(name) + raise interrupted + return open_by_name(instance, project, dataset, name, asof=asof) + + with monkeypatch.context() as patch: + patch.setattr(fake.FakeProject, "create_keyed_table", lose_reply) + patch.setattr(fake.FakeClient, "keyed_table", interrupt_first_lookup) + with pytest.raises(KeyboardInterrupt) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first") + assert caught.value is interrupted + assert lookups == [spiral_lease_table_name(1)] + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) From 387156f507af6bcd022ed4cad6e092c312bc5593 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 00:44:06 -0800 Subject: [PATCH 43/50] docs(spiraldb_lease): say which acquire errors propagate; name both clear prerequisites The acquire docstring said a TimeoutError from any SDK operation propagates; a failed create and a failed reopen by ID are wrapped as LeaseError, and only the generation lookup and state reads propagate raw. clear's ValueError for a missing confirmation now names that pending writes must have settled. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_lease.py | 9 ++++++--- tests/test_databases/test_spiral_lease.py | 2 +- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 61065b20e..c174e0b23 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -329,8 +329,10 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le Raises: LeaseBusyError: If another claim prevents acquisition. LeaseError: If the claim or its state cannot be verified. - TimeoutError: If an SDK operation times out and the error propagates. - Other SDK transport errors can also propagate unchanged. After claiming, + TimeoutError: If the generation lookup before the claim, or a state read + of a generation, times out. Other SDK errors from those calls also + propagate unchanged. A failed create and a failed reopen by ID are + wrapped as ``LeaseError``. After claiming, acquisition attempts release before re-raising. The one unguarded point is between the claim's return and its assignment: an interruption there leaves the generation held until it is cleared. @@ -492,7 +494,8 @@ def clear( """ if confirm_writer_stopped is not True: raise ValueError( - "Confirm that the writer has stopped before clearing its lease" + "Confirm that the writer has stopped and all its pending writes have " + "settled before clearing its lease" ) try: _, newest = _newest(client, project_id, dataset) diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 83574bf9a..edf0cadb9 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -91,7 +91,7 @@ def test_crashed_holder_refuses_until_manually_cleared(client: fake.FakeClient) f"{first.table_id!r}, confirm_writer_stopped=True)" ) in message assert "all its pending writes have settled" in message - with pytest.raises(ValueError, match="stopped"): + with pytest.raises(ValueError, match="stopped and all its pending writes have"): clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=False) check(client, first) clear(other, _PROJECT, _DATASET, first.table_id, confirm_writer_stopped=True) From 36b62a264af2447e866a33afcd28df10f5e77576 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 00:47:05 -0800 Subject: [PATCH 44/50] fix(spiraldb): a lease attached before an interruption is let go of; a held table leases no pod behind it (ITL-1844) - store_writes records a store's tables before attaching the lease, so an interruption between the two still lets go of it. - The lease walk collects no pod result database behind an ArrowTableStream, which holds its rows (ITL-1121); cached-source caches there stay leased, as a run still checks those sources. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/spiraldb_write_scope.py | 4 +- src/orcapod/pipeline/node_run.py | 34 ++++--- .../test_spiraldb_store_runs.py | 96 +++++++++++++++++++ 3 files changed, 119 insertions(+), 15 deletions(-) diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index bc864916b..f49eae619 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -92,8 +92,10 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: for connector in connectors: tables = _tables(connector) if not any(tables is t for t in holding): - tables.hold_lease(check) + # Recorded first, so an interruption once the lease is attached + # still lets go of it (a let-go clears only this check). holding.append(tables) + tables.hold_lease(check) except BaseException as error: _release_all(held, error) raise diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 185785cb5..d03c7e335 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -245,34 +245,40 @@ def _source_side_databases(streams: Iterable[Any]) -> list[Any]: """The databases written by what feeds ``streams`` from outside the job's nodes, through bound sources, wrapped sources and streams. - The cache of every ``CachedSource`` (written when it is checked or read), and the - result databases of every function pod stream met (a stream built outside the job - and bound to a slot computes, and writes its pod's caches, when the run reads it; - ``_pod_result_databases``). Each stream is visited once (linear in the size of the - graph). + The cache of every ``CachedSource`` (written when it is checked, and a run checks + every source it finds, ``check_sources``), and the result databases of every + function pod stream a run reads (a stream built outside the job and bound to a + slot computes, and writes its pod's caches, when the run reads it; + ``_pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the + table holds its rows, whatever its ``upstreams`` name (ITL-1121), so only the + caches of the sources there are collected. Each stream is visited at most twice, + behind a table and not (linear in the size of the graph). """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource + from orcapod.core.streams.arrow_table_stream import ArrowTableStream found: list[Any] = [] - visited: set[int] = set() - pending = deque(streams) + visited: set[tuple[int, bool]] = set() + pending: deque[tuple[Any, bool]] = deque((stream, False) for stream in streams) while pending: - stream = pending.popleft() - if id(stream) in visited: + stream, behind_table = pending.popleft() + if (id(stream), behind_table) in visited: continue - visited.add(id(stream)) + visited.add((id(stream), behind_table)) if isinstance(stream, SourceJobNode): if stream.bound_source is not None: - pending.append(stream.bound_source) + pending.append((stream.bound_source, behind_table)) continue if isinstance(stream, CachedSource): found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the store a run must hold the lease of - if not _is_job_node(stream): # a job node's pods: ``store_scope_databases`` + if not behind_table and not _is_job_node(stream): + # A job node's pods: ``store_scope_databases``. found.extend(db for db in _pod_result_databases(stream) if db is not None) + behind = behind_table or isinstance(stream, ArrowTableStream) inputs = getattr(stream, "live_source_inputs", None) - pending.extend(inputs or ()) - pending.extend(getattr(stream, "upstreams", ())) + pending.extend((each, behind) for each in inputs or ()) + pending.extend((each, behind) for each in getattr(stream, "upstreams", ())) return found diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index e234344c6..cf918ea0f 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -1045,3 +1045,99 @@ def add(x: int, y: int) -> int: SelectDataColumns(["total"])(outside, label="select") _ = _run(job, entry) assert on_store.list_table_paths(("outside",)) != [] + + +# ------------------------------------------------- review of e1581afe9 (ITL-1844) + + +@pytest.mark.usefixtures("root") +def test_an_interrupted_hold_is_let_go_of(monkeypatch: pytest.MonkeyPatch) -> None: + """An interruption once a lease is attached to a store's tables (before the scope + has recorded them) still lets go of it: the next run on the same databases is not + refused.""" + from orcapod.databases.spiraldb_store_tables import StoreTables + + real = StoreTables.hold_lease + interrupted: list[None] = [] + + def attach_then_interrupt(self: Any, check: Any) -> None: + real(self, check) + if not interrupted: + interrupted.append(None) + raise KeyboardInterrupt + + monkeypatch.setattr(StoreTables, "hold_lease", attach_then_interrupt) + databases = [_store("d")] + with pytest.raises(KeyboardInterrupt): + with store_writes(databases, owner="interrupted"): + pass + monkeypatch.undo() + with store_writes(databases, owner="next run"): + pass + + +def _held_table_over(upstream: Any) -> Any: + """A stream holding its rows, naming ``upstream`` as what it was built from.""" + from orcapod.core.streams import ArrowTableStream + + return ArrowTableStream( + _rows().select(["unit", "trial", "x"]), + tag_columns=["unit", "trial"], + upstreams=(upstream,), + ) + + +def _twice_over(stream: Any) -> Any: + from orcapod.core.nodes.function_node import FunctionJobNode + + def twice(x: int) -> int: + return 2 * x + + pod: Any = function_pod(output_keys=("w",))(twice).pod + return FunctionJobNode(pod, stream, pipeline_database=InMemoryArrowDatabase()) + + +@pytest.mark.usefixtures("root") +def test_a_held_table_does_not_lease_its_upstream_pods_database() -> None: + """A run over a table that holds its rows reads no pod behind it (ITL-1121), so it + takes no lease of that pod's store: it runs while another writer holds it, and the + pod is not called.""" + on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) + called: list[int] = [] + + def add(x: int, y: int) -> int: + called.append(x) + return x + y + + pod = function_pod(output_keys=("total",), result_database=on_store.at("behind"))( + add + ) + behind = pod.pod( + ArrowTableSource( + _rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ) + ) + node = _twice_over(_held_table_over(behind)) + _, release = take_lease(SpiralDBConnector("p", "f", store=True), "another") + try: + _ = node.run() + finally: + release() + assert node.as_table().num_rows == 3 + assert called == [] + + +@pytest.mark.usefixtures("root") +def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: + """A run checks every source it finds, also behind a held table, and a check can + write a cached source's cache: its store stays among the run's leased databases.""" + connector = SpiralDBConnector("p", "g", store=True) + cache = ConnectorArrowDatabase(connector) + node = _twice_over(_held_table_over(_cached(cache.at("c"), _rows()))) + databases = node_run.store_scope_databases([node], load_only=False) + leased = spiraldb_write_scope.store_connectors(databases) + assert any(c is connector for c in leased) From 6febee7689a0fa826a7f269de9aa5618cd420702 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 01:52:17 -0800 Subject: [PATCH 45/50] fix(spiraldb): a lease claim is recorded inside its acquisition; one lease per service; an ephemeral store is leased (ITL-1844) - spiraldb_lease.acquire takes on_claim, called with the verified lease inside its guard; store_writes records each claim there, so an interruption once the lease is taken still releases it. - A release interrupted after a cancelled or interrupted body is raised, chained from the body's error. - The writer-lease key uses the address the SDK client resolved (one helper, shared with the keyed-table listing; refused when the client does not expose it), and the connector keeps its own copy of overrides for the client and the saved config. - A job's ephemeral result database on a store is in the run's lease scope. - migrate_spiral_schemas: reserved names are classified before the no-table guard, and a lease generation needs a string key; the test reads keys through each dataset's own connector. - The evaluation script's save-and-load scenario checks the load-only rows. Co-Authored-By: Claude Opus 5.5 --- docs/concepts/spiraldb-store.md | 4 +- docs/dev/scripts/itl_1844_store_evaluation.py | 30 +++- scripts/migrate_spiral_schemas.py | 38 ++-- src/orcapod/databases/spiraldb_connector.py | 48 ++++- src/orcapod/databases/spiraldb_lease.py | 16 +- src/orcapod/databases/spiraldb_write_scope.py | 62 +++++-- src/orcapod/pipeline/node_run.py | 12 +- .../test_migrate_spiral_schemas.py | 166 ++++++++++++++---- tests/test_databases/test_spiral_lease.py | 32 ++++ .../test_spiraldb_store_runs.py | 145 ++++++++++++++- .../test_itl_1844_store_evaluation.py | 18 ++ 11 files changed, 477 insertions(+), 94 deletions(-) diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-store.md index fc023f936..5abe65111 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-store.md @@ -73,7 +73,9 @@ anything is written, also while a run holds the dataset's lease. A write through running job's own databases from outside the run (another thread, an observer) is not told apart from the run's own: do not write through them while the job runs. A load-only run of a job writes no node's table, so it takes a lease only for a cached -source it reads. +source it reads. A run takes one lease per dataset of one service: store connectors +whose client reaches the same service share it, whether their address was left to the +default or given (`overrides={"server.url": ...}`). ### A lease left behind diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_store_evaluation.py index a574dda8e..791e269cb 100644 --- a/docs/dev/scripts/itl_1844_store_evaluation.py +++ b/docs/dev/scripts/itl_1844_store_evaluation.py @@ -282,12 +282,11 @@ def store() -> ConnectorArrowDatabase: # loads the whole branch. loaded.bind(sources={"trials": trials(name, store(), n=7)}) _ = loaded.run(load_only=True) - s["save and load"] = { - "store_flag_saved": '"store": true' in saved.read_text(), - "rows_read": read, - "load_only_rows": loaded.nodes["select"].as_table().num_rows, - "ok": read == {"combine": 7, "select": 7}, - } + s["save and load"] = save_and_load_outcome( + '"store": true' in saved.read_text(), + read, + loaded.nodes["select"].as_table().num_rows, + ) # 8. a second writer is refused while another holds the lease. _, release = take_lease( @@ -321,6 +320,25 @@ def separate_results_expected( ] +def save_and_load_outcome( + flag_saved: bool, rows_read: dict[str, int], load_only_rows: int +) -> dict[str, Any]: + """The "save and load" scenario's record: ok only when both the stored rows read + back and the load-only run's rows are the seven expected. + + Args: + flag_saved: Whether the saved job file holds the store flag. + rows_read: Rows read back from each node's stored results, by node. + load_only_rows: Rows of the load-only run's last node. + """ + return { + "store_flag_saved": flag_saved, + "rows_read": rows_read, + "load_only_rows": load_only_rows, + "ok": rows_read == {"combine": 7, "select": 7} and load_only_rows == 7, + } + + def succeeded(scenarios: dict[str, Any]) -> bool: """Every scenario as expected: tables as on Delta and the recorded outcomes. diff --git a/scripts/migrate_spiral_schemas.py b/scripts/migrate_spiral_schemas.py index 6d15163b8..3d58723d5 100644 --- a/scripts/migrate_spiral_schemas.py +++ b/scripts/migrate_spiral_schemas.py @@ -190,27 +190,34 @@ def first_rows_digest(connector: Any, name: str) -> str | None: return get_default_context().arrow_hasher.hash_table(rows).to_string() -def table_key_columns(connector: Any, name: str) -> list[str]: - """Return a table's key columns as the dry run's connector reads them. +def table_key_fields(connector: Any, name: str) -> list[tuple[str, Any]]: + """Return a table's key columns and their Arrow types, as the dry run reads them. Args: connector: The connector of the table's dataset. name: The table. """ - return list(connector.lookup_table(name).key_columns) + handle = connector.lookup_table(name) + schema = handle.arrow_schema() + return [(key, schema.field(key).type) for key in handle.key_columns] -def is_lease_generation(key_columns: list[str]) -> bool: +def is_lease_generation(key_fields: list[tuple[str, Any]]) -> bool: """Return whether a table under a reserved name is a writer lease generation. - A generation has exactly one key column, carrying the lease signature. + A generation has exactly one key column, carrying the lease signature, of a string + type (the lease writer makes it a large string; a client may report either width). Args: - key_columns: The table's key columns. + key_fields: The table's key columns with their Arrow types. """ - return ( - len(key_columns) == 1 - and LEASE_KEY_PATTERN.fullmatch(key_columns[0]) is not None + import pyarrow as pa + + if len(key_fields) != 1: + return False + name, arrow_type = key_fields[0] + return LEASE_KEY_PATTERN.fullmatch(name) is not None and ( + pa.types.is_string(arrow_type) or pa.types.is_large_string(arrow_type) ) @@ -270,13 +277,12 @@ def dry_run(args: argparse.Namespace) -> None: reserved.setdefault(found.dataset, []).append(found.table) else: tables.setdefault(found.dataset, []).append(found.table) - if missing := [d for d in args.dataset if d not in tables]: - raise MigrationError( - f"no table in dataset(s) {missing}; the project has {sorted(tables)}" - ) + # Every selected dataset that lists a table, a reserved name included: a dataset + # whose only table is a reserved name reaches the reserved-name check below. connectors = { dataset: SpiralDBConnector(args.project, dataset) for dataset in sorted(set(args.dataset)) + if dataset in tables or dataset in reserved } # A reserved name holds a writer lease generation, which is not migrated, or a # table the upgraded connector no longer reads: refuse before planning anything. @@ -284,7 +290,7 @@ def dry_run(args: argparse.Namespace) -> None: collisions: dict[str, list[str]] = {} for dataset, connector in connectors.items(): for name in sorted(reserved.get(dataset, [])): - if is_lease_generation(table_key_columns(connector, name)): + if is_lease_generation(table_key_fields(connector, name)): generations.setdefault(dataset, []).append(name) else: collisions.setdefault(dataset, []).append(name) @@ -304,6 +310,10 @@ def dry_run(args: argparse.Namespace) -> None: "yet (ITL-1860)" ) raise MigrationError(message) + if missing := [d for d in args.dataset if d not in tables]: + raise MigrationError( + f"no table in dataset(s) {missing}; the project has {sorted(tables)}" + ) plan: dict[str, Any] = { "format": PLAN_FORMAT, "version": PLAN_VERSION, diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 41df46be6..89a64f106 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -523,6 +523,28 @@ def _http_get_json(url: str, token: str | None) -> dict[str, Any]: return json.load(response) +def _service_address(client: Any) -> str: + """Return the service address a spiral-sdk client resolved, without a final ``/``. + + The client's address and sign-in are not public API of the SDK: the pinned version + has them, and a version without them is refused here rather than guessed. + + Args: + client: A spiral-sdk client. + + Raises: + RuntimeError: If the client does not expose its resolved address. + """ + native = getattr(client, "_native", None) # no public accessor of the address + address = getattr(native, "api_url", None) + if not isinstance(address, str) or not address: + raise RuntimeError( + "this spiral-sdk client does not expose the service address it resolved " + "(_native.api_url); Orcapod needs the spiral-sdk version it pins" + ) + return address.rstrip("/") + + def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, str]: """Return keyed table names by ID, omitting writer lease generations. @@ -535,9 +557,9 @@ def _list_keyed_tables(client: Any, project_id: str, dataset: str) -> dict[str, project_id: The project. dataset: The dataset; matched exactly by the service. """ - native = client._native # no public accessor of the address and sign-in + native = client._native # no public accessor of the sign-in base = ( - f"{str(native.api_url).rstrip('/')}/api/keyed-tables/projects/" + f"{_service_address(client)}/api/keyed-tables/projects/" f"{urllib.parse.quote(project_id, safe='')}/tables" ) names: dict[str, str] = {} @@ -1001,10 +1023,10 @@ def __init__( raise TypeError(f"store must be True or False, got {store!r}") self._project_id = project_id self._dataset = dataset + # A copy: a later change to the caller's mapping must not change the service + # this connector reads, saves or leases. + overrides = None if overrides is None else dict(overrides) self._overrides = overrides - # The address the client is made for, kept for the writer-lease key: a later - # change to the caller's ``overrides`` must not move the lease to another service. - self._service_url = _api_url(overrides) self._closed = False # One client per service address and sign-in in the process (ITL-1457). shared = _client_for(overrides) @@ -1073,9 +1095,17 @@ def _store_tables(self) -> StoreTables | None: self._require_open() return self._store - def _writer_lease_key(self) -> tuple[str | None, str, str]: - """The dataset a writer lease is taken for: service address, project, dataset.""" - return (self._service_url, self._project_id, self._dataset) + def _writer_lease_key(self) -> tuple[str, str, str]: + """The dataset a writer lease is taken for: service address, project, dataset. + + The address is the one the client resolved, so connectors that reach one + service share one lease however their address was given (none, or the + default's). + + Raises: + RuntimeError: If the client does not expose its resolved address. + """ + return (_service_address(self._client), self._project_id, self._dataset) def _writer_lease_target(self) -> tuple[Any, str, str]: """What ``spiraldb_write_scope`` takes the writer lease with: the SDK client, @@ -1556,7 +1586,7 @@ def to_config(self) -> dict[str, Any]: "connector_type": "spiraldb", "project_id": self._project_id, "dataset": self._dataset, - "overrides": self._overrides, + "overrides": None if self._overrides is None else dict(self._overrides), } if self._store_mode: config["store"] = True diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index c174e0b23..376682a86 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -9,6 +9,7 @@ from __future__ import annotations import os +from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timezone from typing import Protocol, cast @@ -314,7 +315,14 @@ def _release_if_claimed( ) -def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Lease: +def acquire( + client: _Client, + project_id: str, + dataset: str, + *, + owner: str, + on_claim: Callable[[Lease], None] | None = None, +) -> Lease: """Claim a dataset for one writer or raise before any store data can be written. Args: @@ -322,6 +330,10 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le project_id: Project containing the dataset. dataset: Dataset to claim. owner: Operator-visible description of the writer. + on_claim: Optional: given the lease once its claim is verified, inside the + guard: if it raises or is interrupted, the claim is released before the + error propagates. A caller records the lease for its own cleanup there, so + no point after the verified claim leaves it unrecorded and unreleased. Returns: The verified lease for this process. @@ -364,6 +376,8 @@ def acquire(client: _Client, project_id: str, dataset: str, *, owner: str) -> Le raise else: check(client, lease) + if on_claim is not None: + on_claim(lease) except BaseException as exc: if claimed is None: raise diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index f49eae619..db015675a 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -61,8 +61,8 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: or is interrupted (also while letting go of the lease locally). An interruption of a release (``KeyboardInterrupt``, ``CancelledError``, ``SystemExit``) is never swallowed: it raises once every release was attempted, ahead of any ordinary - release failure, after a body that raised too (chained from the body's error, which - is its ``__cause__``). A release that fails with an error after the body raised is + release failure, after a body that raised or was itself interrupted too (chained + from the body's error, which is its ``__cause__``). A release that fails with an error after the body raised is added as a note to the body's error; after a body that succeeded the first failure raises. @@ -78,17 +78,26 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: succeeded (the run's writes are committed then; the message says how to clear the lease). """ - groups: dict[tuple[str | None, str, str], list[SpiralDBConnector]] = {} + groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} for connector in store_connectors(databases): groups.setdefault(connector._writer_lease_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # StoreTables try: for connectors in groups.values(): - check, release = take_lease(connectors[0], owner) # The store tables holding this lease, each once (every store connector has # its own, ``share_client`` copies too; a repeat is skipped all the same). holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # StoreTables - held.append((holding, check, release)) + + def register( + check: Callable[[], None], + release: Callable[[], None], + holding: list[Any] = holding, # pyright: ignore[reportExplicitAny] # StoreTables + ) -> None: + held.append((holding, check, release)) + + # The claim is recorded in ``held`` inside the acquisition's guard: an + # interruption either finds it there or is reconciled by the acquisition. + check, _ = take_lease(connectors[0], owner, on_taken=register) for connector in connectors: tables = _tables(connector) if not any(tables is t for t in holding): @@ -108,13 +117,20 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: def take_lease( - connector: SpiralDBConnector, owner: str + connector: SpiralDBConnector, + owner: str, + *, + on_taken: Callable[[Callable[[], None], Callable[[], None]], None] | None = None, ) -> tuple[Callable[[], None], Callable[[], None]]: """Acquire the writer lease of a store connector's dataset (``spiraldb_lease``). Args: connector: A SpiralDB store connector. owner: Who holds it, shown to a refused second writer. + on_taken: Optional: given ``(check, release)`` once the claim is verified, + inside the acquisition's guard (``spiraldb_lease.acquire``'s ``on_claim``): + if it raises or is interrupted, the claim is released before the error + propagates. Returns: ``(check, release)``: verifies the lease is still held; releases it. @@ -124,15 +140,23 @@ def take_lease( LeaseError: If the claim cannot be verified. """ client, project_id, dataset = connector._writer_lease_target() # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - lease = spiraldb_lease.acquire(client, project_id, dataset, owner=owner) + taken: list[tuple[Callable[[], None], Callable[[], None]]] = [] + + def claimed(lease: spiraldb_lease.Lease) -> None: + def check() -> None: + spiraldb_lease.check(client, lease) - def check() -> None: - spiraldb_lease.check(client, lease) + def release() -> None: + spiraldb_lease.release(client, lease) - def release() -> None: - spiraldb_lease.release(client, lease) + taken.append((check, release)) + if on_taken is not None: + on_taken(check, release) - return check, release + _ = spiraldb_lease.acquire( + client, project_id, dataset, owner=owner, on_claim=claimed + ) + return taken[0] def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # StoreTables; a store connector always has them while open @@ -155,10 +179,10 @@ def _release_all( Raises: BaseException: The first interruption (``KeyboardInterrupt``, ``CancelledError``, ``SystemExit``) of a let-go or release, chained from - the body's error when the body failed with an error; otherwise, after a - successful body, the first failed release. Any other failure is a note on - the error raised (on the body's error when the body failed and nothing - was interrupted, or when the body was itself interrupted). + the body's error when the body failed (with an error or itself + interrupted); otherwise, after a successful body, the first failed + release. Any other failure is a note on the error raised (on the body's + error when the body failed and nothing was interrupted). """ failures: list[BaseException] = [] for holding, check, release in reversed(held): @@ -180,7 +204,7 @@ def _release_all( if not failures: return interruptions = [f for f in failures if not isinstance(f, Exception)] - if error is not None and (not interruptions or not isinstance(error, Exception)): + if error is not None and not interruptions: # The body's error is raised by the caller; every failure is a note on it. for failure in failures: error.add_note( @@ -195,7 +219,7 @@ def _release_all( f"Releasing another SpiralDB writer lease failed: {failure}" ) if error is not None: - # An interruption after a body that failed with an error: the body's error is - # its cause. + # An interruption after a body that failed (an error, or interrupted itself): + # the body's error is its cause. raise primary from error raise primary diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index d03c7e335..b72fb7a12 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -159,12 +159,16 @@ def _pod_result_databases(node: Any) -> list[Any]: """The result databases a function node's own pod writes on a cache miss. The result database of each pod the node's function pod is or wraps - (``@function_pod(pod_cache_database=...)``) and of each data function under them - (``@function_pod(result_database=...)``). Not the job's result database - (``_databases``); not committed at the end of a run, only leased. + (``@function_pod(pod_cache_database=...)``), of each data function under them + (``@function_pod(result_database=...)``), and the node's ephemeral result database + (``set_ephemeral_database``, through the pod that writes it). Not the job's result + database (``_databases``); not committed at the end of a run, only leased. """ found: list[Any] = [] - pods: list[Any] = [getattr(node, "_function_pod", None)] + pods: list[Any] = [ + getattr(node, "_function_pod", None), + getattr(node, "_ephemeral_cached_pod", None), + ] visited: set[int] = set() while pods: pod = pods.pop(0) diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 39f8137e3..d4ed204ca 100644 --- a/tests/test_databases/test_migrate_spiral_schemas.py +++ b/tests/test_databases/test_migrate_spiral_schemas.py @@ -186,10 +186,17 @@ def test_lease_name_recognizers_agree(tool: ModuleType) -> None: ("k", False), ] for key, expected in keys: - assert tool.is_lease_generation([key]) == expected, repr(key) + assert tool.is_lease_generation([(key, pa.large_string())]) == expected, repr( + key + ) assert (spiral_lease_key_column([key]) is not None) == expected, repr(key) lease_key = keys[0][0] - assert not tool.is_lease_generation([lease_key, "k"]) + assert tool.is_lease_generation([(lease_key, pa.string())]) + assert not tool.is_lease_generation([(lease_key, pa.int64())]) + assert not tool.is_lease_generation([(lease_key, pa.large_binary())]) + assert not tool.is_lease_generation( + [(lease_key, pa.large_string()), ("k", pa.large_string())] + ) assert spiral_lease_key_column([lease_key, "k"]) is None @@ -197,17 +204,17 @@ def _legacy_listing( tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch, - reserved: list[tuple[str, str, list[str]]], + reserved: list[tuple[str, str, list[pa.Field[Any]]]], schema_tables: tuple[str, ...] = (), -) -> tuple[dict[str, Any], list[str]]: - """List the planned tables and ``reserved`` (dataset, name, key columns) as the - pyspiral client would, and return the plan and the reserved names opened. +) -> tuple[dict[str, Any], list[tuple[str, str]]]: + """List the planned tables and ``reserved`` (dataset, name, key fields) as the + pyspiral client would, and return the plan and the reserved tables opened. - Each reserved name is used in one dataset only. ``schema_tables`` names the - datasets whose listing also holds a schema table. + ``schema_tables`` names the datasets whose listing also holds a schema table. - The tables under reserved names are made on the fake; the dry run's table - descriptions are the plan's, and the key columns it reads are recorded. + Each dataset's connector serves its own reserved tables (``lookup_table``), so the + dry run's own ``table_key_fields`` reads them; every lookup is recorded as a + ``(dataset, name)`` pair. The dry run's table descriptions are the plan's. """ plan = tool.read_plan(args.plan) descriptions = { @@ -220,25 +227,30 @@ def _legacy_listing( for (dataset, name), table in descriptions.items() ] project = fake.FakeClient().project(args.project) - keys: dict[str, list[str]] = {} - for dataset, name, key_columns in reserved: - made = project.create_keyed_table( - dataset, - name, - pa.schema([pa.field(k, pa.large_string(), False) for k in key_columns]), - ) - assert name not in keys, "reserved names are distinct across datasets here" - keys[name] = key_columns + served: dict[tuple[str, str], list[pa.Field[Any]]] = {} + for dataset, name, key_fields in reserved: + made = project.create_keyed_table(dataset, name, pa.schema(key_fields)) + served[dataset, name] = key_fields listed.append(SimpleNamespace(dataset=dataset, table=name, id=made.resource_id)) listed.extend( SimpleNamespace(dataset=dataset, table=st.SCHEMA_TABLE, id=f"schemas-{dataset}") for dataset in schema_tables ) - opened: list[str] = [] - - def key_columns_of(_connector: Any, name: str) -> list[str]: - opened.append(name) - return keys[name] + opened: list[tuple[str, str]] = [] + + class LegacyConnector(SpiralDBConnector): + """The connector of one dataset, serving that dataset's reserved tables.""" + + def lookup_table(self, table_name: str) -> Any: # pyright: ignore[reportIncompatibleMethodOverride] # a stand-in handle + key = (self._dataset, table_name) # pyright: ignore[reportPrivateUsage] # which dataset this connector reads + if key not in served: + return super().lookup_table(table_name) + opened.append(key) + fields = served[key] + return SimpleNamespace( + key_columns=[field.name for field in fields], + arrow_schema=lambda: pa.schema(fields), + ) legacy = SimpleNamespace( authn=SimpleNamespace(token=lambda: None), @@ -252,13 +264,20 @@ def key_columns_of(_connector: Any, name: str) -> list[str]: "describe_table", lambda _connector, _project, dataset, name: descriptions[dataset, name], ) - monkeypatch.setattr(tool, "table_key_columns", key_columns_of) + monkeypatch.setattr( + "orcapod.databases.spiraldb_connector.SpiralDBConnector", LegacyConnector + ) return plan, opened -def _lease_key(n: int) -> list[str]: - """Return the key columns of a writer lease generation with a synthetic token.""" - return [f"{SPIRAL_LEASE_KEY_PREFIX}{n:032x}"] +def _key(name: str, arrow_type: pa.DataType | None = None) -> list[pa.Field[Any]]: + """Return the key fields of a table with one key column (a large string).""" + return [pa.field(name, arrow_type or pa.large_string(), False)] + + +def _lease_key(n: int, arrow_type: pa.DataType | None = None) -> list[pa.Field[Any]]: + """Return the key fields of a writer lease generation with a synthetic token.""" + return _key(f"{SPIRAL_LEASE_KEY_PREFIX}{n:032x}", arrow_type) def test_dry_run_and_write_skip_lease_generations( @@ -267,8 +286,10 @@ def test_dry_run_and_write_skip_lease_generations( monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str], ) -> None: - """Writer lease generations (lease-signature keys) in selected datasets are - skipped and reported; the plan, the write and the verify are unchanged.""" + """Writer lease generations (lease-signature keys of a string type, either width) + in selected datasets are skipped and reported; the plan, the write and the verify + are unchanged. Each generation is read through its own dataset's connector: one + generation name is in both datasets.""" first, second = args.dataset[:2] plan, opened = _legacy_listing( tool, @@ -276,13 +297,19 @@ def test_dry_run_and_write_skip_lease_generations( monkeypatch, [ (first, spiral_lease_table_name(2), _lease_key(2)), - (second, spiral_lease_table_name(3), _lease_key(3)), + (second, spiral_lease_table_name(1), _lease_key(3, pa.string())), (first, spiral_lease_table_name(1), _lease_key(1)), ], ) tool.dry_run(args) assert tool.read_plan(args.plan) == plan - assert sorted(opened) == [spiral_lease_table_name(n) for n in (1, 2, 3)] + assert sorted(opened) == sorted( + [ + (first, spiral_lease_table_name(1)), + (first, spiral_lease_table_name(2)), + (second, spiral_lease_table_name(1)), + ] + ) printed = capsys.readouterr().out assert "skipped 2 writer lease generation(s)" in printed assert "skipped 1 writer lease generation(s)" in printed @@ -303,10 +330,10 @@ def test_dry_run_refuses_a_reserved_name_table_without_a_lease_key( args, monkeypatch, [ - (second, spiral_lease_table_name(3), ["k"]), + (second, spiral_lease_table_name(3), _key("k")), (first, spiral_lease_table_name(1), _lease_key(1)), - (first, spiral_lease_table_name(2), ["k", "j"]), - ("unselected", spiral_lease_table_name(4), ["k"]), + (first, spiral_lease_table_name(2), _key("k") + _key("j")), + ("unselected", spiral_lease_table_name(4), _key("k")), ], ) with pytest.raises(tool.MigrationError, match="Rename them") as refused: @@ -317,11 +344,74 @@ def test_dry_run_refuses_a_reserved_name_table_without_a_lease_key( assert f"{args.project}/{first}/{spiral_lease_table_name(2)}" in message assert f"{args.project}/{second}/{spiral_lease_table_name(3)}" in message assert spiral_lease_table_name(1) not in message - assert spiral_lease_table_name(4) not in opened + assert ("unselected", spiral_lease_table_name(4)) not in opened assert spiral_lease_table_name(4) not in message assert Path(args.plan).read_text() == before +def test_dry_run_refuses_a_lease_shaped_key_of_another_type( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """A reserved-name table whose one key has the lease signature but is not a + string is not a lease generation: the dry run refuses it, to be renamed.""" + first = args.dataset[0] + before = Path(args.plan).read_text() + _ = _legacy_listing( + tool, + args, + monkeypatch, + [(first, spiral_lease_table_name(1), _lease_key(1, pa.int64()))], + ) + with pytest.raises(tool.MigrationError, match="Rename them") as refused: + tool.dry_run(args) + assert f"{args.project}/{first}/{spiral_lease_table_name(1)}" in str(refused.value) + assert Path(args.plan).read_text() == before + + +def test_a_dataset_holding_only_a_reserved_name_table_is_told_to_rename_it( + tool: ModuleType, args: argparse.Namespace, monkeypatch: pytest.MonkeyPatch +) -> None: + """A selected dataset whose only listed table is a reserved name that is not a + lease generation gets the rename guidance, not "no table"; a selected dataset + with only lease generations, or nothing listed, still gets "no table".""" + args.dataset = [*args.dataset, "reserved-only"] + _ = _legacy_listing( + tool, + args, + monkeypatch, + [("reserved-only", spiral_lease_table_name(1), _key("k"))], + ) + with pytest.raises(tool.MigrationError, match="Rename them") as refused: + tool.dry_run(args) + assert f"{args.project}/reserved-only/{spiral_lease_table_name(1)}" in str( + refused.value + ) + + +@pytest.mark.parametrize("listed", ["only a lease generation", "nothing"]) +def test_a_dataset_without_an_ordinary_table_has_no_table( + tool: ModuleType, + args: argparse.Namespace, + monkeypatch: pytest.MonkeyPatch, + listed: str, +) -> None: + """A selected dataset with no ordinary table, after the reserved names are + checked, is refused with "no table".""" + args.dataset = [*args.dataset, "empty"] + _ = _legacy_listing( + tool, + args, + monkeypatch, + [("empty", spiral_lease_table_name(1), _lease_key(1))] + if listed == "only a lease generation" + else [], + ) + with pytest.raises( + tool.MigrationError, match=r"no table in dataset\(s\) \['empty'\]" + ): + tool.dry_run(args) + + def test_the_dry_run_reads_raise_no_keyed_table_deprecation( tool: ModuleType, project: Any ) -> None: @@ -667,8 +757,8 @@ def test_dry_run_refusal_names_the_existing_schema_row_limitation( args, monkeypatch, [ - (first, spiral_lease_table_name(1), ["k"]), - (second, spiral_lease_table_name(2), ["k"]), + (first, spiral_lease_table_name(1), _key("k")), + (second, spiral_lease_table_name(2), _key("k")), ], schema_tables=(second,), ) diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index edf0cadb9..1d08acdf8 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -767,6 +767,38 @@ def interrupt(*_args: object) -> Lease: check(client, acquire(client, _PROJECT, _DATASET, owner="next")) +@pytest.mark.parametrize("raised", [KeyboardInterrupt, RuntimeError]) +def test_a_failure_of_on_claim_releases_the_claim( + client: fake.FakeClient, raised: type[BaseException] +) -> None: + """``on_claim`` is given the verified lease inside the guard: when it raises or is + interrupted, the claim is released before the error propagates, also after it + recorded the lease (a second release of it is harmless).""" + recorded: list[Lease] = [] + failure = raised("stopped while recording the claim") + + def on_claim(lease: Lease) -> None: + recorded.append(lease) + raise failure + + with pytest.raises(raised) as caught: + _ = acquire(client, _PROJECT, _DATASET, owner="first", on_claim=on_claim) + assert caught.value is failure + assert len(recorded) == 1 + release(client, recorded[0]) + with pytest.raises(LeaseError, match="released"): + check(client, recorded[0]) + check(client, acquire(client, _PROJECT, _DATASET, owner="next")) + + +def test_on_claim_is_given_the_lease_acquire_returns(client: fake.FakeClient) -> None: + """``on_claim`` is called once, with the lease ``acquire`` then returns.""" + recorded: list[Lease] = [] + lease = acquire(client, _PROJECT, _DATASET, owner="first", on_claim=recorded.append) + assert recorded == [lease] + check(client, lease) + + @pytest.mark.parametrize("operation", ["release", "clear"]) def test_a_failed_state_read_before_release_is_a_lease_error( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, operation: str diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_store_runs.py index cf918ea0f..e0662bd89 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_store_runs.py @@ -681,14 +681,68 @@ def test_a_job_on_a_wrapped_store_holds_its_lease_and_stores_as_on_delta( @pytest.mark.usefixtures("root") def test_the_lease_key_keeps_the_service_address_of_construction() -> None: - """Changing the caller's overrides after construction moves neither the client nor - the lease to another service.""" + """Changing the caller's overrides after construction moves neither the client, the + lease nor the saved configuration to another service.""" overrides = {"server.url": "https://one.example"} connector = SpiralDBConnector("p", "d", store=True, overrides=overrides) key = connector._writer_lease_key() # pyright: ignore[reportPrivateUsage] overrides["server.url"] = "https://two.example" assert connector._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] assert key[0] == "https://one.example" + saved = connector.to_config() + assert saved["overrides"] == {"server.url": "https://one.example"} + saved["overrides"]["server.url"] = "https://three.example" + assert connector.to_config()["overrides"] == {"server.url": "https://one.example"} + loaded = SpiralDBConnector.from_config(connector.to_config()) + assert loaded._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "given", ["https://api.fake.invalid", "https://api.fake.invalid/"] +) +def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: + """A store connector with no address and one given the default address (also with + a final slash) reach one service: a run over both takes one lease, held by both + stores; another service keeps its own lease.""" + plain = SpiralDBConnector("p", "d", store=True) + addressed = SpiralDBConnector("p", "d", {"server.url": given}, store=True) + other = SpiralDBConnector( + "p", "d", {"server.url": "https://other.invalid"}, store=True + ) + databases = [ConnectorArrowDatabase(c) for c in (plain, addressed, other)] + key = plain._writer_lease_key() # pyright: ignore[reportPrivateUsage] + assert addressed._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] + assert other._writer_lease_key() != key # pyright: ignore[reportPrivateUsage] + with spiraldb_write_scope.store_writes(databases[:2], owner="test"): + assert len(_lease_tables()) == 1 + held = [c._store_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + assert held[0] is not None and held[0] is held[1] + assert all(c._store_tables()._lease_check is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("native", ["missing", "no address"]) +def test_a_client_without_its_resolved_address_is_refused( + monkeypatch: pytest.MonkeyPatch, native: str +) -> None: + """A client that does not expose the address it resolved is refused when a run + takes the lease: no address is guessed, and no lease is taken.""" + from types import SimpleNamespace + + connector = SpiralDBConnector("p", "d", store=True) + client = connector._client # pyright: ignore[reportPrivateUsage] + stand_in = ( + SimpleNamespace() + if native == "missing" + else SimpleNamespace(_native=SimpleNamespace(access_token=lambda: "t")) + ) + monkeypatch.setattr(connector, "_client", stand_in) + with pytest.raises(RuntimeError, match="resolved"): + with store_writes([ConnectorArrowDatabase(connector)], owner="test"): + pass + assert _lease_tables() == [] + monkeypatch.setattr(connector, "_client", client) @pytest.mark.usefixtures("root") @@ -1076,6 +1130,93 @@ def attach_then_interrupt(self: Any, check: Any) -> None: pass +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("datasets", [("d",), ("d", "r")]) +def test_an_interruption_once_the_lease_is_taken_still_releases_it( + monkeypatch: pytest.MonkeyPatch, datasets: tuple[str, ...] +) -> None: + """An interruption right after the lease is acquired (before the scope goes on) + still releases it: the claim was recorded inside the acquisition. Every dataset is + free afterwards.""" + real = spiraldb_write_scope.take_lease + taken: list[None] = [] + + def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: + result = real(*args, **kwargs) + taken.append(None) + if len(taken) == len(datasets): + raise KeyboardInterrupt + return result + + monkeypatch.setattr(spiraldb_write_scope, "take_lease", take_then_interrupt) + databases = [_store(dataset) for dataset in datasets] + with pytest.raises(KeyboardInterrupt): + with store_writes(databases, owner="interrupted"): + pass + monkeypatch.undo() + for dataset in datasets: + _, release = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + release() + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("body", [asyncio.CancelledError, KeyboardInterrupt]) +def test_a_release_interruption_after_an_interrupted_body_is_raised( + monkeypatch: pytest.MonkeyPatch, body: type[BaseException] +) -> None: + """A body cancelled or interrupted, then a release interrupted: the release's + interruption is raised, chained from the body's, with an ordinary release error as + a note; every lease is released.""" + real = spiraldb_lease.release + seen: list[None] = [] + released = KeyboardInterrupt("release interrupted") + + def fail_then_interrupt(client: Any, lease: Any) -> None: + seen.append(None) + real(client, lease) + if len(seen) == 1: + raise spiraldb_lease.LeaseError("first release failed") + raise released + + monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) + stopped = body("body stopped") + with pytest.raises(KeyboardInterrupt) as raised: + with store_writes([_store("d"), _store("r")], owner="test"): + raise stopped + assert raised.value is released + assert raised.value.__cause__ is stopped + assert any("first release failed" in note for note in raised.value.__notes__) + monkeypatch.undo() + for dataset in ("d", "r"): + _, release = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + release() + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("job_database", ["in-memory", "store"]) +def test_an_ephemeral_result_database_on_a_store_is_leased(job_database: str) -> None: + """A job's ephemeral result database (``set_ephemeral_database``) on a store is + written under the run's lease: the run succeeds, its results are stored there, and + the lease is released.""" + from orcapod.types import NodeConfig + + database = InMemoryArrowDatabase() if job_database == "in-memory" else _store() + ephemeral = _store("e") + job = PipelineJob(name=JOB, database=database) + with job: + combine.pod(_cached(InMemoryArrowDatabase(), _rows()), label="combine") + job.set_ephemeral_database(ephemeral) + job.nodes["combine"].node_config = NodeConfig(is_result_ephemeral=True) + assert job.run().ok + fresh = _store("e") + paths = fresh.list_table_paths() + assert len(paths) == 1 + stored = fresh.get_all_records(paths[0]) + assert stored is not None and stored.num_rows == len(_rows()) + _, release = take_lease(SpiralDBConnector("p", "e", store=True), "after") + release() + + def _held_table_over(upstream: Any) -> Any: """A stream holding its rows, naming ``upstream`` as what it was built from.""" from orcapod.core.streams import ArrowTableStream diff --git a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py index 056ecc65e..979114355 100644 --- a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py +++ b/tests/test_dev_scripts/test_itl_1844_store_evaluation.py @@ -68,6 +68,24 @@ def test_a_wrong_recorded_outcome_fails( assert not script.succeeded(scenarios) +@pytest.mark.parametrize( + ("rows_read", "load_only_rows", "ok"), + [ + ({"combine": 7, "select": 7}, 7, True), + ({"combine": 7, "select": 7}, 0, False), + ({"combine": 7, "select": 6}, 7, False), + ], +) +def test_the_save_and_load_scenario_checks_the_load_only_rows( + script: ModuleType, rows_read: dict[str, int], load_only_rows: int, ok: bool +) -> None: + """The scenario's own ok needs the load-only run's seven rows too, not only the + rows read back.""" + outcome = script.save_and_load_outcome(True, rows_read, load_only_rows) + assert outcome["ok"] is ok + assert outcome["load_only_rows"] == load_only_rows + + def test_a_column_of_another_arrow_type_is_not_comparable_equal( script: ModuleType, ) -> None: From 6ff94d7673add8c98259f61e768168f91f65f9d2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 02:04:50 -0800 Subject: [PATCH 46/50] test(spiraldb_lease): check that acquire released the claim before a caller's own release (ITL-1844) Co-Authored-By: Claude Opus 5.5 --- tests/test_databases/test_spiral_lease.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 1d08acdf8..0c3cc384a 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -785,6 +785,10 @@ def on_claim(lease: Lease) -> None: _ = acquire(client, _PROJECT, _DATASET, owner="first", on_claim=on_claim) assert caught.value is failure assert len(recorded) == 1 + # Released by acquire itself, before any release of the caller's. + with pytest.raises(LeaseError, match="released"): + check(client, recorded[0]) + # A caller that recorded the lease releases it again: harmless. release(client, recorded[0]) with pytest.raises(LeaseError, match="released"): check(client, recorded[0]) From de39bbc4cca586667bfa9759c631952b48812278 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 13:51:15 -0800 Subject: [PATCH 47/50] refactor(spiraldb)!: rename the SpiralDB store to the writable SpiralDB database (ITL-1844) Developer decision of 2026-12-02: every store term of the SpiralDB store work becomes a database term, in code, docs, flags and tests. - SpiralDBConnector(..., writable=True) replaces store=True, with no alias; a saved job records writable: true, and a saved connector with a store key is refused at load and by from_config, naming writable=True. - The table metadata key is orcapod.table_format and the format value orcapod.spiral_database.draft. A table of the earlier draft (its value, under either key) is listed as another table format and refused when opened, never read or written. - Modules, classes, errors and functions renamed (spiral_database_codec, spiral_database_identity, spiraldb_tables / SpiralDBTables, spiraldb_writable_registry, SpiralDBLeaseRequiredError, database_writes, database_write_scope, ...); the docs page is spiraldb-database.md. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1540.md | 2 +- changelog.d/ITL-1837.md | 2 +- changelog.d/ITL-1840.md | 2 +- changelog.d/ITL-1844.md | 24 +- docs/api/databases.md | 4 +- docs/api/errors.md | 2 +- docs/concepts/pipeline-job.md | 10 +- ...spiraldb-store.md => spiraldb-database.md} | 54 +- ...ion.py => itl_1844_database_evaluation.py} | 112 ++-- docs/reference/database-types.md | 5 +- docs/reference/hashing.md | 2 +- site/astro.config.mjs | 2 +- src/orcapod/core/nodes/function_node.py | 9 +- src/orcapod/core/nodes/operator_node.py | 9 +- src/orcapod/core/nodes/source_node.py | 4 +- .../databases/connector_arrow_database.py | 203 +++--- ...iral_store.py => spiral_database_codec.py} | 83 +-- ...dentity.py => spiral_database_identity.py} | 191 +++--- src/orcapod/databases/spiraldb_connector.py | 119 ++-- src/orcapod/databases/spiraldb_lease.py | 6 +- .../databases/spiraldb_store_registry.py | 32 - ...ldb_store_tables.py => spiraldb_tables.py} | 248 ++++---- .../databases/spiraldb_writable_registry.py | 33 + src/orcapod/databases/spiraldb_write_scope.py | 71 ++- src/orcapod/databases/store_table_names.py | 22 +- src/orcapod/errors.py | 20 +- src/orcapod/pipeline/_observer_database.py | 2 +- src/orcapod/pipeline/job.py | 36 +- src/orcapod/pipeline/node_run.py | 31 +- src/orcapod/pipeline/serialization.py | 36 +- ...store.py => test_spiral_database_codec.py} | 317 +++++----- ...ty.py => test_spiral_database_identity.py} | 228 +++---- tests/test_databases/test_spiral_lease.py | 4 +- .../test_spiraldb_connector_integration.py | 36 +- ...mode.py => test_spiraldb_writable_mode.py} | 596 ++++++++++-------- ...runs.py => test_spiraldb_writable_runs.py} | 465 +++++++------- tests/test_databases/type_matrix.py | 5 +- ...y => test_itl_1844_database_evaluation.py} | 28 +- .../test_pipeline/test_observer_databases.py | 48 +- 39 files changed, 1651 insertions(+), 1452 deletions(-) rename docs/concepts/{spiraldb-store.md => spiraldb-database.md} (72%) rename docs/dev/scripts/{itl_1844_store_evaluation.py => itl_1844_database_evaluation.py} (80%) rename src/orcapod/databases/{spiral_store.py => spiral_database_codec.py} (95%) rename src/orcapod/databases/{spiral_store_identity.py => spiral_database_identity.py} (50%) delete mode 100644 src/orcapod/databases/spiraldb_store_registry.py rename src/orcapod/databases/{spiraldb_store_tables.py => spiraldb_tables.py} (85%) create mode 100644 src/orcapod/databases/spiraldb_writable_registry.py rename tests/test_databases/{test_spiral_store.py => test_spiral_database_codec.py} (85%) rename tests/test_databases/{test_spiral_store_identity.py => test_spiral_database_identity.py} (64%) rename tests/test_databases/{test_spiraldb_store_mode.py => test_spiraldb_writable_mode.py} (79%) rename tests/test_databases/{test_spiraldb_store_runs.py => test_spiraldb_writable_runs.py} (73%) rename tests/test_dev_scripts/{test_itl_1844_store_evaluation.py => test_itl_1844_database_evaluation.py} (85%) diff --git a/changelog.d/ITL-1540.md b/changelog.d/ITL-1540.md index 5e1825c2e..4cde76c77 100644 --- a/changelog.d/ITL-1540.md +++ b/changelog.d/ITL-1540.md @@ -1,7 +1,7 @@ ### Fixed - Status and logging observers now raise `SpiralDBObserverNotSupportedError` at setup when - given a SpiralDB store, including scoped views and extension-aware wrappers (ITL-1540). + given a SpiralDB database, including scoped views and extension-aware wrappers (ITL-1540). ### Known limitations diff --git a/changelog.d/ITL-1837.md b/changelog.d/ITL-1837.md index d79e1a377..b4c2e8839 100644 --- a/changelog.d/ITL-1837.md +++ b/changelog.d/ITL-1837.md @@ -8,7 +8,7 @@ ### Known limitations -- The SpiralDB store's table format (the encoding of a stored table's columns and the +- The writable SpiralDB database's table format (the encoding of a stored table's columns and the identity record kept in a table's metadata) is provisional: outside the 0.4.0 freeze, it may change in a later version, and tables written in it may then need to be written again. (ITL-1837) diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md index 6b07dbc09..5eec33a4a 100644 --- a/changelog.d/ITL-1840.md +++ b/changelog.d/ITL-1840.md @@ -1,6 +1,6 @@ ### Known limitations -- A SpiralDB store (`SpiralDBConnector(..., store=True)`, ITL-1844) keeps every stored +- A writable SpiralDB database (`SpiralDBConnector(..., writable=True)`, ITL-1844) keeps every stored table kind through `ConnectorArrowDatabase`: one table per path, its identity and manifest in the table's metadata. Its format is provisional, outside the 0.4.0 freeze. (ITL-1840) diff --git a/changelog.d/ITL-1844.md b/changelog.d/ITL-1844.md index e6d6dd92b..5ccf68e3b 100644 --- a/changelog.d/ITL-1844.md +++ b/changelog.d/ITL-1844.md @@ -1,31 +1,31 @@ ### Added -- A SpiralDB dataset can be a job's database: `SpiralDBConnector(project_id, dataset, store=True)` - under `ConnectorArrowDatabase` stores every table a job writes (function results and +- A SpiralDB dataset can be a job's database: a writable SpiralDB database, + `SpiralDBConnector(project_id, dataset, writable=True)` under `ConnectorArrowDatabase`, stores every table a job writes (function results and pipeline records, operator caches, cached sources, side-effect logs), also as a separate - result database. Provisional in 0.4.0: the store's table format and its writer lease may - change in a later version, which may not read tables written now. Nothing of the store - enters a hash. See "SpiralDB as a Job's Database" in the concepts. -- One writer per SpiralDB store: `job.run()`, `job.run_async()` and a job node's `run()` + result database. Provisional in 0.4.0: the database's table format and its writer lease may + change in a later version, which may not read tables written now. Nothing of the + database enters a hash. See "SpiralDB as a Job's Database" in the concepts. +- One writer per writable SpiralDB database: `job.run()`, `job.run_async()` and a job node's `run()` take the dataset's writer lease before checking a source or writing anything, and release it when they end, also when they fail. A second writer is refused then with `LeaseBusyError`, before anything of its run happens. A stale lease is cleared by its project, dataset and table id with `spiraldb_lease.clear(client, project_id, dataset, table_id, confirm_writer_stopped=True)`. -- A job saved on a store records `store: true` and no credential; `PipelineJob.load` +- A job saved on a writable SpiralDB database records `writable: true` and no credential; `PipelineJob.load` takes the connector again and refuses a SpiralDB connector of the other kind. ### Known limitations -- Only a job run writes a SpiralDB store, through the store connectors it holds the lease - with: a write through any other store connector (a cached source read outside a run, a +- Only a job run writes a writable SpiralDB database, through the writable connectors it + holds the lease with: a write through any other writable connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a connector of its own flushed directly) raises - `SpiralDBStoreLeaseRequiredError`, also while a run holds the lease. A write through a + `SpiralDBLeaseRequiredError`, also while a run holds the lease. A write through a running job's own databases from outside the run is not told apart from the run's own. A way to hold the lease outside a run is later work (ITL-1849). - The writer lease is refuse-only: no waiting, no takeover, no expiry. Each run leaves one small lease table in the dataset, which is kept. -- A store reads a table's whole key column to tell which rows it holds, and whole tables +- A writable SpiralDB database reads a table's whole key column to tell which rows it holds, and whole tables to read stored rows, so a run's cost grows with the tables' history. -- The store does not take over tables it did not write, and status and logging observers +- The database does not take over tables it did not write, and status and logging observers still refuse a SpiralDB database. diff --git a/docs/api/databases.md b/docs/api/databases.md index e787ee033..9806c28b7 100644 --- a/docs/api/databases.md +++ b/docs/api/databases.md @@ -8,8 +8,8 @@ code. See site/README.md. Database backends store pipeline results. The SQLite and PostgreSQL connectors support reads and writes through `ConnectorArrowDatabase`. The SpiralDB connector reads, and writes -only when opened as a job's store (`store=True`, provisional; see -[SpiralDB as a Job's Database](../concepts/spiraldb-store.md)). +only when opened writable (`writable=True`, provisional; see +[SpiralDB as a Job's Database](../concepts/spiraldb-database.md)). **Provisional.** `ExtensionAwareDatabase` is expected to be integrated more closely with the underlying database classes (ITL-1539), so its public form may change. diff --git a/docs/api/errors.md b/docs/api/errors.md index c4b21e759..f24cf163f 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -132,7 +132,7 @@ These exceptions and warnings report storage, schema, and connector problems. ::: orcapod.errors.SpiralDBObserverNotSupportedError -::: orcapod.errors.SpiralDBStoreLeaseRequiredError +::: orcapod.errors.SpiralDBLeaseRequiredError ::: orcapod.errors.SpiralDBSignInError diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 0557a3deb..f77676349 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -63,7 +63,7 @@ Among `job.run()`'s optional arguments, the tutorial `SyncPipelineOrchestrator(error_policy="fail_fast")` to stop at the first failing row; the default policy skips failed rows and continues) and `observer=` (`StatusObserver`, `LoggingObserver`) to record what happened during the run. Both observers raise -`SpiralDBObserverNotSupportedError` at setup if given a SpiralDB store, so give them +`SpiralDBObserverNotSupportedError` at setup if given a SpiralDB database, so give them another database such as Delta (ITL-1540). If a built-in observer cannot encode or write an event, the failure is logged, the run continues, the summary counts the lost events per observer kind in `lost_observer_events`, and one `ObserverEventsLostWarning` is @@ -278,8 +278,8 @@ refused. PostgreSQL also refuses column names and explicit table identifiers lon SQLite and PostgreSQL stores generate table names within 63 bytes from the node's path, using a readable hint and a digest of the full path. A database on `SpiralDBConnector` refuses every write (`SpiralDBWriteNotSupportedError`) unless it is opened -as a store, `SpiralDBConnector(..., store=True)`: see -[SpiralDB as a Job's Database](spiraldb-store.md). The full list, +writable, `SpiralDBConnector(..., writable=True)`: see +[SpiralDB as a Job's Database](spiraldb-database.md). The full list, type by type, is [Data types per database](../reference/database-types.md). Orcapod's own stored tables hold such columns. A function node's result table holds @@ -293,8 +293,8 @@ is attached to them, before anything runs: - every side-effect node, on SQLite; - every operator node with caching on (`CacheMode.LOG` or `REPLAY`), on SQLite: the SQLite connector has no column type for a timestamp (adding one is ITL-1482); -- every node that stores anything, on a plain SpiralDB connector (a SpiralDB store keeps - them all). +- every node that stores anything, on a plain SpiralDB connector (a writable SpiralDB database + keeps them all). An operator cache or cached source on a SQL connector is also refused when it is written, before anything is stored, if one of its own columns has a type or name the connector does not store. On diff --git a/docs/concepts/spiraldb-store.md b/docs/concepts/spiraldb-database.md similarity index 72% rename from docs/concepts/spiraldb-store.md rename to docs/concepts/spiraldb-database.md index 5abe65111..d5eefe25e 100644 --- a/docs/concepts/spiraldb-store.md +++ b/docs/concepts/spiraldb-database.md @@ -2,19 +2,19 @@ A job can keep everything it stores in a SpiralDB dataset: function results, pipeline records, operator caches, cached sources and side-effect logs. Open the dataset as a -**store** and give it to the job as any other database. +**writable SpiralDB database** and give it to the job as any other database. !!! warning "Provisional in 0.4.0" - The SpiralDB store is provisional. The format of its tables (how a table is named, + The writable SpiralDB database is provisional. The format of its tables (how a table is named, what its metadata records, how values are encoded) and its writer lease may change in a later version, and a later version may not read tables written now. Nothing of the - store enters a hash: a job's hashes, ids and stored paths are the same on SpiralDB as + database enters a hash: a job's hashes, ids and stored paths are the same on SpiralDB as on Delta. -## Opening a store +## Opening the SpiralDB database -`SpiralDBConnector(project_id, dataset, store=True)` opens one dataset as a store. Wrap it -in `ConnectorArrowDatabase` and use it as the job's database, its separate result +`SpiralDBConnector(project_id, dataset, writable=True)` opens one dataset as a writable +SpiralDB database. Wrap it in `ConnectorArrowDatabase` and use it as the job's database, its separate result database, or a cached source's database: @@ -22,25 +22,25 @@ database, or a cached source's database: from orcapod import PipelineJob from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector -store = ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", store=True) +database = ConnectorArrowDatabase( + SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) ) -job = PipelineJob(name="experiment", database=store) +job = PipelineJob(name="experiment", database=database) ``` Signing in is spiral-sdk's: the `SPIRAL_*` environment variables, or a saved -`spiral login`. Without `store=True`, a `SpiralDBConnector` reads existing keyed tables +`spiral login`. Without `writable=True`, a `SpiralDBConnector` reads existing keyed tables (a `SpiralDBTableSource`) and writes nothing. Each stored table is one keyed table of the dataset, named from its path (a readable part of the path and a digest of all of it). Its metadata records the full path, the layout, the data context and the columns, so a table under that name that another -writer made for something else is refused, never written over. The store reads and -writes only the tables it made: it does not take over a table it did not write. +writer made for something else is refused, never written over. The database reads +and writes only the tables it made: it does not take over a table it did not write. ## One writer at a time -A store has one writer at a time. Every run of a job (`job.run()`, `job.run_async()`, +The SpiralDB database has one writer at a time. Every run of a job (`job.run()`, `job.run_async()`, a job node's `run()`, and a load-only run that reads a cached source) takes the dataset's **writer lease** before it checks a source, computes or writes anything, and releases it when it ends, also when it fails. A run whose database and result database @@ -48,7 +48,7 @@ are on one dataset takes one lease. While one run holds the lease, a second writer, in this process or another, is refused when its run starts, with `LeaseBusyError`. Nothing of its run has happened then: no -source was checked, nothing computed, no store data table made. (A run that writes +source was checked, nothing computed, no data table made. (A run that writes several datasets takes their leases one after another, so a dataset whose lease it took before the refusal may hold a new lease table, released.) The error names the lease's table id and who holds it. The lease is refuse-only: the second writer does not wait and never @@ -65,15 +65,15 @@ except LeaseBusyError as refused: # SpiralDB dataset 'pipeline_results' has a conflicting writer lease (owner ..., table ID ...). ... ``` -Only a job run writes a store, through the store connectors it holds the lease with -(those of its databases and of the cached sources it reads). A write through any other -store connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a -connector of its own or over a `share_client()` copy, flushed directly) raises `SpiralDBStoreLeaseRequiredError` before +Only a job run writes the SpiralDB database, through the writable connectors it holds the +lease with (those of its databases and of the cached sources it reads). A write through +any other writable connector (a cached source read outside a run, a `ConnectorArrowDatabase` over a +connector of its own or over a `share_client()` copy, flushed directly) raises `SpiralDBLeaseRequiredError` before anything is written, also while a run holds the dataset's lease. A write through a running job's own databases from outside the run (another thread, an observer) is not told apart from the run's own: do not write through them while the job runs. A load-only run of a job writes no node's table, so it takes a lease only for a cached -source it reads. A run takes one lease per dataset of one service: store connectors +source it reads. A run takes one lease per dataset of one service: writable connectors whose client reaches the same service share it, whether their address was left to the default or given (`overrides={"server.url": ...}`). @@ -111,8 +111,8 @@ one, also released ones: removing one by hand can let two writers in. ## Saving and loading a job -A job saved on a store records the connector (`connector_type`, project, dataset, the -service address and `store: true`), never a credential. A connector is not rebuilt from +A job saved on the SpiralDB database records the connector (`connector_type`, project, +dataset, the service address and `writable: true`), never a credential. A connector is not rebuilt from a saved file: give it again when loading, as for every connector database: @@ -120,12 +120,13 @@ a saved file: give it again when loading, as for every connector database: loaded = PipelineJob.load( "experiment.json", database=ConnectorArrowDatabase( - SpiralDBConnector("my-project-123456", "pipeline_results", store=True) + SpiralDBConnector("my-project-123456", "pipeline_results", writable=True) ), ) ``` -A job saved on a store is loaded with a store connector, and one saved on a plain +A job saved on the SpiralDB database is loaded with a writable connector, and one saved +on a plain `SpiralDBConnector` with a plain one: the load refuses the other kind, since the two read different tables. @@ -134,12 +135,13 @@ read different tables. - Each check of which rows a table holds reads the table's whole key column, and each read of stored rows reads the whole table, so the cost of a run grows with the table's history. -- Only a job run writes a store: a cached source over a store is read within a run. A +- Only a job run writes the SpiralDB database: a cached source over it is read within a + run. A way to hold the lease outside a run is planned (ITL-1849). - Status and logging observers do not write to SpiralDB: they raise `SpiralDBObserverNotSupportedError` at setup; give them another database such as Delta. -- The store does not take over tables it did not write. -- A column the store cannot keep (a null struct, a duration, a nested logical type) is +- The database does not take over tables it did not write. +- A column the database cannot keep (a null struct, a duration, a nested logical type) is refused before anything of its table is written, naming the column. The other databases are compared type by type in [Data types per database](../reference/database-types.md). diff --git a/docs/dev/scripts/itl_1844_store_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py similarity index 80% rename from docs/dev/scripts/itl_1844_store_evaluation.py rename to docs/dev/scripts/itl_1844_database_evaluation.py index 791e269cb..e33ec9b5f 100644 --- a/docs/dev/scripts/itl_1844_store_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -1,21 +1,21 @@ -"""End-to-end evaluation of the SpiralDB store, as switched on by ITL-1844. +"""End-to-end evaluation of the writable SpiralDB database, as switched on by ITL-1844. One job holding every table kind (a cached source: ``sdb_v2``; a function pod: ``pdb_v2`` and ``rdb_v1``; a logged operator node: ``odb_v3``; a side-effect sink: ``tdb_v2``) is run -through each scenario on Delta and on a SpiralDB store, and every stored table is compared +through each scenario on Delta and on a writable SpiralDB database, and every stored table is compared value for value, apart from the columns a run fills with its own time or a random id. Scenarios: a first run (sync), a second run with one more input row, a REPLAY run of the operator, an async run (``run_async``) and a node run on fresh job names, a separate -result database on the same dataset, a saved job loaded with the store and read back, a +result database on the same dataset, a saved job loaded with the database and read back, a load-only run, and a second writer refused while a lease is held. - uv run python docs/dev/scripts/itl_1844_store_evaluation.py fake - uv run python docs/dev/scripts/itl_1844_store_evaluation.py live \\ + uv run python docs/dev/scripts/itl_1844_database_evaluation.py fake + uv run python docs/dev/scripts/itl_1844_database_evaluation.py live \\ --project --dataset ``live`` needs a sign-in spiral-sdk finds (the ``SPIRAL_*`` environment variables) and -writes into the given dataset only: store tables of job names starting with +writes into the given dataset only: database tables of job names starting with ``itl1844_eval_``, and one lease table per run. spiral-sdk cannot drop a keyed table, so they stay; the report lists every one. Prints a JSON report. """ @@ -49,7 +49,7 @@ SpiralDBConnector, ) from orcapod.databases import spiraldb_lease # noqa: E402 -from orcapod.databases.spiral_store_identity import spiral_store_table_name # noqa: E402 +from orcapod.databases.spiral_database_identity import spiral_table_name # noqa: E402 from orcapod.databases.spiraldb_connector import _open_keyed_table # noqa: E402 from orcapod.databases.spiraldb_write_scope import take_lease # noqa: E402 from orcapod.databases.store_table_names import spiral_lease_table_name # noqa: E402 @@ -164,27 +164,27 @@ def same_table(a: pa.Table | None, b: pa.Table | None) -> bool: ) -def compare(store: Any, delta: Any, prefix: tuple[str, ...]) -> dict[str, Any]: +def compare(spiral_db: Any, delta: Any, prefix: tuple[str, ...]) -> dict[str, Any]: """Every table under ``prefix``: the same paths and rows on both.""" return compare_paths( - store, [(p, delta, p) for p in delta.list_table_paths(prefix)], prefix + spiral_db, [(p, delta, p) for p in delta.list_table_paths(prefix)], prefix ) def compare_paths( - store: Any, + spiral_db: Any, expected: list[tuple[tuple[str, ...], Any, tuple[str, ...]]], prefix: tuple[str, ...], ) -> dict[str, Any]: - """The store's tables under ``prefix`` against ``expected``: each store path with + """The database's tables under ``prefix`` against ``expected``: each database table path with the database and path it must equal there.""" - paths = sorted(store.list_table_paths(prefix)) + paths = sorted(spiral_db.list_table_paths(prefix)) report: dict[str, Any] = { "same_paths": paths == sorted(p for p, _, _ in expected), "tables": {}, } for path, database, other in sorted(expected, key=lambda e: e[0]): - a = store.get_all_records(path) if path in paths else None + a = spiral_db.get_all_records(path) if path in paths else None same = same_table(a, database.get_all_records(other)) report["tables"]["/".join(path)] = { "layout": path[-1], @@ -209,39 +209,41 @@ def evaluate( ) -> None: """Run every scenario, filling ``report`` as each one ends.""" - def store() -> ConnectorArrowDatabase: - return ConnectorArrowDatabase(SpiralDBConnector(project, dataset, store=True)) + def spiral_db() -> ConnectorArrowDatabase: + return ConnectorArrowDatabase( + SpiralDBConnector(project, dataset, writable=True) + ) delta = DeltaTableDatabase(work / "delta") s = report["scenarios"] # 1. first run, sync. name = f"itl1844_eval_{stamp}_sync" - on_store = store() + on_spiral = spiral_db() CALLS.clear() - _ = timed(report, "first run (store)", lambda: build(name, on_store, n=6).run()) - store_calls = len(CALLS) + _ = timed(report, "first run (spiral)", lambda: build(name, on_spiral, n=6).run()) + spiral_calls = len(CALLS) _ = build(name, delta, n=6).run() s["first run"] = { - **compare(on_store, delta, (name,)), - "calls_on_store": store_calls, + **compare(on_spiral, delta, (name,)), + "calls_on_spiral": spiral_calls, } # 2. one more input row: only it is computed and delivered. CALLS.clear() SENT.clear() - _ = timed(report, "new row (store)", lambda: build(name, store(), n=7).run()) - store_calls, store_sent = len(CALLS), len(SENT) + _ = timed(report, "new row (spiral)", lambda: build(name, spiral_db(), n=7).run()) + spiral_calls, spiral_sent = len(CALLS), len(SENT) _ = build(name, delta, n=7).run() s["new row"] = { - **compare(store(), delta, (name,)), - "calls_on_store": store_calls, - "delivered_on_store": store_sent, + **compare(spiral_db(), delta, (name,)), + "calls_on_spiral": spiral_calls, + "delivered_on_spiral": spiral_sent, } # 3. REPLAY of the operator cache. replayed = [] - for database in (store(), delta): + for database in (spiral_db(), delta): job = build(name, database, n=7, cache_mode=CacheMode.REPLAY) _ = job.run() replayed.append(comparable(job.nodes["select"].as_table())) @@ -257,44 +259,48 @@ def store() -> ConnectorArrowDatabase: ("node run", lambda job: [job.nodes[k].run() for k in ("select", "sink")]), ): fresh = f"itl1844_eval_{stamp}_{label.replace(' ', '_')}" - _ = timed(report, f"{label} (store)", lambda: run(build(fresh, store(), n=6))) + _ = timed( + report, f"{label} (spiral)", lambda: run(build(fresh, spiral_db(), n=6)) + ) _ = run(build(fresh, delta, n=6)) - s[label] = compare(store(), delta, (fresh,)) + s[label] = compare(spiral_db(), delta, (fresh,)) # 6. a separate result database on the same dataset (one lease). fresh = f"itl1844_eval_{stamp}_results" results_delta = DeltaTableDatabase(work / "delta_results") - _ = build(fresh, store(), n=6, result_database=store().at(fresh, "results")).run() + _ = build( + fresh, spiral_db(), n=6, result_database=spiral_db().at(fresh, "results") + ).run() _ = build(fresh, delta, n=6, result_database=results_delta).run() s["separate results"] = compare_paths( - store(), separate_results_expected(fresh, delta, results_delta), (fresh,) + spiral_db(), separate_results_expected(fresh, delta, results_delta), (fresh,) ) - # 7. save, load with the store, read back, load-only run. + # 7. save, load with the database, read back, load-only run. saved = work / "job.json" - build(name, store(), n=7).save(saved) - loaded = PipelineJob.load(saved, database=store()) + build(name, spiral_db(), n=7).save(saved) + loaded = PipelineJob.load(saved, database=spiral_db()) read = { k: loaded.nodes[k].as_source().as_table().num_rows for k in ("combine", "select") } # The cached source is not rebuilt on load: bind its slot, so the load-only run # loads the whole branch. - loaded.bind(sources={"trials": trials(name, store(), n=7)}) + loaded.bind(sources={"trials": trials(name, spiral_db(), n=7)}) _ = loaded.run(load_only=True) s["save and load"] = save_and_load_outcome( - '"store": true' in saved.read_text(), + '"writable": true' in saved.read_text(), read, loaded.nodes["select"].as_table().num_rows, ) # 8. a second writer is refused while another holds the lease. _, release = take_lease( - SpiralDBConnector(project, dataset, store=True), "evaluation: another writer" + SpiralDBConnector(project, dataset, writable=True), "evaluation: another writer" ) fresh = f"itl1844_eval_{stamp}_refused" try: - build(fresh, store(), n=6).run() + build(fresh, spiral_db(), n=6).run() refused = False except spiraldb_lease.LeaseBusyError: refused = True @@ -302,7 +308,7 @@ def store() -> ConnectorArrowDatabase: release() s["second writer"] = { "refused": refused, - "nothing_written": store().list_table_paths((fresh,)) == [], + "nothing_written": spiral_db().list_table_paths((fresh,)) == [], } report["ok"] = succeeded(s) @@ -311,7 +317,7 @@ def store() -> ConnectorArrowDatabase: def separate_results_expected( name: str, delta: Any, results_delta: Any ) -> list[tuple[tuple[str, ...], Any, tuple[str, ...]]]: - """Where each store table of the separate-results job must equal a Delta table: + """Where each database table of the separate-results job must equal a Delta table: a result table (under ``/results``) the same path in ``results_delta``, any other the same path in ``delta``.""" return [(p, delta, p) for p in delta.list_table_paths((name,))] + [ @@ -327,12 +333,12 @@ def save_and_load_outcome( back and the load-only run's rows are the seven expected. Args: - flag_saved: Whether the saved job file holds the store flag. + flag_saved: Whether the saved job file holds the database flag. rows_read: Rows read back from each node's stored results, by node. load_only_rows: Rows of the load-only run's last node. """ return { - "store_flag_saved": flag_saved, + "writable_flag_saved": flag_saved, "rows_read": rows_read, "load_only_rows": load_only_rows, "ok": rows_read == {"combine": 7, "select": 7} and load_only_rows == 7, @@ -343,7 +349,7 @@ def succeeded(scenarios: dict[str, Any]) -> bool: """Every scenario as expected: tables as on Delta and the recorded outcomes. The first run computes all six rows; the new row is the only one computed and - delivered; the store flag is saved; the load-only run loads seven rows; a refused + delivered; the database flag is saved; the load-only run loads seven rows; a refused writer wrote nothing. """ first, new = scenarios.get("first run", {}), scenarios.get("new row", {}) @@ -353,10 +359,10 @@ def succeeded(scenarios: dict[str, Any]) -> bool: ) return ( all(v.get("ok", True) for v in scenarios.values()) - and first.get("calls_on_store") == 6 - and new.get("calls_on_store") == 1 - and new.get("delivered_on_store") == 1 - and saved.get("store_flag_saved") is True + and first.get("calls_on_spiral") == 6 + and new.get("calls_on_spiral") == 1 + and new.get("delivered_on_spiral") == 1 + and saved.get("writable_flag_saved") is True and saved.get("load_only_rows") == 7 and second.get("refused") is True and second.get("nothing_written") is True @@ -364,19 +370,21 @@ def succeeded(scenarios: dict[str, Any]) -> bool: def store_tables(project: str, dataset: str, stamp: str) -> list[dict[str, str]]: - """Every store table of this evaluation's jobs, by name and layout. + """Every database table of this evaluation's jobs, by name and layout. Listed under each job name only: a listing of the whole dataset is refused when the - dataset holds a table of another store format under a store table name. + dataset holds a table of another table format under a database table name. """ - store = ConnectorArrowDatabase(SpiralDBConnector(project, dataset, store=True)) + spiral_db = ConnectorArrowDatabase( + SpiralDBConnector(project, dataset, writable=True) + ) every = sorted( path for job_name in sorted({f"itl1844_eval_{stamp}_{x}" for x in JOB_SUFFIXES}) - for path in store.list_table_paths((job_name,)) + for path in spiral_db.list_table_paths((job_name,)) ) return [ - {"name": spiral_store_table_name(p), "layout": p[-1], "path": "/".join(p)} + {"name": spiral_table_name(p), "layout": p[-1], "path": "/".join(p)} for p in every ] @@ -446,7 +454,7 @@ def main() -> int: # fails (the service still down) is reported apart and never hides the report. report["store_tables"] = inventory( report, - "store tables", + "database tables", lambda: store_tables(args.project, args.dataset, stamp), ) after = inventory( diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index 4a0335757..197690290 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -61,8 +61,9 @@ The library value types (NumPy, pandas, Polars, torch) are The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a job's store ([SpiralDB as a Job's Database](../concepts/spiraldb-store.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a -job uses one. +SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's +Database](../concepts/spiraldb-database.md)), not compared here. See [The +database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 686a11742..15bddf13d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -391,7 +391,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` | | database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` | | SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` | -| SpiralDB store manifest checksum | a store table's manifest payload (record path and Arrow schemas, canonical JSON); the store is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_store.py:_checksum` | +| SpiralDB database manifest checksum | a writable SpiralDB database table's manifest payload (record path and Arrow schemas, canonical JSON); its format is provisional | SHA-256 hex | the manifest header's check of its chunks in the table's metadata (a checksum of a stored record) | `databases/spiral_database_codec.py:_checksum` | | Connector store table name | the full store path, as a compact UTF-8 JSON array of path components | SHA-256 hex, `spiral_table_name_v1` (`SPIRAL_TABLE_NAME_LABEL`) | the bare hexadecimal suffix in a table name, with a length set by the backend | `databases/store_table_names.py:store_table_digest` | | synthesized struct class name | the field signature | MD5 hex, 8 digits | a Python class name (a name) | (not reached by a traced test) `semantic_types/universal_converter.py` | | random ids | nothing | `uuid4`, `uuid7` | run ids, datagram and record uuids, observer ids, correlation keys | (not hashes) | diff --git a/site/astro.config.mjs b/site/astro.config.mjs index d7b1b05b6..bc6e5326b 100644 --- a/site/astro.config.mjs +++ b/site/astro.config.mjs @@ -169,7 +169,7 @@ export default defineConfig({ page('Function Pods', 'concepts/function-pods'), page('Data-tags', 'concepts/data-tags'), page('Pipelines and Jobs', 'concepts/pipeline-job'), - page('SpiralDB as a Job\'s Database', 'concepts/spiraldb-store'), + page('SpiralDB as a Job\'s Database', 'concepts/spiraldb-database'), page('Provenance', 'concepts/provenance'), page('Working in Notebooks', 'concepts/notebooks'), page('Your Own Data Types', 'concepts/your-own-data-types'), diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3457c9d90..d05c96a2a 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -371,7 +371,7 @@ def run_job_node( depends_on_job_nodes, refuse_unloadable_inputs, run_with_dependencies, - store_write_scope, + database_write_scope, ) from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.run_summary import warn_row_failures @@ -386,9 +386,10 @@ def run_job_node( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([node]) - # The writer leases of the SpiralDB stores the run may write are held from the - # source check to the end of the run; a second writer is refused (ITL-1844). - with store_write_scope([node], load_only=load_only): + # The writer leases of the writable SpiralDB databases the run may write are held + # from the source check to the end of the run; a second writer is refused + # (ITL-1844). + with database_write_scope([node], load_only=load_only): # Every source feeding the run first takes in any new data (ITL-1102). unchecked = check_sources([node]) if node.holds_current_run(load_only=load_only): diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 91a290cf8..e7679f4bb 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -2074,7 +2074,7 @@ def run(self, *, load_only: bool = False) -> StreamView: SourceSpecMismatchError: If a bound source now depends on a bindable slot or the live inputs contain a cycle (ITL-1559). """ - from orcapod.pipeline.node_run import store_write_scope + from orcapod.pipeline.node_run import database_write_scope from orcapod.pipeline.restrictions import refuse_restriction_conflicts from orcapod.pipeline.source_consistency import ( require_consistent_sources, @@ -2089,9 +2089,10 @@ def run(self, *, load_only: bool = False) -> StreamView: # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts([self]) - # The writer leases of the SpiralDB stores the run may write are held from the - # source check to the end of the run; a second writer is refused (ITL-1844). - with store_write_scope([self], load_only=load_only): + # The writer leases of the writable SpiralDB databases the run may write are + # held from the source check to the end of the run; a second writer is refused + # (ITL-1844). + with database_write_scope([self], load_only=load_only): return self._run_holding_leases( load_only=load_only, caller=sys._getframe(1), # pyright: ignore[reportPrivateUsage] # the caller's line is where the warning is shown diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 5c19f5f50..d16c5f72f 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1881,7 +1881,7 @@ def run(self, *, load_only: bool = False) -> StreamView: from orcapod.pipeline.node_run import ( check_sources, refuse_unloadable_inputs, - store_write_scope, + database_write_scope, ) from orcapod.pipeline.source_consistency import ( require_consistent_sources, @@ -1892,7 +1892,7 @@ def run(self, *, load_only: bool = False) -> StreamView: require_consistent_sources([(f"node {self.label!r}", self)]) # A cached source writes its cache when checked or read: its store's writer # lease is held for the run (ITL-1844). - with store_write_scope([self], load_only=load_only): + with database_write_scope([self], load_only=load_only): _ = check_sources([self]) if load_only: refuse_unloadable_inputs(self) diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 2b596bb49..9866f7b71 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -44,12 +44,12 @@ ) from orcapod.databases.postgresql_connector import PostgreSQLConnector from orcapod.databases.spiraldb_connector import SpiralDBConnector -from orcapod.databases.spiral_store_identity import ( - SpiralStoreTableCollisionError, +from orcapod.databases.spiral_database_identity import ( + SpiralTableCollisionError, refuse_other_format_path, ) -from orcapod.databases.spiraldb_store_tables import ( - StoreTables, +from orcapod.databases.spiraldb_tables import ( + SpiralDBTables, declared_keeping_identifier, ) from orcapod.logical_types.canonical_form import storage_form_schema @@ -130,11 +130,11 @@ def _with_live_logical_types( """Return ``records`` with each column given in a logical type's storage form live, when that changes nothing about its identifier. - For a SpiralDB store only (ITL-1840): rows are buffered and recorded in one form, so - a column given in storage form (its identifier as ``ARROW:extension:*`` field - metadata) is wrapped as the live type the rows' data context resolves for it, the - one rule a read and a table's schema apply too (``declared_keeping_identifier``: a - registered type, or one a factory rebuilds from the identifier). A column is + For a writable SpiralDB database only (ITL-1840): rows are buffered and recorded in + one form, so a column given in storage form (its identifier as ``ARROW:extension:*`` + field metadata) is wrapped as the live type the rows' data context resolves for it, + the one rule a read and a table's schema apply too (``declared_keeping_identifier``: + a registered type, or one a factory rebuilds from the identifier). A column is wrapped only when the live type states exactly the identifier bytes given: one the reader also reads under other bytes (an older identifier) is kept as given, so the bytes are never replaced @@ -168,11 +168,13 @@ def _with_live_logical_types( _R = TypeVar("_R") -def _one_store_operation( +def _one_spiral_operation( method: "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]", ) -> "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]": - """Run a public method as one operation of a SpiralDB store (``StoreTables.operation``): - each table name is opened once inside it and its handle reused. Any other + """Run a public method as one operation of a writable SpiralDB database. + + One ``SpiralDBTables.operation``: each table name is opened once inside it and its + handle reused. Any other connector calls the method as it is. """ @@ -182,9 +184,9 @@ def wrapped( ) -> _R: if self._spiral_connector is None: # pyright: ignore[reportPrivateUsage] return method(self, *args, **kwargs) - store = self._spiral # pyright: ignore[reportPrivateUsage] - assert store is not None - with store.operation(): + tables = self._spiral # pyright: ignore[reportPrivateUsage] + assert tables is not None + with tables.operation(): return method(self, *args, **kwargs) return wrapped @@ -227,10 +229,10 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. - A SpiralDB store, ``SpiralDBConnector(..., store=True)`` (provisional in 0.4.0), is - read and written through its store tables (``spiraldb_store_tables``): names - computed from the full path, identity and manifest in each table's metadata, rows - through the store codec. Its writes need the writer lease a job run holds + A writable SpiralDB database, ``SpiralDBConnector(..., writable=True)`` (provisional + in 0.4.0), is read and written through its database tables (``spiraldb_tables``): + names computed from the full path, identity and manifest in each table's metadata, + rows through the database codec. Its writes need the writer lease a job run holds (``spiraldb_write_scope``). A plain ``SpiralDBConnector`` refuses every write, as before. @@ -264,11 +266,11 @@ def __init__( self._sql_store: SQLStoreConnector | None = ( connector if isinstance(connector, SQLStoreConnector) else None ) - # A SpiralDB connector in store mode; ``None`` for any other (ITL-1840). + # A writable SpiralDB connector; ``None`` for any other (ITL-1840). self._spiral_connector: SpiralDBConnector | None = ( connector if isinstance(connector, SpiralDBConnector) - and connector._store_tables() is not None # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + and connector._writable_tables() is not None # pyright: ignore[reportPrivateUsage] # the database's one reader and writer else None ) self.max_hierarchy_depth = max_hierarchy_depth @@ -323,15 +325,15 @@ def __init__( ) @property - def _spiral(self) -> StoreTables | None: - """The SpiralDB store's tables, or ``None`` for any other connector. + def _spiral(self) -> SpiralDBTables | None: + """The writable SpiralDB database's tables, or ``None`` for any other connector. Raises: - RuntimeError: If the store's connector has been closed. + RuntimeError: If the database's connector has been closed. """ if self._spiral_connector is None: return None - return self._spiral_connector._store_tables() # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + return self._spiral_connector._writable_tables() # pyright: ignore[reportPrivateUsage] # the database's one reader and writer def _discard_pending_state(self, key: str) -> None: """Forget indexes when an entire queued batch is discarded.""" @@ -346,9 +348,9 @@ def _get_record_key(self, record_path: tuple[str, ...]) -> str: full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: if self._spiral_connector is not None: - # A path list_table_paths gives a table of another store format, - # then the one path domain of a SpiralDB store (its identity record - # and manifest apply it too). + # A path list_table_paths gives a table of another table format, + # then the one path domain of a writable SpiralDB database (its identity + # record and manifest apply it too). refuse_other_format_path(full_path) _ = require_store_path_domain(full_path) return "/".join(full_path) @@ -375,8 +377,8 @@ def _schema_from_record_key(self, record_key: str) -> str | None: def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: """Map a full record path to a name the connector can store.""" - if (store := self._spiral) is not None: - return store.table_name(self._plain_path(record_path)) + if (tables := self._spiral) is not None: + return tables.table_name(self._plain_path(record_path)) if self._sql_store is not None and record_path: return store_table_name( self._plain_path(record_path), @@ -469,8 +471,8 @@ def _find_committed_table( self, table_name: str, full_path: tuple[str, ...], *, schema: str | None ) -> tuple[str | None, str] | None: """Return the verified schema and name of a committed table.""" - if (store := self._spiral) is not None: - return (None, table_name) if store.has_table(table_name) else None + if (tables := self._spiral) is not None: + return (None, table_name) if tables.has_table(table_name) else None if self._sql_store is None: if table_name in self._connector.get_table_names(): return None, table_name @@ -497,8 +499,8 @@ def _get_committed_table( cannot read the stored table fails the run rather than one row (``job.run``'s contract for an unreadable stored table), as ``get_table_schema`` does. - SpiralStoreTableCollisionError: If the table under the name is not this - path's store table. + SpiralTableCollisionError: If the table under the name is not this + path's database table. """ full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) @@ -512,15 +514,15 @@ def _get_committed_table( if table is None: return None schema, name = table - if (store := self._spiral) is not None: - batches = list(store.scan(name)) + if (tables := self._spiral) is not None: + batches = list(tables.scan(name)) else: batches = list( self._connector.iter_batches( f"SELECT * FROM {sql_table_identifier(name, schema)}" ) ) - except (OrcapodDatabaseError, SpiralStoreTableCollisionError): + except (OrcapodDatabaseError, SpiralTableCollisionError): # A table that is not this path's is refused as such, never as unreadable. raise except Exception as exc: @@ -533,8 +535,8 @@ def _stored_conflicts( """Return input IDs found in the committed table.""" schema, name = table column = self.RECORD_ID_COLUMN - if (store := self._spiral) is not None: - return store.existing_record_ids(name, input_ids) + if (tables := self._spiral) is not None: + return tables.existing_record_ids(name, input_ids) if self._sql_store is not None: assert schema is not None return self._sql_store.existing_record_ids( @@ -542,7 +544,7 @@ def _stored_conflicts( ) return self._connector.existing_record_ids(name, column, input_ids) - @_one_store_operation + @_one_spiral_operation def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -550,14 +552,14 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] catalog and pending batches. Other connectors list by sanitized names. No record table is read. - A SpiralDB store lists its tables by the paths their identity records hold. - A table whose record names another store format is listed with the last - component ``"/"``, which no layout and no store path - can equal (a component never holds ``/``): stale-layout detection reports it - as a table of another layout, and opening that path raises ``ValueError`` - saying what it is. A partial or unreadable record, or a record of a path - whose table has another name, refuses the whole listing - (``SpiralStoreTableCollisionError``). + A writable SpiralDB database lists its tables by the paths their identity + records hold. A table whose record names another table format is listed with + the last component ``"/"``, which no layout and no + database table path can equal (a component never holds ``/``): stale-layout + detection reports it as a table of another layout, and opening that path raises + ``ValueError`` saying what it is. A partial or unreadable record, or a record of + a path whose table has another name, refuses the whole listing + (``SpiralTableCollisionError``). Args: prefix: Leading path components, relative to ``self.base_path``. @@ -566,13 +568,13 @@ 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 - if (store := self._spiral) is not None: + if (tables := self._spiral) is not None: full_prefix = self._plain_path(full_prefix) pending = [self._record_path_from_key(key) for key in self._pending_batches] return sorted( { path[len(self._path_prefix) :] - for path in store.table_paths(full_prefix, pending) + for path in tables.table_paths(full_prefix, pending) } ) if self._sql_store is not None: @@ -618,7 +620,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) return sorted(found) - @_one_store_operation + @_one_spiral_operation def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a table exists at ``record_path``. @@ -645,7 +647,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── - @_one_store_operation + @_one_spiral_operation def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the committed or queued schema without fetching rows. @@ -669,9 +671,9 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: pending = self._pending_batches.get(record_key) return None if pending is None else pending.schema schema, name = table - if (store := self._spiral) is not None: + if (tables := self._spiral) is not None: # As recorded: field and schema metadata included, as a read gives. - return store.arrow_schema(name) + return tables.arrow_schema(name) return pa.schema( pa.field(column.name, column.arrow_type, nullable=column.nullable) for column in self._column_info(name, schema) @@ -698,11 +700,11 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column the connector cannot store, naming the connector, the column, its Arrow type and why. """ - store = self._spiral + tables = self._spiral for field in schema: primary_key = field.name == self.RECORD_ID_COLUMN - if store is not None: - reason = store.unstorable_column_reason( + if tables is not None: + reason = tables.unstorable_column_reason( field.name, field.type, primary_key ) else: @@ -773,12 +775,12 @@ def validate_records(self, records: pa.Table) -> None: Args: records: The rows (any number, none included) to check. """ - if (store := self._spiral) is not None: - store.validate(records, None) + if (tables := self._spiral) is not None: + tables.validate(records, None) return self._connector.validate_records(records) - @_one_store_operation + @_one_spiral_operation def add_records( self, record_path: tuple[str, ...], @@ -828,9 +830,9 @@ def add_records( table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) records = normalize_table_to_large_types(records, keep_null=True) - # The schemas a SpiralDB store holds for the table, as recorded. + # The schemas a writable SpiralDB database holds for the table, as recorded. recorded: list[pa.Schema] = [] - if (store := self._spiral) is not None: + if (tables := self._spiral) is not None: from orcapod.contexts import resolve_context # The identifier bytes as given, against those held as recorded, before @@ -846,25 +848,26 @@ def add_records( # live: buffered and stored in one form, resolved under the rows' own data # context. That context is checked against the one the table records, # before the rows are buffered. - converter = resolve_context(store.data_context(records)).type_converter + converter = resolve_context(tables.data_context(records)).type_converter records = _with_live_logical_types( records, cast("LogicalTypeConverterProtocol", cast(object, converter)), ) - store.validate(records, table_name) + tables.validate(records, table_name) else: self._connector.validate_records(records) record_key = self._get_record_key(record_path) - if store is not None: - # One data context per store table, as its write requires: rows of another - # one than those pending for the table are refused here, never buffered. + if tables is not None: + # One data context per database table, as its write requires: rows of + # another one than those pending for the table are refused here, never + # buffered. pending = self._pending_batches.get(record_key) if pending is not None: from orcapod.contexts.stored import require_same_data_context require_same_data_context( - store.data_context(records), store.data_context(pending) + tables.data_context(records), tables.data_context(pending) ) committed_table = None pending_owner_key: tuple[str, str] | None = None @@ -886,7 +889,7 @@ def add_records( # A column of another logical type is refused first, on the raw identifier # bytes, before the reorder compares types (ITL-1371). # The held schemas are gathered once for both checks (one table listing). - if store is not None: + if tables is not None: # Compared as recorded: every logical type in its storage form. records = in_held_column_order( records, self._held_column_order(record_path) @@ -992,8 +995,8 @@ def _held_column_order( def _column_info(self, table_name: str, schema: str | None) -> list[ColumnInfo]: """Inspect the relation selected by the catalog when a schema was verified.""" - if (store := self._spiral) is not None: - return store.column_info(table_name) + if (tables := self._spiral) is not None: + return tables.column_info(table_name) if self._sql_store is not None: return self._sql_store.get_column_info(table_name, schema=schema) return self._connector.get_column_info(table_name) @@ -1040,10 +1043,10 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: return held def _recorded_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema]: - """The schemas a SpiralDB store holds for a table, as recorded: the pending - batch's and the stored manifest's, every logical type in its storage form with - the identifier bytes it was given with (``_with_live_logical_types`` never - replaces them). For the identifier check, before any form is converted. + """The schemas a writable SpiralDB database holds for a table, as recorded: the + pending batch's and the stored manifest's, every logical type in its storage + form with the identifier bytes it was given with (``_with_live_logical_types`` + never replaces them). For the identifier check, before any form is converted. Args: record_path: The table's path, relative to ``base_path``. @@ -1051,16 +1054,16 @@ def _recorded_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema]: Returns: The schemas, pending first. """ - store = self._spiral - assert store is not None + tables = self._spiral + assert tables is not None held: list[pa.Schema] = [] record_key = self._get_record_key(record_path) pending = self._pending_batches.get(record_key) if pending is not None: held.append(storage_form_schema(pending.schema)) table_name = self._path_to_table_name(self._path_prefix + record_path) - if store.has_table(table_name): - held.append(store.recorded_schema(table_name)) + if tables.has_table(table_name): + held.append(tables.recorded_schema(table_name)) return held def _refuse_changed_columns( @@ -1108,8 +1111,8 @@ def _read_stored_schema( Read without rows from a connector that offers ``get_arrow_schema`` (``SpiralDBConnector``); from any other, the schema of its first batch. """ - if (store := self._spiral) is not None: - return store.arrow_schema(table_name) + if (tables := self._spiral) is not None: + return tables.arrow_schema(table_name) get_arrow_schema = getattr(self._connector, "get_arrow_schema", None) if callable(get_arrow_schema): return cast("pa.Schema", get_arrow_schema(table_name)) @@ -1196,7 +1199,7 @@ def guard_table_schema( self._get_record_key(record_path), check ) - @_one_store_operation + @_one_spiral_operation def flush(self) -> None: """Insert all ready batches into the connector.""" for record_key in list(self._pending_batches): @@ -1211,7 +1214,7 @@ def flush_result_batch( """Commit a durable result table even if no pipeline records are stored.""" self.flush_batch(record_path) - @_one_store_operation + @_one_spiral_operation def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) @@ -1236,8 +1239,8 @@ def _flush_by_key(self, record_key: str) -> None: record_path = self._record_path_from_key(record_key) table_name = self._path_to_table_name(record_path) self._require_table_name(table_name) - if (store := self._spiral) is not None: - transaction = nullcontext((None, store.has_table(table_name))) + if (tables := self._spiral) is not None: + transaction = nullcontext((None, tables.has_table(table_name))) elif self._sql_store is None: transaction = nullcontext( (None, table_name in self._connector.get_table_names()) @@ -1288,17 +1291,17 @@ def _write_ready_batch( schema: str | None, ) -> None: """Check the current schema and write the ready rows.""" - store = self._spiral - if store is not None: + tables = self._spiral + if tables is not None: # The rows against the table as it is now: it may have been made since # they were buffered, recording another data context or other identifiers # (compared as recorded, before any form is converted: ITL-1371). - store.validate(pending, table_name) + tables.validate(pending, table_name) if table_exists: self._refuse_changed_columns( self._record_path_from_key(record_key), storage_form_schema(pending.schema), - [store.recorded_schema(table_name)], + [tables.recorded_schema(table_name)], ) columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). @@ -1307,21 +1310,21 @@ def _write_ready_batch( if check is not None: if existing is None: schema_now = pending.schema - elif store is not None: + elif tables is not None: # As recorded: field and schema metadata included, as # ``get_table_schema`` gives it. - schema_now = store.arrow_schema(table_name) + schema_now = tables.arrow_schema(table_name) else: schema_now = pa.schema(existing) - if store is None: + if tables is None: check(schema_now) else: # The caller's check runs outside this operation: a public call it # makes looks every name up again, and the write opens its table again. - with store.outside_operation(): + with tables.outside_operation(): check(schema_now) if existing is not None: - if self.keeps_field_metadata and store is None: + if self.keeps_field_metadata and tables is None: # A different handle may have created the table after this batch # was queued. The connector's ColumnInfo omits field metadata. held = self._read_stored_schema(table_name, schema) @@ -1355,12 +1358,12 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # Another writer can commit an ID after it was checked at add time. # Use the connector's atomic insert-if-missing for both modes. - if store is not None: + if tables is not None: # Writes only the keys the write's fresh key read does not show: a row # visible then is never overwritten (SpiralDB's append replaces a row of # the same key). A key another writer stores after that read can still # be replaced until the one-writer lease (ITL-1452). - store.write(table_name, pending) + tables.write(table_name, pending) elif self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN @@ -1396,7 +1399,7 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # ── Read methods ────────────────────────────────────────────────────────── - @_one_store_operation + @_one_spiral_operation def get_record_by_id( self, record_path: tuple[str, ...], @@ -1446,7 +1449,7 @@ def get_record_by_id( report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) - @_one_store_operation + @_one_spiral_operation def get_all_records( self, record_path: tuple[str, ...], @@ -1478,7 +1481,7 @@ def get_all_records( table = parts[0] if len(parts) == 1 else pa.concat_tables(_alike(parts)) return self._handle_record_id_column(table, record_id_column) - @_one_store_operation + @_one_spiral_operation def get_records_by_ids( self, record_path: tuple[str, ...], @@ -1503,7 +1506,7 @@ def get_records_by_ids( return None return self._handle_record_id_column(filtered, record_id_column) - @_one_store_operation + @_one_spiral_operation def get_records_with_column_value( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/spiral_store.py b/src/orcapod/databases/spiral_database_codec.py similarity index 95% rename from src/orcapod/databases/spiral_store.py rename to src/orcapod/databases/spiral_database_codec.py index 100d0bbab..92926c51e 100644 --- a/src/orcapod/databases/spiral_store.py +++ b/src/orcapod/databases/spiral_database_codec.py @@ -1,4 +1,4 @@ -"""The codec of an Orcapod store table in SpiralDB (ITL-1446, ITL-1837). +"""The codec of an Orcapod database table in SpiralDB (ITL-1446, ITL-1837). Pure functions, with no SpiralDB client: they say how a table Orcapod stores is written to SpiralDB and how it is read back. Nothing calls them yet, and the format they write is @@ -16,18 +16,18 @@ * **The manifest.** One a table, written before its first rows; a table that still has no rows may be recorded again (``manifest_entries``, ``read_manifest``): the record path, the kind, the logical schema, and the stored names at every depth. It is - kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's identity - record (``spiral_store_identity``); never in the dataset's schema table, which is all - or nothing under one completion marker (decision of 2026-11-26). + kept in the table's own metadata, in chunks of at most 8 KiB, beside the table's + identity record (``spiral_database_identity``); never in the dataset's schema table, + which is all or nothing under one completion marker (decision of 2026-11-26). Logical types are handled by their identifier (extension name and metadata) alone, as ``ARROW:extension:*`` field metadata over the storage type: neither writing nor reading a manifest consults the types registered in the process. ``canonical_form.declaration_form_schema`` makes them live. -A SpiralDB store is a set of rows: the order of rows is not kept. An order-sensitive -step (``Batch``) over a stored source may therefore group differently than over a Delta -store. +A writable SpiralDB database 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 database. """ from __future__ import annotations @@ -59,7 +59,7 @@ # ------------------------------------------------------------------------ errors -class SpiralStoreError(ValueError): +class SpiralDatabaseError(ValueError): """A column, value, name or manifest the codec refuses. Attributes: @@ -82,15 +82,15 @@ def __str__(self) -> str: return f"column {where}: {self.reason}" -class UnstorableInSpiralError(SpiralStoreError): +class UnstorableInSpiralError(SpiralDatabaseError): """Rows or a schema SpiralDB would not give back exactly. Nothing was written.""" -class StoredRowsError(SpiralStoreError): +class StoredRowsError(SpiralDatabaseError): """Rows read from SpiralDB are not what the manifest says was written.""" -class ManifestError(SpiralStoreError): +class ManifestError(SpiralDatabaseError): """A manifest cannot be read, is of an unknown format or version, or is not the one asked for.""" @@ -100,7 +100,7 @@ def _at(segment: str) -> Iterator[None]: """Add ``segment`` in front of the path of an error raised inside.""" try: yield - except SpiralStoreError as exc: + except SpiralDatabaseError as exc: exc.path = (segment, *exc.path) raise @@ -150,7 +150,7 @@ def _require_utf8(text: str) -> None: @dataclass(frozen=True) class Refusal: - """Something the store does not keep. + """Something the database does not keep. Attributes: what: What it is. @@ -166,7 +166,7 @@ class Refusal: def error(self) -> UnstorableInSpiralError: """The refusal as an error.""" return UnstorableInSpiralError( - f"a SpiralDB store refuses {self.what} ({self.why})" + f"a writable SpiralDB database refuses {self.what} ({self.why})" ) @@ -174,7 +174,7 @@ def error(self) -> UnstorableInSpiralError: _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") +NO_ROWS = Refusal("a write of no rows", "it publishes nothing; the database sends none") RENAMED_MAP = Refusal( "a map whose fields are not named key and value", "Arrow IPC renames them" ) @@ -192,7 +192,7 @@ def error(self) -> UnstorableInSpiralError: # Substitutes that held live, not used yet: large_binary, int64. Refusal("a fixed-size binary", _REFUSED_LIVE, _types.is_fixed_size_binary), # spiral-sdk 0.16.80 accepts a duration column (0.16.78 refused it); whether the - # store keeps durations is decided apart (ITL-1852). + # database keeps durations is decided apart (ITL-1852). Refusal("a duration", "its encoding is not decided (ITL-1852)", _types.is_duration), Refusal("an interval", _REFUSED_LIVE, _types.is_interval), ) @@ -253,7 +253,9 @@ def _logical_field(field: pa.Field[Any]) -> pa.Field[Any]: if pa.types.is_dictionary(arrow_type): # An encoding, not a type: refused here, before a dictionary of a logical # type's values is taken for that type (``identity_node`` looks through it). - raise UnstorableInSpiralError(f"a SpiralDB store keeps no type {arrow_type}") + raise UnstorableInSpiralError( + f"a writable SpiralDB database keeps no type {arrow_type}" + ) if node.identifier is not None and EXTENSION_NAME_KEY not in (field.metadata or {}): arrow_type = arrow_type.storage_type _refuse_nested_identifier(arrow_type) @@ -421,7 +423,9 @@ def _physical_type(arrow_type: pa.DataType) -> pa.DataType: 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}") + raise UnstorableInSpiralError( + f"a writable SpiralDB database keeps no type {arrow_type}" + ) def physical_schema(schema: pa.Schema) -> pa.Schema: @@ -601,7 +605,7 @@ def _large_list(array: Any, items: Any, target: Any) -> Any: # ------------------------------------------------------------------- rows, as read -def require_stored_schema(found: pa.Schema, manifest: StoreManifest) -> None: +def require_stored_schema(found: pa.Schema, manifest: TableManifest) -> 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. @@ -659,7 +663,7 @@ def _require_type(found: Any, logical: Any, stored: Any) -> None: def decode_rows( - rows: pa.Table, manifest: StoreManifest, schema: pa.Schema | None = None + rows: pa.Table, manifest: TableManifest, schema: pa.Schema | None = None ) -> pa.Table: """Return rows read from SpiralDB as the logical rows they were written from. @@ -706,7 +710,7 @@ def decode_rows( return pa.Table.from_arrays(columns, schema=target) -def empty_rows(manifest: StoreManifest) -> pa.Table: +def empty_rows(manifest: TableManifest) -> 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 @@ -807,10 +811,10 @@ def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: # ---------------------------------------------------------------------- the manifest -# A draft, written only while no public way opens a store: the persisted format and -# version are fixed when the store is switched on, with a decision then on reading the +# A draft, provisional in 0.4.0: the persisted format and version are fixed in a later +# version, with a decision then on reading the # tables written in this draft format. Provisional: outside the 0.4.0 freeze. -MANIFEST_FORMAT = "orcapod.spiral_store.draft" +MANIFEST_FORMAT = "orcapod.spiral_database.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 @@ -820,8 +824,8 @@ def _decode(array: Any, field: pa.Field[Any], physical: pa.Field[Any]) -> Any: @dataclass(frozen=True) -class StoreManifest: - """What a store table's manifest says. Make one with ``new_manifest``. +class TableManifest: + """What a database table's manifest says. Make one with ``new_manifest``. Attributes: record_path: The table's full record path, each component exact. @@ -839,7 +843,7 @@ class StoreManifest: def new_manifest( record_path: tuple[str, ...], kind: str, schema: pa.Schema -) -> StoreManifest: +) -> TableManifest: """Return the manifest of a table to be created. Args: @@ -852,20 +856,21 @@ def new_manifest( Raises: UnstorableInSpiralError: If the schema cannot be stored, or the path is outside - the store path domain (``store_table_names.require_store_path_domain``, - which the table's identity record applies too). + the database table path domain + (``store_table_names.require_store_path_domain``, which the table's identity + record applies too). """ try: _ = require_store_path_domain(record_path) except ValueError as exc: raise UnstorableInSpiralError(str(exc)) from exc _require_utf8(kind) - return StoreManifest( + return TableManifest( record_path, kind, logical_schema(schema), physical_schema(schema) ) -def manifest_bytes(manifest: StoreManifest) -> bytes: +def manifest_bytes(manifest: TableManifest) -> bytes: """Return the payload that records ``manifest``. ``manifest_entries`` cuts it into a table's metadata entries. Writing the same @@ -911,7 +916,7 @@ def _schema_of(text: object) -> pa.Schema: raise ManifestError(f"a schema cannot be read ({exc})") from exc -def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreManifest: +def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> TableManifest: """Return the manifest ``manifest_bytes`` recorded. Args: @@ -924,7 +929,7 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM 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. + or of another path; or the recorded schemas are not a database table's. """ try: body = json.loads(recorded.decode("ascii")) @@ -957,7 +962,9 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM try: _ = require_store_path_domain(cast("list[str]", path)) except ValueError as exc: - raise ManifestError(f"the recorded path is not a store path: {exc}") from exc + raise ManifestError( + f"the recorded path is not a database table path: {exc}" + ) from exc if tuple(cast("list[str]", path)) != record_path: raise ManifestError( f"the table is recorded as {path}, not as {list(record_path)}" @@ -969,7 +976,7 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM expected = physical_schema(schema) except UnstorableInSpiralError as exc: raise ManifestError( - f"the recorded schema is not a store schema: {exc}" + f"the recorded schema is not a database table schema: {exc}" ) from exc except UnicodeDecodeError as exc: # pyarrow holds a name of any bytes, and fails where it is read as text. @@ -984,7 +991,7 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM _require_distinct(physical) except UnicodeDecodeError as exc: raise ManifestError(f"a recorded name is not UTF-8 text ({exc})") from exc - return StoreManifest(record_path, kind, usable, physical) + return TableManifest(record_path, kind, usable, physical) MANIFEST_KEY = "orcapod.manifest" @@ -995,7 +1002,7 @@ def read_manifest_bytes(recorded: bytes, record_path: tuple[str, ...]) -> StoreM _CHUNK_BYTES = 8_000 -def manifest_entries(manifest: StoreManifest) -> dict[str, bytes]: +def manifest_entries(manifest: TableManifest) -> 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 @@ -1028,7 +1035,7 @@ def manifest_entries(manifest: StoreManifest) -> dict[str, bytes]: def read_manifest( metadata: Mapping[str, bytes], record_path: tuple[str, ...] -) -> StoreManifest | None: +) -> TableManifest | None: """Return the manifest in a table's metadata. Args: diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_database_identity.py similarity index 50% rename from src/orcapod/databases/spiral_store_identity.py rename to src/orcapod/databases/spiral_database_identity.py index bc0521355..9cbb5639c 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_database_identity.py @@ -1,17 +1,18 @@ -"""The name and identity record of a SpiralDB store table (ITL-1837). +"""The name and identity record of a writable SpiralDB database table (ITL-1837). -A store table's full path (the store's base path plus the record path) is too long for a -SpiralDB table name, so the table is named by the rule every connector store shares, +A database table's full path (the database's base path plus the record path) is too long +for a SpiralDB table name, so the table is named by the rule every connector database +shares, ``store_table_names.store_table_name``, with SpiralDB's budget: a hint of at most -``SPIRAL_HINT_LENGTH`` characters and the whole 64-digit digest. The full path is written -into the table's own metadata, with the store format, the layout and the data context of -the writer that created it. A store computes the name to find a table and never lists to -find one; the record says which path a table holds, and a table recording another path is -refused (``SpiralStoreTableCollisionError``). +``SPIRAL_HINT_LENGTH`` characters and the whole 64-digit digest. The full path is +written into the table's own metadata, with the table format, the layout and the data +context of the writer that created it. The database computes the name to find a table +and never lists to find one; the record says which path a table holds, and a table +recording another path is refused (``SpiralTableCollisionError``). -The store format is provisional: it is outside the 0.4.0 freeze, and no public way to -open a store exists yet. Its marker (``STORE_FORMAT``) says so, so a table written in it -is told apart from one written in the format that is eventually fixed. +The table format is provisional: it is outside the 0.4.0 freeze. Its marker +(``TABLE_FORMAT``) says so, so a table written in it is told apart from one written in +the format that is eventually fixed. The module is pure: it imports no SpiralDB client. """ @@ -32,14 +33,13 @@ ) -class SpiralStoreTableCollisionError(ValueError): - """A SpiralDB table under a store table's name is not that store table. +class SpiralTableCollisionError(ValueError): + """A SpiralDB table under a database table's name is not that database table. - A store table's name is computed from its full path; its metadata records the path, - the store format, the layout and the data context. A table whose record names another - path or format, or is incomplete or unreadable, is refused: never read, written or - adopted. Internal while the store is not offered (it moves to ``orcapod.errors`` when - a store can be opened). + A database table's name is computed from its full path; its metadata records the + path, the table format, the layout and the data context. A table whose record names + another path or format, or is incomplete or unreadable, is refused: never read, + written or adopted. Internal: not part of ``orcapod.errors``. Attributes: reason: What is wrong. @@ -51,35 +51,49 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: self.reason = reason self.table = table where = "" if table is None else f"table {table}: " - super().__init__(f"{where}not this store's table: {reason}") + super().__init__(f"{where}not this database's table: {reason}") SPIRAL_HINT_LENGTH = 96 -"""The most characters of a SpiralDB store table name's hint.""" +"""The most characters of a writable SpiralDB database table name's hint.""" SPIRAL_DIGEST_LENGTH = 64 -"""The hex digits of the path digest a SpiralDB store table name keeps: all of them.""" +"""The hex digits of the path digest a writable SpiralDB database table name keeps: all +of them. +""" -STORE_FORMAT = "orcapod.spiral_store.draft" -"""The format of a store table, recorded in its metadata. Provisional: fixed (and renamed) -when the store is switched on.""" +TABLE_FORMAT = "orcapod.spiral_database.draft" +"""The format of a database table, recorded in its metadata. Provisional: fixed in a later +version.""" MAX_METADATA_ENTRY_BYTES = 8192 """The most UTF-8 bytes of a metadata entry's key and value together that SpiralDB accepts (measured with spiral-sdk 0.16.78).""" -STORE_KEY = "orcapod.store" +FORMAT_KEY = "orcapod.table_format" 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) +_RECORD_KEYS = (FORMAT_KEY, PATH_KEY, LAYOUT_KEY, DATA_CONTEXT_KEY) +EARLIER_DRAFT_FORMAT_KEY = "orcapod.store" +"""The key an earlier draft of the format recorded its format under (before 0.4.0). + +A table that records its format there is of another table format: a listing reports it +as one, and it is never read or written.""" + +def _with_format_entry(metadata: Mapping[str, bytes]) -> Mapping[str, bytes]: + """The metadata, with an earlier draft's format entry under ``FORMAT_KEY``.""" + if FORMAT_KEY in metadata or EARLIER_DRAFT_FORMAT_KEY not in metadata: + return metadata + return {**metadata, FORMAT_KEY: metadata[EARLIER_DRAFT_FORMAT_KEY]} -def spiral_store_table_name(path: Sequence[str]) -> str: - """Return the SpiralDB name of the store table at ``path``. + +def spiral_table_name(path: Sequence[str]) -> str: + """Return the SpiralDB name of the database table at ``path``. Args: - path: The full path components: the store's base path, then the record path. + path: The full path components: the database's base path, then the record path. Returns: ``o1__``, at most 164 characters, all in ``[a-z0-9_]``. @@ -92,14 +106,15 @@ def spiral_store_table_name(path: Sequence[str]) -> str: ) -def spiral_store_table_name_prefix(prefix: Sequence[str]) -> str: - """Return the start of the name of every store table whose path starts with ``prefix``. +def spiral_table_name_prefix(prefix: Sequence[str]) -> str: + """Return the start of the name of every database 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. + prefix: Leading full path components; empty for every database table. """ if not prefix: return STORE_TABLE_NAME_PREFIX @@ -109,8 +124,8 @@ def spiral_store_table_name_prefix(prefix: Sequence[str]) -> str: @dataclass(frozen=True) -class StoreTableRecord: - """What a store table's metadata records. +class TableRecord: + """What a database table's metadata records. Attributes: path: The full path components. @@ -123,17 +138,17 @@ class StoreTableRecord: data_context_key: str -def store_table_metadata( +def table_identity_metadata( path: Sequence[str], data_context_key: str ) -> dict[str, bytes]: - """Return the metadata a new store table at ``path`` is given. + """Return the metadata a new database table at ``path`` is given. Args: path: The full path components. data_context_key: The data context of the writer creating the table. Raises: - ValueError: If the path is outside the store path domain + ValueError: If the path is outside the database table path domain (``store_table_names.require_store_path_domain``), the data context key is empty, or an entry is over SpiralDB's entry limit (``MAX_METADATA_ENTRY_BYTES``). @@ -141,9 +156,9 @@ def store_table_metadata( components = require_store_path_domain(path) # one read of ``path``, kept path_json = store_table_path_json(components) if not data_context_key: - raise ValueError("a store table records the data context that created it") + raise ValueError("a database table records the data context that created it") record = { - STORE_KEY: STORE_FORMAT.encode(), + FORMAT_KEY: TABLE_FORMAT.encode(), PATH_KEY: path_json, LAYOUT_KEY: components[-1].encode(), DATA_CONTEXT_KEY: data_context_key.encode(), @@ -158,8 +173,8 @@ def store_table_metadata( return record -def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord | None: - """Return the store table record in a table's metadata. +def read_table_identity_metadata(metadata: Mapping[str, bytes]) -> TableRecord | None: + """Return the database table record in a table's metadata. Args: metadata: The table's metadata, as SpiralDB returns it. @@ -169,28 +184,29 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord creation stopped before its metadata, or another program's. Raises: - SpiralStoreTableCollisionError: If the record is partial, of another format, or + SpiralTableCollisionError: If the record is partial, of another format, or unreadable. """ + metadata = _with_format_entry(metadata) if not any(k in metadata for k in _RECORD_KEYS): return None _require_complete(metadata) - if metadata[STORE_KEY] != STORE_FORMAT.encode(): - raise SpiralStoreTableCollisionError( - f"its format is {metadata[STORE_KEY]!r}, not {STORE_FORMAT!r}" + if metadata[FORMAT_KEY] != TABLE_FORMAT.encode(): + raise SpiralTableCollisionError( + f"its format is {metadata[FORMAT_KEY]!r}, not {TABLE_FORMAT!r}" ) return _read_record(metadata) -def read_store_table_record_of_any_format( +def read_table_record_of_any_format( metadata: Mapping[str, bytes], -) -> tuple[StoreTableRecord, str] | None: - """Return a table's record and the store format it names, whatever the format. +) -> tuple[TableRecord, str] | None: + """Return a table's record and the table format it names, whatever the format. - For a listing only: it places a table of another store format by its recorded + For a listing only: it places a table of another table format by its recorded path, so the listing can report it without reading it. Every check - ``read_store_table_metadata`` makes is made, except that the format must be this - store's; a table is never opened through what this returns. + ``read_table_identity_metadata`` makes is made, except that the format must be this + database's; a table is never opened through what this returns. Args: metadata: The table's metadata, as SpiralDB returns it. @@ -200,88 +216,81 @@ def read_store_table_record_of_any_format( entries. Raises: - SpiralStoreTableCollisionError: If the record is partial or unreadable (its + SpiralTableCollisionError: If the record is partial or unreadable (its format included, or empty). """ + metadata = _with_format_entry(metadata) if not any(k in metadata for k in _RECORD_KEYS): return None _require_complete(metadata) try: - store_format = metadata[STORE_KEY].decode() + table_format = metadata[FORMAT_KEY].decode() except UnicodeDecodeError as exc: - raise SpiralStoreTableCollisionError( - f"its record cannot be read: {exc}" - ) from exc - if not store_format: - raise SpiralStoreTableCollisionError("its record names no store format") - return _read_record(metadata), store_format + raise SpiralTableCollisionError(f"its record cannot be read: {exc}") from exc + if not table_format: + raise SpiralTableCollisionError("its record names no table format") + return _read_record(metadata), table_format def _require_complete(metadata: Mapping[str, bytes]) -> None: """Refuse a record that lacks one of its entries.""" missing = [k for k in _RECORD_KEYS if k not in metadata] if missing: - raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + raise SpiralTableCollisionError(f"its record lacks {missing}") -def _read_record(metadata: Mapping[str, bytes]) -> StoreTableRecord: +def _read_record(metadata: Mapping[str, bytes]) -> TableRecord: """The record of complete metadata, its format aside. Raises: - SpiralStoreTableCollisionError: If the record cannot be read, or its path, - layout or data context is not one a store table records. + SpiralTableCollisionError: If the record cannot be read, or its path, + layout or data context is not one a database table records. """ 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 + raise SpiralTableCollisionError(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}" - ) + raise SpiralTableCollisionError(f"its path is not a list of names: {path!r}") components = tuple(cast("list[str]", items)) try: # What a writer refuses, a reader refuses. _ = require_store_path_domain(components) except ValueError as exc: - raise SpiralStoreTableCollisionError( - f"its path cannot be named: {exc}" - ) from exc + raise SpiralTableCollisionError(f"its path cannot be named: {exc}") from exc if layout != components[-1]: - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( 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) + raise SpiralTableCollisionError("it records no data context") + return TableRecord(components, layout, data_context_key) OTHER_FORMAT_SEPARATOR = "/" -"""Joins a recorded layout and a store format in the last component a listing gives a -table of another store format. No store path component holds it +"""Joins a recorded layout and a table format in the last component a listing gives a +table of another table format. No database table path component holds it (``require_store_path_domain``), so that component never names a layout or a path.""" -def other_format_last_component(record: StoreTableRecord, store_format: str) -> str: - """The last component a listing gives a table of another store format. +def other_format_last_component(record: TableRecord, table_format: str) -> str: + """The last component a listing gives a table of another table format. Args: record: The table's record. - store_format: The store format the record names. + table_format: The table format the record names. Returns: ``"/"``. """ - return f"{record.layout}{OTHER_FORMAT_SEPARATOR}{store_format}" + return f"{record.layout}{OTHER_FORMAT_SEPARATOR}{table_format}" def refuse_other_format_path(path: Sequence[str]) -> None: - """Refuse a path a listing gives a table of another store format. + """Refuse a path a listing gives a table of another table format. Args: path: A record path to open. @@ -292,26 +301,26 @@ def refuse_other_format_path(path: Sequence[str]) -> None: """ if not path or not isinstance(path[-1], str): return - layout, separator, store_format = path[-1].partition(OTHER_FORMAT_SEPARATOR) - if separator and layout and store_format: + layout, separator, table_format = path[-1].partition(OTHER_FORMAT_SEPARATOR) + if separator and layout and table_format: raise ValueError( - f"{list(path)} is how list_table_paths shows a table of another store " - f"format ({store_format!r}): it is not this store's table and cannot be " + f"{list(path)} is how list_table_paths shows a table of another table " + f"format ({table_format!r}): it is not this database's table and cannot be " "opened" ) -def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> None: - """Refuse a store table whose record is of another path than ``path``. +def require_table_path(record: TableRecord, path: Sequence[str]) -> None: + """Refuse a database table whose record is of another path than ``path``. Args: - record: The table's record (``read_store_table_metadata``). + record: The table's record (``read_table_identity_metadata``). path: The full path the table was looked up for. Raises: - SpiralStoreTableCollisionError: If the record is of another path. + SpiralTableCollisionError: If the record is of another path. """ if record.path != tuple(path): - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( f"it records path {list(record.path)}, not {list(path)}" ) diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 89a64f106..8fc964488 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,8 +49,8 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path -from orcapod.databases.spiraldb_store_registry import register_store_connector -from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.databases.spiraldb_writable_registry import register_writable_connector +from orcapod.databases.spiraldb_tables import SpiralDBTables from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, @@ -523,6 +523,14 @@ def _http_get_json(url: str, token: str | None) -> dict[str, Any]: return json.load(response) +STORE_KEY_REFUSAL = ( + "a SpiralDB connector configuration with a 'store' key is not read: the writable " + "SpiralDB database is SpiralDBConnector(..., writable=True), saved as " + "'writable': true" +) +"""The refusal of a saved SpiralDB connector configuration that names ``store``.""" + + def _service_address(client: Any) -> str: """Return the service address a spiral-sdk client resolved, without a final ``/``. @@ -1002,13 +1010,13 @@ 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 job's pipeline store (ITL-1844), for - ``ConnectorArrowDatabase``: tables named from their paths, rows through the - store codec, one writer at a time (a job run takes the dataset's writer - lease, and a second writer is refused). Its tables are read and written only - through ``ConnectorArrowDatabase``, and only a job run writes them. - Provisional in 0.4.0: the store's table format and its lease may change in - a later version, which may not read tables written now. + writable: Open the dataset as a writable SpiralDB database, a job's database + (ITL-1844), for ``ConnectorArrowDatabase``: tables named from their paths, + rows through the database codec, one writer at a time (a job run takes the + dataset's writer lease, and a second writer is refused). Its tables are read + and written only through ``ConnectorArrowDatabase``, and only a job run + writes them. Provisional in 0.4.0: the table format and the lease may change + in a later version, which may not read tables written now. """ def __init__( @@ -1017,10 +1025,10 @@ def __init__( dataset: str = "default", overrides: dict[str, str] | None = None, *, - store: bool = False, + writable: bool = False, ) -> None: - if not isinstance(store, bool): # pyright: ignore[reportUnnecessaryIsInstance] # a saved or user value - raise TypeError(f"store must be True or False, got {store!r}") + if not isinstance(writable, bool): # pyright: ignore[reportUnnecessaryIsInstance] # a saved or user value + raise TypeError(f"writable must be True or False, got {writable!r}") self._project_id = project_id self._dataset = dataset # A copy: a later change to the caller's mapping must not change the service @@ -1046,24 +1054,24 @@ def __init__( lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), _kept_rows_for(_api_url(overrides), project_id, dataset), ) - # Kept after ``close`` releases the store's tables, so a closed store connector - # never acts as a plain one. - self._store_mode = store - self._store: StoreTables | None = None - if store: - # A run looks for store leases only while a store connector exists. - register_store_connector(self) - self._store = self._new_store_tables() - - def _new_store_tables(self) -> StoreTables: - """The store's tables of this connector's dataset, over its SDK client. - - Each store connector has its own, so the writer lease a run attaches to one + # Kept after ``close`` releases the tables, so a closed writable connector never + # acts as a plain one. + self._writable = writable + self._tables: SpiralDBTables | None = None + if writable: + # A run looks for writer leases only while a writable connector exists. + register_writable_connector(self) + self._tables = self._new_tables() + + def _new_tables(self) -> SpiralDBTables: + """The database tables of this connector's dataset, over its SDK client. + + Each writable connector has its own, so the writer lease a run attaches to one connector's tables never lets another connector write (``share_client`` too). """ client, health = self._client, self._health project_id, dataset = self._project_id, self._dataset - return StoreTables( + return SpiralDBTables( sp, project_id, dataset, @@ -1082,18 +1090,18 @@ def _require_open(self) -> None: raise RuntimeError("SpiralDBConnector is closed") require_same_process(self._pid) - def _store_tables(self) -> StoreTables | None: - """The store's tables, or ``None`` on a plain connector. + def _writable_tables(self) -> SpiralDBTables | None: + """The database tables, or ``None`` on a plain connector. - For ``ConnectorArrowDatabase``, the only reader and writer of a store's tables. + For ``ConnectorArrowDatabase``, the only reader and writer of these tables. Raises: - RuntimeError: If this is a store-mode connector and it has been closed. + RuntimeError: If this is a writable connector and it has been closed. """ - if not self._store_mode: + if not self._writable: return None self._require_open() - return self._store + return self._tables def _writer_lease_key(self) -> tuple[str, str, str]: """The dataset a writer lease is taken for: service address, project, dataset. @@ -1117,27 +1125,27 @@ def _writer_lease_target(self) -> tuple[Any, str, str]: self._require_open() return (self._client, self._project_id, self._dataset) - def _refuse_in_store_mode(self) -> None: - """Refuse an operation on raw tables of a store-mode connector.""" - if self._store_mode: + def _refuse_if_writable(self) -> None: + """Refuse an operation on raw tables of a writable connector.""" + if self._writable: raise ValueError( - "a store-mode SpiralDB connector reads and writes its tables through " + "a writable SpiralDB connector reads and writes its tables through " "ConnectorArrowDatabase only, never as raw tables" ) def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope. - A store connector's copy is a store connector too, registered as one, so a - run on it takes the dataset's writer lease also after the original is gone. It - has its own store tables: a run's lease held through one of the two never lets + A writable connector's copy is writable too, registered as one, so a run on it + takes the dataset's writer lease also after the original is gone. It has its own + tables: a run's lease held through one of the two never lets the other write. """ self._require_open() shared = copy(self) - if self._store_mode: - shared._store = shared._new_store_tables() # pyright: ignore[reportPrivateUsage] # a copy of this class - register_store_connector(shared) + if self._writable: + shared._tables = shared._new_tables() # pyright: ignore[reportPrivateUsage] # a copy of this class + register_writable_connector(shared) return shared def _qualified(self, table_name: str) -> str: @@ -1171,7 +1179,7 @@ def get_table_names(self) -> list[str]: Sorted list of plain table name strings (no ``dataset.`` prefix). """ self._require_open() - self._refuse_in_store_mode() + self._refuse_if_writable() with self._service_call("list the tables of", "*"): listed = _list_keyed_tables(self._client, self._project_id, self._dataset) with _about_table(f"{self._project_id}/{self._dataset}"): @@ -1203,10 +1211,10 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. ValueError: If the table is an internal schema or lease table, or this - connector is in store mode. + connector is writable. """ self._require_open() - self._refuse_in_store_mode() + self._refuse_if_writable() self._require_user_table(table_name) missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}" if ( @@ -1345,7 +1353,7 @@ def iter_batches( non-nullable column (naming the table and the column). """ self._require_open() - self._refuse_in_store_mode() + self._refuse_if_writable() if params is not None: logger.warning( "SpiralDBConnector does not support query parameters; " @@ -1558,9 +1566,9 @@ def close(self) -> None: del self._client del self._shared del self._schemas - # The store's tables hold the client too; a connector from + # The database tables hold the client too; a connector from # ``share_client`` has its own. - self._store = None + self._tables = None def __enter__(self) -> SpiralDBConnector: return self @@ -1576,7 +1584,7 @@ def to_config(self) -> dict[str, Any]: Returns: Dict with ``connector_type``, ``project_id``, ``dataset``, and - ``overrides`` keys, and ``store: True`` for a store connector. + ``overrides`` keys, and ``writable: True`` for a writable connector. Raises: RuntimeError: If this connector has been closed. @@ -1588,8 +1596,8 @@ def to_config(self) -> dict[str, Any]: "dataset": self._dataset, "overrides": None if self._overrides is None else dict(self._overrides), } - if self._store_mode: - config["store"] = True + if self._writable: + config["writable"] = True return config @classmethod @@ -1598,22 +1606,25 @@ def from_config(cls, config: dict[str, Any]) -> SpiralDBConnector: Args: config: Dict with ``connector_type``, ``project_id``, and optionally - ``dataset``, ``overrides`` and ``store`` keys. + ``dataset``, ``overrides`` and ``writable`` keys. Returns: A new, open SpiralDBConnector instance. Raises: - ValueError: If ``connector_type`` is not ``"spiraldb"``. + ValueError: If ``connector_type`` is not ``"spiraldb"``, or the config holds + a ``store`` key (not an option: ``writable``). """ if config.get("connector_type") != "spiraldb": raise ValueError( f"Expected connector_type 'spiraldb', " f"got {config.get('connector_type')!r}" ) + if "store" in config: + raise ValueError(STORE_KEY_REFUSAL) return cls( project_id=config["project_id"], dataset=config.get("dataset", "default"), overrides=config.get("overrides"), - store=config.get("store", False), + writable=config.get("writable", False), ) diff --git a/src/orcapod/databases/spiraldb_lease.py b/src/orcapod/databases/spiraldb_lease.py index 376682a86..9f708a216 100644 --- a/src/orcapod/databases/spiraldb_lease.py +++ b/src/orcapod/databases/spiraldb_lease.py @@ -1,4 +1,4 @@ -"""Internal one-writer leases for SpiralDB stores. +"""Internal one-writer leases for writable SpiralDB databases. Generation discovery requires a contiguous sequence. Deleting a generation table by hand can admit a second holder while a newer generation is still @@ -323,7 +323,7 @@ def acquire( owner: str, on_claim: Callable[[Lease], None] | None = None, ) -> Lease: - """Claim a dataset for one writer or raise before any store data can be written. + """Claim a dataset for one writer or raise before any database data can be written. Args: client: SDK client used for the lease. @@ -381,7 +381,7 @@ def acquire( except BaseException as exc: if claimed is None: raise - # The claim token was verified and no store writes could start. The release + # The claim token was verified and no database writes could start. The release # row can be written even if reading the current lease state failed. try: _write_release(client, claimed, key) diff --git a/src/orcapod/databases/spiraldb_store_registry.py b/src/orcapod/databases/spiraldb_store_registry.py deleted file mode 100644 index b3f3e0251..000000000 --- a/src/orcapod/databases/spiraldb_store_registry.py +++ /dev/null @@ -1,32 +0,0 @@ -"""Which SpiralDB store connectors exist in this process (ITL-1844). - -A run takes the writer lease of every SpiralDB store it may write -(``spiraldb_write_scope.store_writes``), found by walking the run's graph. A store -database always holds its store connector, so when no store connector exists in the -process no run can write a store, and the run skips the walk (``any_store_connector``). -This module is a leaf: checking it imports nothing of SpiralDB. -""" - -from __future__ import annotations - -from weakref import WeakSet - -_store_connectors: WeakSet[object] = WeakSet() - - -def register_store_connector(connector: object) -> None: - """Record a store connector, for as long as it exists. - - Args: - connector: A ``SpiralDBConnector`` made with ``store=True``. - """ - _store_connectors.add(connector) - - -def any_store_connector() -> bool: - """Whether any SpiralDB store connector exists in this process (closed ones too). - - Returns: - ``False`` only when no run can hold a SpiralDB store database. - """ - return len(_store_connectors) > 0 diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_tables.py similarity index 85% rename from src/orcapod/databases/spiraldb_store_tables.py rename to src/orcapod/databases/spiraldb_tables.py index ae206b646..8987861d2 100644 --- a/src/orcapod/databases/spiraldb_store_tables.py +++ b/src/orcapod/databases/spiraldb_tables.py @@ -1,17 +1,18 @@ -"""The tables of a SpiralDB pipeline store, one dataset's (ITL-1840). +"""The tables of a writable SpiralDB database, one dataset's (ITL-1840). -What ``ConnectorArrowDatabase`` does with the tables of a SpiralDB store, -``SpiralDBConnector(..., store=True)`` (public and provisional in 0.4.0, ITL-1844). The -design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried -from PR 595 onto ``main``'s database structure. +What ``ConnectorArrowDatabase`` does with the tables of a writable SpiralDB database, +``SpiralDBConnector(..., writable=True)`` (public and provisional in 0.4.0, ITL-1844). +The design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, +carried from PR 595 onto ``main``'s database structure. -- A table's name is computed from its full record path (``spiral_store_identity``); a +- A table's name is computed from its full record path (``spiral_database_identity``); a table is found by opening that name, never by listing. -- Its metadata holds its identity record and its manifest (``spiral_store``): the record +- Its metadata holds its identity record and its manifest (``spiral_database_codec``): +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 rows (a + record, is refused (``SpiralTableCollisionError``). A table with no rows (a creation that stopped before its first rows) is new to any first writer. - Rows are encoded on write and decoded on read by the codec; a read gives the logical columns, logical types live. @@ -21,14 +22,15 @@ - A table's name is opened on every call (a table can be renamed and another made under its name); what a table holding rows records is kept by its table id, and only once an append to it succeeded or a read found its rows. -- The store's tables are listed by one listing of the dataset, narrowed by name, and the +- The database'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). One writer at a time (ITL-1844): every write needs the dataset's writer lease (``spiraldb_lease``), handed in by the run that holds it (``spiraldb_write_scope``) and checked before each write; a write with none is refused -(``SpiralDBStoreLeaseRequiredError``) before anything is created or written. A first write +(``SpiralDBLeaseRequiredError``) before anything is created or written. A first write still re-reads the table just before recording it and never overwrites what that read shows. """ @@ -44,11 +46,11 @@ import pyarrow as pa import pyarrow.compute as pc -import orcapod.databases.spiral_store as codec -import orcapod.databases.spiral_store_identity as identity -from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +import orcapod.databases.spiral_database_codec as codec +import orcapod.databases.spiral_database_identity as identity +from orcapod.databases.spiral_database_identity import SpiralTableCollisionError from orcapod.databases.store_table_names import require_store_path_domain -from orcapod.errors import InputValidationError, SpiralDBStoreLeaseRequiredError +from orcapod.errors import InputValidationError, SpiralDBLeaseRequiredError from orcapod.logical_types.canonical_form import ( EXTENSION_METADATA_KEY, EXTENSION_NAME_KEY, @@ -64,7 +66,7 @@ class _Scan(Protocol): - """The part of spiral-sdk's scan the store uses.""" + """The part of spiral-sdk's scan the database uses.""" def to_table(self) -> pa.Table: """The rows the scan reads, as one Arrow table.""" @@ -72,7 +74,7 @@ def to_table(self) -> pa.Table: class _KeyedTable(Protocol): - """The part of spiral-sdk's ``KeyedTable`` the store uses.""" + """The part of spiral-sdk's ``KeyedTable`` the database uses.""" @property def resource_id(self) -> str: ... @@ -103,13 +105,13 @@ def scan( def append(self, data: pa.Table) -> _KeyedTable: """Write rows; a row whose key the table holds replaces that row. The returned - table is not used: the store opens the table by name again.""" + table is not used: the database opens the table by name again.""" ... @dataclass(frozen=True) class _Found: - """A store table that holds rows, with what its metadata records. + """A database table that holds rows, with what its metadata records. Attributes: table_id: SpiralDB's id of the table. @@ -118,13 +120,13 @@ class _Found: """ table_id: str - record: identity.StoreTableRecord - manifest: codec.StoreManifest + record: identity.TableRecord + manifest: codec.TableManifest @dataclass(frozen=True) class _Opened: - """A store table found under its name now: what it records, and the snapshot it + """A database table found under its name now: what it records, and the snapshot it was opened as (every read and write of the call goes through that snapshot). Attributes: @@ -144,7 +146,7 @@ class _Opened: @dataclass(frozen=True) class _New: - """A store table found under its name with no rows yet: new to any first writer. + """A database table found under its name with no rows yet: new to any first writer. Attributes: seen: What it recorded when it was judged (``_seen_manifest``): its first write @@ -154,15 +156,15 @@ class _New: """ seen: _Seen - record: identity.StoreTableRecord | None + record: identity.TableRecord | None _Judgment = _Opened | _New | None """What a name was judged: a table with rows, a table with none, or no table.""" -class StoreTables: - """The store tables of one SpiralDB dataset. +class SpiralDBTables: + """The database tables of one SpiralDB dataset. Every keyed table is opened or created through the connector's callables, never through the SDK client here: the connector owns every call that opens a keyed table @@ -203,9 +205,9 @@ def __init__( # manifest never change once it holds rows. Which table a name opens is asked # on every call (a table can be renamed, and another made under its name). self._found_by_id: dict[str, _Found] = {} - # The record of a listed table that holds rows and the store format it names, + # The record of a listed table that holds rows and the table format it names, # by its id (a table that holds rows never loses them). - self._records_by_id: dict[str, tuple[identity.StoreTableRecord, str]] = {} + self._records_by_id: dict[str, tuple[identity.TableRecord, str]] = {} # Within one public operation (``operation``): what each name was judged, its # name opened once and its handle reused. Empty outside an operation. # Kept per thread: an operation is one thread's call, and no other operation @@ -217,7 +219,7 @@ def __init__( self._lease_check: Callable[[], None] | None = None key_column: str = codec.KEY_COLUMN - """The key column of every store table.""" + """The key column of every database table.""" def unstorable_column_reason( self, name: str, arrow_type: pa.DataType, primary_key: bool @@ -235,7 +237,7 @@ def unstorable_column_reason( 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" + return f"a database 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])) @@ -275,8 +277,8 @@ def validate(self, records: pa.Table, table_name: str | None) -> None: InputValidationError: If the data context is not one this Orcapod has, or not the table's. UnstorableInSpiralError: If the codec refuses the rows. - SpiralStoreTableCollisionError: If the table under the name is not this - path's store table. + SpiralTableCollisionError: If the table under the name is not this + path's database table. """ if records.num_rows == 0: return @@ -300,13 +302,14 @@ def table_name(self, path: tuple[str, ...]) -> str: Raises: ValueError: If the path is how ``table_paths`` lists a table of another - store format (``identity.refuse_other_format_path``), or is outside the - store path domain (``store_table_names.require_store_path_domain``), - which the table's identity record and manifest apply too. + table format (``identity.refuse_other_format_path``), or is outside the + database table path domain + (``store_table_names.require_store_path_domain``), which the table's + identity record and manifest apply too. """ identity.refuse_other_format_path(path) components = require_store_path_domain(path) - name = identity.spiral_store_table_name(components) + name = identity.spiral_table_name(components) self._paths[name] = components return name @@ -315,7 +318,7 @@ def _path_of(self, table_name: str) -> tuple[str, ...]: 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" + f"{table_name!r} is not a name this database computed for a path" ) return path @@ -329,14 +332,16 @@ def _about(self, table_name: str) -> Iterator[None]: """ try: yield - except SpiralStoreTableCollisionError as exc: + except SpiralTableCollisionError as exc: if exc.table is not None: raise - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( exc.reason, table=self._qualified(table_name) ) from exc except Exception as exc: - exc.add_note(f"SpiralDB store table {self._qualified(table_name)}") + exc.add_note( + f"writable SpiralDB database table {self._qualified(table_name)}" + ) raise # ── operations ─────────────────────────────────────────────────────────── @@ -348,7 +353,7 @@ def operation(self) -> Iterator[None]: reads; a write always opens its name afresh. Operations nest; the handles are forgotten when the outermost ends, so the next operation opens each name again (a table can be renamed, and another made under its name, between them). Code - the store does not control runs ``outside_operation``. + the database does not control runs ``outside_operation``. """ depth = cast(int, getattr(self._now, "depth", 0)) if depth == 0: @@ -363,7 +368,7 @@ def operation(self) -> Iterator[None]: @contextmanager def outside_operation(self) -> Iterator[None]: - """Run code this store does not control (a caller's callback) outside the + """Run code this database does not control (a caller's callback) outside the current operation: a public call it makes opens every name afresh in an operation of its own, and the enclosing operation forgets every handle it held once the code returns, since that code may have renamed or replaced a table. @@ -383,7 +388,9 @@ def _judged_now(self) -> dict[str, _Judgment] | None: return cast("dict[str, _Judgment] | None", getattr(self._now, "judged", None)) def _forget_opened(self, table_name: str) -> None: - """Forget a name's handle in the current operation: this store writes to it.""" + """Forget a name's handle in the current operation: this database writes to + it. + """ judged = self._judged_now() if judged is not None: _ = judged.pop(table_name, None) @@ -420,7 +427,7 @@ def _judgment(self, table_name: str) -> _Judgment: The judgment. Raises: - SpiralStoreTableCollisionError: If the table's key is not the store's, it + SpiralTableCollisionError: If the table's key is not the database's, it records another path or format, or it holds rows without a manifest. """ judged = self._judged_now() @@ -449,26 +456,26 @@ def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: if known is not None and known.record.path == path: return _Opened(known, table) _require_key(table, self._service_call) - with self._service_call("read the metadata of a store table"): + with self._service_call("read the metadata of a database table"): metadata = table.get_metadata() - record = identity.read_store_table_metadata(metadata) + record = identity.read_table_identity_metadata(metadata) if record is not None: - identity.require_store_table_path(record, path) + identity.require_table_path(record, path) if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]): # New: its first write records it, unless what it saw here changed. return _New(_seen_manifest(metadata, path), record) try: manifest = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: - raise SpiralStoreTableCollisionError(str(exc)) from exc + raise SpiralTableCollisionError(str(exc)) from exc if record is None or manifest is None: - raise SpiralStoreTableCollisionError("it holds rows but no store manifest") + raise SpiralTableCollisionError("it holds rows but no table manifest") found = _Found(str(table.resource_id), record, manifest) self._found_by_id[found.table_id] = found return _Opened(found, table) def has_table(self, table_name: str) -> bool: - """Whether the store table at a computed name holds rows (and a manifest). + """Whether the database table at a computed name holds rows (and a manifest). Args: table_name: A name ``table_name`` returned. @@ -484,7 +491,7 @@ def _qualified(self, table_name: str) -> str: 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 + """Return the full paths of the database tables under ``prefix``, and of the pending ones. One listing of the dataset; the names that start as a table under ``prefix`` @@ -494,13 +501,13 @@ def table_paths( stopped after recording the table and before its rows leaves one); a pending path is listed all the same. - A table whose complete, readable record names another store format, with its + A table whose complete, readable record names another table format, with its recorded path under ``prefix``, is listed as its recorded path with the last component ``"/"`` - (``identity.other_format_last_component``): no layout and no store path has that - component, so the table is reported as one of another layout, and opening that - path is refused (``table_name``). Its name is not checked: another format may - name its tables otherwise. + (``identity.other_format_last_component``): no layout and no database table path + has that component, so the table is reported as one of another layout, and + opening that path is refused (``table_name``). Its name is not checked: another + format may name its tables otherwise. Args: prefix: The full path prefix. @@ -509,9 +516,9 @@ def table_paths( Returns: The paths, sorted. """ - start = identity.spiral_store_table_name_prefix(prefix) + start = identity.spiral_table_name_prefix(prefix) found = {p for p in pending if p[: len(prefix)] == prefix} - with self._service_call("list the store tables"): + with self._service_call("list the database tables"): listed = self._list_tables() for table_id, table_name in listed.items(): if not table_name.startswith(start): @@ -520,24 +527,24 @@ def table_paths( read = self._record_of(table_id, table_name) if read is None: continue - record, store_format = read + record, table_format = read if record.path[: len(prefix)] != prefix: continue - if store_format == identity.STORE_FORMAT: + if table_format == identity.TABLE_FORMAT: found.add(record.path) else: - last = identity.other_format_last_component(record, store_format) + last = identity.other_format_last_component(record, table_format) found.add((*record.path[:-1], last)) return sorted(found) def _record_of( self, table_id: str, table_name: str - ) -> tuple[identity.StoreTableRecord, str] | None: - """The record of a listed table and the store format it names, read once per + ) -> tuple[identity.TableRecord, str] | None: + """The record of a listed table and the table format it names, read once per id; ``None`` without one, or when the table holds no rows. - For this store's format, the name it is listed under now is checked against its - record on every call, the cached one included: a table renamed keeps its id. + For this database's format, the name it is listed under now is checked against + its record on every call, the cached one included: a table renamed keeps its id. Whether it holds rows is asked until it does. Args: @@ -548,23 +555,23 @@ def _record_of( table: _KeyedTable | None = None if read is None: table = self._open_table_by_id(table_id) - with self._service_call("read the metadata of a store table"): + with self._service_call("read the metadata of a database table"): metadata = table.get_metadata() - read = identity.read_store_table_record_of_any_format(metadata) + read = identity.read_table_record_of_any_format(metadata) if read is None: return None # never kept: its record may be written later - record, store_format = read + record, table_format = read if ( - store_format == identity.STORE_FORMAT - and identity.spiral_store_table_name(record.path) != table_name + table_format == identity.TABLE_FORMAT + and identity.spiral_table_name(record.path) != table_name ): - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( f"it records path {list(record.path)}, whose table has another name" ) if table is not None: # Another format's key column is its own: one row of every column. columns = ( - [codec.KEY_COLUMN] if store_format == identity.STORE_FORMAT else None + [codec.KEY_COLUMN] if table_format == identity.TABLE_FORMAT else None ) if not _holds_rows(table, self._service_call, columns): return None # never kept: its rows may be written later @@ -584,7 +591,7 @@ def _require(self, table_name: str) -> _Found: """ opened = self._judge(table_name) if opened is None: - raise KeyError(f"no store table {self._qualified(table_name)}") + raise KeyError(f"no database table {self._qualified(table_name)}") return opened.found def recorded_schema(self, table_name: str) -> pa.Schema: @@ -634,12 +641,12 @@ def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: """ opened = self._judgment(table_name) if opened is None: - raise KeyError(f"no store table {self._qualified(table_name)}") + raise KeyError(f"no database table {self._qualified(table_name)}") if isinstance(opened, _New): return # it exists, with no rows found = opened.found schema = _live(found.manifest.schema, found.record.data_context_key) - with self._about(table_name), self._service_call("read a store table"): + with self._about(table_name), self._service_call("read a database table"): stored = opened.table.scan().to_table() if stored.num_rows == 0: return @@ -683,7 +690,7 @@ def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: Returns: The ids it holds. """ - with self._service_call("read the keys of a store table"): + with self._service_call("read the keys of a database table"): stored = table.scan([codec.KEY_COLUMN]).to_table() held = cast( "list[bytes]", @@ -703,7 +710,9 @@ def hold_lease(self, check: Callable[[], None]) -> None: RuntimeError: If a lease is held for these tables already. """ if self._lease_check is not None: - raise RuntimeError("these store tables are already written under a lease") + raise RuntimeError( + "these database tables are already written under a lease" + ) self._lease_check = check def let_go_of_lease(self, check: Callable[[], None]) -> None: @@ -718,21 +727,21 @@ def let_go_of_lease(self, check: Callable[[], None]) -> None: def _require_lease(self) -> None: """Refuse a write unless a run holds the dataset's writer lease, and check it. - The lease is held by the store connectors of the run that took it: a write + The lease is held by the writable connectors of the run that took it: a write through any other connector to the dataset is refused, also while that run holds the lease. A write through the run's own connectors is the run's (its databases, its cached sources); the lease does not tell its callers apart. Raises: - SpiralDBStoreLeaseRequiredError: If no run holds the lease. + SpiralDBLeaseRequiredError: If no run holds the lease. LeaseError: If the lease is no longer held (``spiraldb_lease.check``). """ check = self._lease_check if check is None: - raise SpiralDBStoreLeaseRequiredError( - f"this SpiralDB store connector holds no writer lease of dataset " - f"{self._project_id}/{self._dataset}: a SpiralDB store is written only " - "through the connectors of a job run (job.run(), job.run_async() or a " + raise SpiralDBLeaseRequiredError( + f"this writable SpiralDB connector holds no writer lease of dataset " + f"{self._project_id}/{self._dataset}: a writable SpiralDB database is " + "written only through the connectors of a job run (job.run(), job.run_async() or a " "job node's run()), which takes the lease; nothing was written" ) check() @@ -762,7 +771,7 @@ def _create_or_open(self, table_name: str) -> _KeyedTable: # Made meanwhile: the caller compares it with what it judged. table = self._open_table(table_name) if table is None: - raise KeyError(f"no store table {self._qualified(table_name)}") + raise KeyError(f"no database table {self._qualified(table_name)}") return table def _unchanged_since_judged( @@ -770,7 +779,7 @@ def _unchanged_since_judged( table: _KeyedTable, path: tuple[str, ...], seen: _Seen, - seen_record: identity.StoreTableRecord | None, + seen_record: identity.TableRecord | None, ) -> bool: """Whether a table opened to be recorded is still as it was judged new: the same identity record (or none), an equivalent manifest (or none; compared by name, @@ -792,15 +801,15 @@ def _unchanged_since_judged( Whether it is unchanged. Raises: - SpiralStoreTableCollisionError: If the table's identity record, read with + SpiralTableCollisionError: If the table's identity record, read with the manifest, is of another path or cannot be read: an identity is never recorded over. """ - with self._service_call("read the metadata of a store table"): + with self._service_call("read the metadata of a database table"): metadata = table.get_metadata() - record = identity.read_store_table_metadata(metadata) + record = identity.read_table_identity_metadata(metadata) if record is not None: - identity.require_store_table_path(record, path) + identity.require_table_path(record, path) now = _seen_manifest(metadata, path) return ( record == seen_record @@ -809,7 +818,7 @@ def _unchanged_since_judged( ) def _require_same_manifest( - self, table: _KeyedTable, path: tuple[str, ...], manifest: codec.StoreManifest + self, table: _KeyedTable, path: tuple[str, ...], manifest: codec.TableManifest ) -> _Found: """Refuse a table another writer recorded since it was judged, unless it records the same manifest: another writer's record is never overwritten. @@ -824,20 +833,20 @@ def _require_same_manifest( writer's equivalent ones. Raises: - SpiralStoreTableCollisionError: If it records another path or manifest, or + SpiralTableCollisionError: If it records another path or manifest, or holds rows without one. """ - with self._service_call("read the metadata of a store table"): + with self._service_call("read the metadata of a database table"): metadata = table.get_metadata() - record = identity.read_store_table_metadata(metadata) + record = identity.read_table_identity_metadata(metadata) if record is not None: - identity.require_store_table_path(record, path) + identity.require_table_path(record, path) try: current = None if record is None else codec.read_manifest(metadata, path) except codec.ManifestError as exc: - raise SpiralStoreTableCollisionError(str(exc)) from exc + raise SpiralTableCollisionError(str(exc)) from exc if record is None or current is None or not _same_manifest(current, manifest): - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( "another writer recorded it since it was judged, with another manifest" ) return _Found(str(table.resource_id), record, current) @@ -867,9 +876,9 @@ def write(self, table_name: str, records: pa.Table) -> None: UnstorableInSpiralError: If the codec refuses the rows. InputValidationError: If their data context is not one this Orcapod has, or not the one the table records (checked when they are buffered too). - SpiralStoreTableCollisionError: If the table under the name is not this - path's store table. - SpiralDBStoreLeaseRequiredError: If no job run holds the dataset's writer + SpiralTableCollisionError: If the table under the name is not this + path's database table. + SpiralDBLeaseRequiredError: If no job run holds the dataset's writer lease; nothing is written. LeaseError: If the lease the run took is no longer held. """ @@ -927,7 +936,7 @@ def _write_first( context: str, records: pa.Table, seen: _Seen, - seen_record: identity.StoreTableRecord | None, + seen_record: identity.TableRecord | None, ) -> None: """The first write of a table judged absent or new (``write``). @@ -943,7 +952,7 @@ def _write_first( """ manifest = codec.new_manifest(path, path[-1], records.schema) metadata = { - **identity.store_table_metadata(path, context), + **identity.table_identity_metadata(path, context), **codec.manifest_entries(manifest), } encoded = _encoded(records) @@ -953,11 +962,11 @@ def _write_first( table = self._create_or_open(table_name) _require_key(table, self._service_call) if self._unchanged_since_judged(table, path, seen, seen_record): - with self._service_call("record a store table"): + with self._service_call("record a database table"): table.set_metadata(metadata) recorded = _Found( str(table.resource_id), - identity.StoreTableRecord(path, path[-1], context), + identity.TableRecord(path, path[-1], context), manifest, ) else: @@ -978,7 +987,7 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: encoded: The rows, encoded. """ try: - with self._service_call("write a store table"): + with self._service_call("write a database table"): _ = table.append(encoded) except BaseException: # The service may hold the rows, some, or none: judged again next call. @@ -988,7 +997,7 @@ def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: def _stored_names_difference( - manifest: codec.StoreManifest, schema: pa.Schema + manifest: codec.TableManifest, schema: pa.Schema ) -> str | None: """Where the stored names ``codec.encode_rows`` gives rows of ``schema`` differ from those ``manifest`` records, at any depth; ``None`` when they are the same. @@ -1024,28 +1033,28 @@ def _names_of(field: pa.Field[Any]) -> tuple[object, ...]: def _require_key( table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] ) -> None: - """Refuse a table whose key is not the store's: ``__record_id``, binary. + """Refuse a table whose key is not the database's: ``__record_id``, binary. Args: table: The table. - service_call: The store's ``service_call``. + service_call: The database's ``service_call``. Raises: - SpiralStoreTableCollisionError: If its key is another. + SpiralTableCollisionError: If its key is another. """ key_type = None if tuple(table.key_columns) == (codec.KEY_COLUMN,): - with service_call("read the schema of a store table"): + with service_call("read the schema of a database table"): key_type = table.schema().field(codec.KEY_COLUMN).type if key_type is not None and ( pa.types.is_binary(key_type) or pa.types.is_large_binary(key_type) ): return if tuple(table.key_columns) == (codec.KEY_COLUMN,): - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( f"its key {codec.KEY_COLUMN!r} is {key_type}, not binary" ) - raise SpiralStoreTableCollisionError( + raise SpiralTableCollisionError( f"its key columns are {list(table.key_columns)}, not [{codec.KEY_COLUMN!r}]" ) @@ -1059,10 +1068,10 @@ def _holds_rows( Args: table: The table. - service_call: The store's ``service_call``. + service_call: The database's ``service_call``. columns: The columns of the one row read (``None`` for all of them). """ - with service_call("read a key of a store table"): + with service_call("read a key of a database table"): keys = table.scan(columns, limit=1).to_table() return keys.num_rows > 0 @@ -1116,7 +1125,8 @@ def _one_data_context(records: pa.Table) -> str: """ 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" + "a writable SpiralDB database keeps rows with a " + f"{DATA_CONTEXT_COLUMN!r} column only" ) values = cast( "list[object]", pc.unique(records.column(DATA_CONTEXT_COLUMN)).to_pylist() @@ -1128,7 +1138,8 @@ def _one_data_context(records: pa.Table) -> str: ) if len(values) != 1 or not isinstance(values[0], str): raise ValueError( - f"rows of one write to a SpiralDB store hold one data context, not {values}" + "rows of one write to a writable SpiralDB database hold one data context, " + f"not {values}" ) key = values[0] from orcapod.contexts import resolve_context @@ -1166,8 +1177,9 @@ def declared_keeping_identifier( field: pa.Field[Any], type_converter: Any, # pyright: ignore[reportExplicitAny] # a data context's converter ) -> pa.Field[Any]: - """The one declaration rule of a SpiralDB store: a field in the declaration form - (``declaration_form_field``) only when that keeps its identifier's bytes. + """The one declaration rule of a writable SpiralDB database: a field in the + declaration form (``declaration_form_field``) only when that keeps its identifier's + bytes. A logical type in its storage form is made live when the live type the converter resolves states exactly the identifier bytes recorded. A type the converter also @@ -1235,7 +1247,7 @@ def _live(schema: pa.Schema, data_context: str) -> pa.Schema: ) -def _same_manifest(one: codec.StoreManifest, other: codec.StoreManifest) -> bool: +def _same_manifest(one: codec.TableManifest, other: codec.TableManifest) -> bool: """Whether two manifests record one table: the same path and kind, equivalent logical schemas (``schema_difference``) and the same stored schema. Never by their bytes, which differ for equivalent schemas represented differently.""" @@ -1273,6 +1285,6 @@ def _same_seen(one: _Seen, other: _Seen) -> bool: return False if one[0] == "manifest": return _same_manifest( - cast(codec.StoreManifest, one[1]), cast(codec.StoreManifest, other[1]) + cast(codec.TableManifest, one[1]), cast(codec.TableManifest, other[1]) ) return one[1] == other[1] diff --git a/src/orcapod/databases/spiraldb_writable_registry.py b/src/orcapod/databases/spiraldb_writable_registry.py new file mode 100644 index 000000000..e6f125881 --- /dev/null +++ b/src/orcapod/databases/spiraldb_writable_registry.py @@ -0,0 +1,33 @@ +"""Which writable SpiralDB connectors exist in this process (ITL-1844). + +A run takes the writer lease of every writable SpiralDB database it may write +(``spiraldb_write_scope.database_writes``), found by walking the run's graph. A writable +database always holds its writable connector, so when no writable connector exists in +the process no run can write one, and the run skips the walk +(``any_writable_connector``). +This module is a leaf: checking it imports nothing of SpiralDB. +""" + +from __future__ import annotations + +from weakref import WeakSet + +_writable_connectors: WeakSet[object] = WeakSet() + + +def register_writable_connector(connector: object) -> None: + """Record a writable connector, for as long as it exists. + + Args: + connector: A ``SpiralDBConnector`` made with ``writable=True``. + """ + _writable_connectors.add(connector) + + +def any_writable_connector() -> bool: + """Whether any writable SpiralDB connector exists in this process (closed ones too). + + Returns: + ``False`` only when no run can hold a writable SpiralDB database. + """ + return len(_writable_connectors) > 0 diff --git a/src/orcapod/databases/spiraldb_write_scope.py b/src/orcapod/databases/spiraldb_write_scope.py index db015675a..ac03ae498 100644 --- a/src/orcapod/databases/spiraldb_write_scope.py +++ b/src/orcapod/databases/spiraldb_write_scope.py @@ -1,16 +1,17 @@ -"""The writer leases a job run holds on the SpiralDB stores it writes (ITL-1844). - -A SpiralDB store (``SpiralDBConnector(..., store=True)``) has one writer at a time. A -job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) takes the writer -lease of every store dataset it may write (``store_writes``) before it checks a source, -computes or writes anything, and releases each lease when it ends, also when it fails. -A second writer is refused when it asks for the lease (``LeaseBusyError``), so before it -writes. A store write with no lease held is refused (``SpiralDBStoreLeaseRequiredError``, -raised by ``spiraldb_store_tables``). - -One lease per dataset: several store connectors on one dataset (a job's database and its -result database, a cached source's database) share the one lease the run takes. The lease -is refuse-only: no waiting, no taking over, no expiry (``spiraldb_lease``). +"""The writer leases a job run holds on the writable SpiralDB databases it writes +(ITL-1844). + +A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) has one writer +at a time. A job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) +takes the writer lease of every writable dataset it may write (``database_writes``) +before it checks a source, computes or writes anything, and releases each lease when it +ends, also when it fails. A second writer is refused when it asks for the lease +(``LeaseBusyError``), so before it writes. A database write with no lease held is +refused (``SpiralDBLeaseRequiredError``, raised by ``spiraldb_tables``). + +One lease per dataset: several writable connectors on one dataset (a job's database and +its result database, a cached source's database) share the one lease the run takes. The +lease is refuse-only: no waiting, no taking over, no expiry (``spiraldb_lease``). """ from __future__ import annotations @@ -25,15 +26,15 @@ from orcapod.databases.spiraldb_connector import SpiralDBConnector -def store_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: - """The distinct SpiralDB store connectors under ``databases``, in the order met. +def writable_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: + """The distinct writable SpiralDB connectors under ``databases``, in the order met. Args: databases: Databases a run may write, through ``ExtensionAwareDatabase`` views too; ``None`` entries are skipped. Returns: - Each store connector once (by object). + Each writable connector once (by object). """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views @@ -42,18 +43,19 @@ def store_connectors(databases: Iterable[object]) -> list[SpiralDBConnector]: for given in databases: database = unwrap_database_views( given - ) # a store under a library view is leased too + ) # a writable database under a library view is leased too if not isinstance(database, ConnectorArrowDatabase): continue - connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the store's connector, read by the one module that leases it + connector = database._spiral_connector # pyright: ignore[reportPrivateUsage] # the database's connector, read by the one module that leases it if connector is not None and not any(connector is c for c in found): found.append(connector) return found @contextlib.contextmanager -def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: - """Hold the writer lease of every SpiralDB store dataset among ``databases``. +def database_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: + """Hold the writer lease of every writable SpiralDB database dataset among + ``databases``. Every lease is acquired before the body runs; a refused one releases those already taken and raises. Each lease is released when the body ends, also when it raises @@ -68,7 +70,7 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: Args: databases: The databases the run may write. Nothing happens when none is a - SpiralDB store. + writable SpiralDB database. owner: Who holds the leases, shown to a refused second writer. Raises: @@ -79,19 +81,20 @@ def store_writes(databases: Iterable[object], *, owner: str) -> Iterator[None]: clear the lease). """ groups: dict[tuple[str, str, str], list[SpiralDBConnector]] = {} - for connector in store_connectors(databases): + for connector in writable_connectors(databases): groups.setdefault(connector._writer_lease_key(), []).append(connector) # pyright: ignore[reportPrivateUsage] # the lease is taken by this module only - held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # StoreTables + held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables try: for connectors in groups.values(): - # The store tables holding this lease, each once (every store connector has - # its own, ``share_client`` copies too; a repeat is skipped all the same). - holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # StoreTables + # The database tables holding this lease, each once (every writable + # connector has its own, ``share_client`` copies too; a repeat is skipped + # all the same). + holding: list[Any] = [] # pyright: ignore[reportExplicitAny] # SpiralDBTables def register( check: Callable[[], None], release: Callable[[], None], - holding: list[Any] = holding, # pyright: ignore[reportExplicitAny] # StoreTables + holding: list[Any] = holding, # pyright: ignore[reportExplicitAny] # SpiralDBTables ) -> None: held.append((holding, check, release)) @@ -122,10 +125,10 @@ def take_lease( *, on_taken: Callable[[Callable[[], None], Callable[[], None]], None] | None = None, ) -> tuple[Callable[[], None], Callable[[], None]]: - """Acquire the writer lease of a store connector's dataset (``spiraldb_lease``). + """Acquire the writer lease of a writable connector's dataset (``spiraldb_lease``). Args: - connector: A SpiralDB store connector. + connector: A writable SpiralDB connector. owner: Who holds it, shown to a refused second writer. on_taken: Optional: given ``(check, release)`` once the claim is verified, inside the acquisition's guard (``spiraldb_lease.acquire``'s ``on_claim``): @@ -159,21 +162,21 @@ def release() -> None: return taken[0] -def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # StoreTables; a store connector always has them while open - tables = connector._store_tables() # pyright: ignore[reportPrivateUsage] # the lease is handed to the store by this module only +def _tables(connector: SpiralDBConnector) -> Any: # pyright: ignore[reportExplicitAny] # SpiralDBTables; a writable connector always has them while open + tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] # the lease is handed to the database by this module only if tables is None: - raise RuntimeError("not a SpiralDB store connector") + raise RuntimeError("not a writable SpiralDB connector") return tables def _release_all( - held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]], # pyright: ignore[reportExplicitAny] # StoreTables + held: list[tuple[list[Any], Callable[[], None], Callable[[], None]]], # pyright: ignore[reportExplicitAny] # SpiralDBTables error: BaseException | None, ) -> None: """Let go of and release every lease in ``held``, each attempted whatever failed. Args: - held: The leases taken, with the store tables that hold each. + held: The leases taken, with the database tables that hold each. error: The body's error, ``None`` when the body succeeded. Raises: diff --git a/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 027e95db7..5d92b100b 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -35,22 +35,22 @@ def spiral_lease_key_column(keys: Sequence[str]) -> str | None: def require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: - """Refuse a path outside the SpiralDB store's component syntax. + """Refuse a path outside the SpiralDB database's component syntax. - A SpiralDB store table's full path is at least one component, and every component - is a non-empty ``str`` (not a subclass) with a UTF-8 form that holds neither ``/`` - nor NUL. Every writer and reader of a SpiralDB store table's identity record and - manifest applies it, so they accept and refuse the same component syntax. It is - the SpiralDB store's rule only: the other databases keep their own path rules (the - in-memory store accepts a lone surrogate or a ``str`` subclass, the Delta store - refuses a quoted component). Naming (``store_table_path_json``) encodes any path of - strings. + A SpiralDB database table's full path is at least one component, and every + component is a non-empty ``str`` (not a subclass) with a UTF-8 form that holds + neither ``/`` nor NUL. Every writer and reader of a SpiralDB database table's + identity record and manifest applies it, so they accept and refuse the same + component syntax. It is the SpiralDB database's rule only: the other databases keep + their own path rules (the in-memory store accepts a lone surrogate or a ``str`` + subclass, the Delta store refuses a quoted component). Naming + (``store_table_path_json``) encodes any path of strings. A path inside this syntax can still be refused for its size: each entry of the identity record is capped at SpiralDB's entry limit - (``spiral_store_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an + (``spiral_database_identity.MAX_METADATA_ENTRY_BYTES``, 8,192 bytes), so an 8,192-character component is valid here, round-trips through the chunked manifest, - and is refused by ``spiral_store_identity.store_table_metadata``. + and is refused by ``spiral_database_identity.table_identity_metadata``. Args: path: The store's base path followed by its record path. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 9b58f94cb..14a42d9f3 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -738,18 +738,22 @@ class SpiralDBWriteNotSupportedError(NotImplementedError): """ -class SpiralDBStoreLeaseRequiredError(RuntimeError): - """A SpiralDB store was written outside a job run (ITL-1844). - - A store (``SpiralDBConnector(..., store=True)``) is written only while a job run - (``job.run()``, ``job.run_async()`` or a job node's ``run()``) holds the dataset's - writer lease. A write anywhere else (a ``CachedSource`` read outside a run, a - ``ConnectorArrowDatabase`` flushed directly) is refused before anything is written. +class SpiralDBLeaseRequiredError(RuntimeError): + """A writable SpiralDB database was written outside a job run (ITL-1844). + + A writable SpiralDB database (``SpiralDBConnector(..., writable=True)``) is written + only while a job run (``job.run()``, ``job.run_async()`` or a job node's ``run()``) + holds the dataset's writer lease. A write anywhere else (a ``CachedSource`` read + outside a run, a ``ConnectorArrowDatabase`` flushed directly) is refused before + anything is written. """ class SpiralDBObserverNotSupportedError(SpiralDBWriteNotSupportedError): - """A status or logging observer was given a SpiralDB store at setup (ITL-1540).""" + """A status or logging observer was given a SpiralDB database at setup. + + Any SpiralDB connector is refused (ITL-1540). + """ class SpiralDBSignInError(RuntimeError): diff --git a/src/orcapod/pipeline/_observer_database.py b/src/orcapod/pipeline/_observer_database.py index 8fbd8ca97..0ab42409b 100644 --- a/src/orcapod/pipeline/_observer_database.py +++ b/src/orcapod/pipeline/_observer_database.py @@ -54,6 +54,6 @@ def require_observer_database(database: ArrowDatabaseProtocol) -> None: connector = _stored_reference(backend, "_connector") if issubclass(type(connector), SpiralDBConnector): raise SpiralDBObserverNotSupportedError( - "Observers cannot record to a SpiralDB store in this version. " + "Observers cannot record to a SpiralDB database in this version. " + "Give the observer another database, for example Delta." ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 3cae2a67e..6626e5865 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -42,7 +42,7 @@ clear_run_rows, plan_run, run_owner, - store_write_scope, + database_write_scope, ) from orcapod.pipeline.observer_losses import RunLosses from orcapod.pipeline.restrictions import ( @@ -1375,15 +1375,15 @@ def run( whatever the orchestrator's ``error_policy``, also when the read was needed to write a node's results. Its rows are not recomputed and the table is not overwritten. - LeaseBusyError: If another writer holds a SpiralDB store the run would - write (ITL-1844): refused before any source is checked and before - anything is computed or written. The leases a run takes are + LeaseBusyError: If another writer holds a writable SpiralDB database the + run would write (ITL-1844): refused before any source is checked and + before anything is computed or written. The leases a run takes are released when it ends, also when it fails. LeaseError: If a SpiralDB writer lease cannot be verified, or released at the end of a run that succeeded (its writes are committed). """ - # The writer leases of the SpiralDB stores the run writes are held from the - # source check to the end of the run (ITL-1844). + # The writer leases of the writable SpiralDB databases the run writes are held + # from the source check to the end of the run (ITL-1844). with contextlib.ExitStack() as leases: summary = self._run_holding( leases, @@ -1506,7 +1506,8 @@ async def run_async( f"{type(orchestrator).__name__}. Use job.run(orchestrator=...) to run " "it." ) - # The writer leases of the SpiralDB stores the run writes (ITL-1844). + # The writer leases of the writable SpiralDB databases the run writes + # (ITL-1844). with contextlib.ExitStack() as leases: summary = await self._run_async_holding( leases, @@ -1776,13 +1777,13 @@ def _prepare_run( # source, is refused before any source is checked and before anything is # computed or written (ITL-1218). refuse_restriction_conflicts(exec_dag.nodes()) - # One writer per SpiralDB store (ITL-1844): the run takes the writer lease of - # every store it may write before a source is checked (a cached source writes + # One writer per SpiralDB database (ITL-1844): the run takes the writer lease of + # every database it may write before a source is checked (a cached source writes # its cache then) and before anything is computed or written. A second writer # is refused here. if leases is not None: leases.enter_context( - store_write_scope( + database_write_scope( list(exec_dag.nodes()), load_only=load_only, # Every database a full run's flushes may write: its own, the @@ -2343,12 +2344,13 @@ def load( database is a connector database (SQLite, PostgreSQL, SpiralDB) and the argument that gives it is missing: a connector is not rebuilt from a file. The message names each such binding. Also if a - SpiralDB database was saved on a store - (``SpiralDBConnector(..., store=True)``) and the one given is a + SpiralDB database was saved writable + (``SpiralDBConnector(..., writable=True)``) and the one given is a plain SpiralDB connector database, or the other way round (ITL-1844). Only a SpiralDB database of the other kind is refused: a database that is not a SpiralDB one may stand for a saved - SpiralDB database. + SpiralDB database. A saved SpiralDB connector with a ``store`` key + is refused whatever database is given. """ import json as _json import os @@ -2367,7 +2369,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, - spiraldb_store_mismatch, + spiraldb_writable_mismatch, warn_saved_tags_as_data, ) @@ -2403,8 +2405,8 @@ def load( f"{path}: a database connector is not rebuilt from a saved job; it " "must be given to PipelineJob.load. " + "; ".join(missing) + "." ) - # A SpiralDB store and a plain SpiralDB connector read different tables - # (ITL-1844). + # A writable SpiralDB database and a plain SpiralDB connector read different + # tables (ITL-1844). mismatched = [ f"bindings.{slot_name}: {reason}" for slot_name, given in ( @@ -2412,7 +2414,7 @@ def load( ("result_database", result_database), ) if ( - reason := spiraldb_store_mismatch( + reason := spiraldb_writable_mismatch( data.get("bindings", {}).get(slot_name), given ) ) diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index b72fb7a12..23d47d96b 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -275,9 +275,9 @@ def _source_side_databases(streams: Iterable[Any]) -> list[Any]: pending.append((stream.bound_source, behind_table)) continue if isinstance(stream, CachedSource): - found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the store a run must hold the lease of + found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of if not behind_table and not _is_job_node(stream): - # A job node's pods: ``store_scope_databases``. + # A job node's pods: ``write_scope_databases``. found.extend(db for db in _pod_result_databases(stream) if db is not None) behind = behind_table or isinstance(stream, ArrowTableStream) inputs = getattr(stream, "live_source_inputs", None) @@ -306,10 +306,10 @@ def _job_nodes_under(targets: Iterable[Any]) -> list[Any]: return found -def store_scope_databases( +def write_scope_databases( streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = () ) -> list[Any]: - """The databases a run may write, for its writer leases (``store_write_scope``). + """The databases a run may write, for its writer leases (``database_write_scope``). A full run may write ``databases`` (a job's database and result database), the databases of the job nodes in ``streams`` and of every job node they depend on @@ -326,7 +326,7 @@ def store_scope_databases( databases: The job's own databases, for a full run. Returns: - The databases, in the order met (repeats are left to ``store_writes``). + The databases, in the order met (repeats are left to ``database_writes``). """ written: list[Any] = [] if not load_only: @@ -341,18 +341,19 @@ def store_scope_databases( return written -def store_write_scope( +def database_write_scope( streams: Sequence[Any], *, load_only: bool, databases: Iterable[Any] = (), owner: str | None = None, ) -> AbstractContextManager[None]: - """The writer leases a run holds on the SpiralDB stores it may write (ITL-1844). + """The writer leases a run holds on the writable SpiralDB databases it may write + (ITL-1844). - The run may write the databases ``store_scope_databases`` lists. Entered before the - run checks its sources (``spiraldb_write_scope.store_writes``). When no SpiralDB - store connector exists in the process, no run can write a store: nothing is walked + The run may write the databases ``write_scope_databases`` lists. Entered before the + run checks its sources (``spiraldb_write_scope.database_writes``). When no writable + SpiralDB connector exists in the process, no run can write one: nothing is walked and the scope holds nothing. Args: @@ -365,16 +366,16 @@ def store_write_scope( Returns: The context manager that holds the leases. """ - from orcapod.databases.spiraldb_store_registry import any_store_connector + from orcapod.databases.spiraldb_writable_registry import any_writable_connector - if not any_store_connector(): + if not any_writable_connector(): return contextlib.nullcontext() - from orcapod.databases.spiraldb_write_scope import store_writes + from orcapod.databases.spiraldb_write_scope import database_writes - written = store_scope_databases(streams, load_only=load_only, databases=databases) + written = write_scope_databases(streams, load_only=load_only, databases=databases) if owner is None: owner = run_owner(_job_name(streams[0]) if streams else "") - return store_writes(written, owner=owner) + return database_writes(written, owner=owner) def run_owner(name: str) -> str: diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 116b9a52e..a16513144 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -582,13 +582,15 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" -def spiraldb_store_mismatch(config: Any, given: Any) -> str | None: +def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """Why a database given at load cannot stand for a saved SpiralDB one, or ``None``. - A job saved on a SpiralDB store (``SpiralDBConnector(..., store=True)``, ITL-1844) - is loaded with a store connector, and one saved on a plain SpiralDB connector with - a plain one: the two read different tables. The project and dataset are not - compared (a job may be pointed at a copy). + A job saved on a writable SpiralDB database (``SpiralDBConnector(..., + writable=True)``, ITL-1844) is loaded with a writable connector, and one saved on a + plain SpiralDB connector with a plain one: the two read different tables. The + project and dataset are not compared (a job may be pointed at a copy). A saved + SpiralDB connector with a ``store`` key is refused whatever is given: it is not an + option of this version. Args: config: The saved database configuration. @@ -600,28 +602,34 @@ def spiraldb_store_mismatch(config: Any, given: Any) -> str | None: """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - from orcapod.databases.spiraldb_connector import SpiralDBConnector + from orcapod.databases.spiraldb_connector import ( + STORE_KEY_REFUSAL, + SpiralDBConnector, + ) if saved_connector_kind(config) != "spiraldb": return None + saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) + if "store" in saved: + return STORE_KEY_REFUSAL given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over if not isinstance(connector, SpiralDBConnector): return None - saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) - saved_store = saved.get("store", False) is True - given_store = connector._store_mode # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a store - if saved_store == given_store: + saved_writable = saved.get("writable", False) is True + given_writable = connector._writable # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a writable database + if saved_writable == given_writable: return None - if saved_store: + if saved_writable: return ( - "the job was saved on a SpiralDB store: pass a store connector, " - "SpiralDBConnector(..., store=True)" + "the job was saved on a writable SpiralDB database: pass a writable " + "connector, SpiralDBConnector(..., writable=True)" ) return ( - "the job was saved on a plain SpiralDB connector: pass one without store=True" + "the job was saved on a plain SpiralDB connector: pass one without " + "writable=True" ) diff --git a/tests/test_databases/test_spiral_store.py b/tests/test_databases/test_spiral_database_codec.py similarity index 85% rename from tests/test_databases/test_spiral_store.py rename to tests/test_databases/test_spiral_database_codec.py index 0c37ecb3f..69a23c3ac 100644 --- a/tests/test_databases/test_spiral_store.py +++ b/tests/test_databases/test_spiral_database_codec.py @@ -1,4 +1,4 @@ -"""The codec of a SpiralDB store table: names, types, rows and the manifest (ITL-1446, ITL-1497). +"""The codec of a writable SpiralDB database 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 @@ -25,7 +25,7 @@ import pytest from orcapod.contexts import get_default_context -from orcapod.databases import spiral_store as store +from orcapod.databases import spiral_database_codec as spiral_db 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 ( @@ -38,7 +38,7 @@ _same_values as same_values, # pyright: ignore[reportPrivateUsage] ) -KEY = store.KEY_COLUMN +KEY = spiral_db.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 @@ -122,7 +122,7 @@ def as_spiral_returns(rows: pa.Table, seed: int = 0, small: bool = False) -> pa. def by_id(rows: pa.Table) -> pa.Table: - """Rows sorted by key: a store is a set of rows.""" + """Rows sorted by key: a database 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()) @@ -132,24 +132,24 @@ def by_id(rows: pa.Table) -> pa.Table: PATH = ("run", "fn", "pdb_v1") -def new(schema: pa.Schema, path: tuple[str, ...] = PATH) -> store.StoreManifest: +def new(schema: pa.Schema, path: tuple[str, ...] = PATH) -> spiral_db.TableManifest: """A manifest of a table of ``schema`` at ``path``, in memory (not serialized).""" - return store.new_manifest(path, "function_pipeline", schema) + return spiral_db.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)) + return spiral_db.manifest_bytes(new(schema, path)) -def read(recorded: bytes, path: tuple[str, ...] = PATH) -> store.StoreManifest: +def read(recorded: bytes, path: tuple[str, ...] = PATH) -> spiral_db.TableManifest: """Parse a raw manifest payload (``manifest_bytes``), not a table's metadata.""" - return store.read_manifest_bytes(recorded, path) + return spiral_db.read_manifest_bytes(recorded, path) def decode(rows: pa.Table, schema: pa.Schema) -> pa.Table: """Decode through a manifest read back, giving ``schema`` (live types kept).""" - return store.decode_rows(rows, read(entries(schema)), large(schema)) + return spiral_db.decode_rows(rows, read(entries(schema)), large(schema)) def large_type(arrow_type: Any) -> Any: @@ -219,14 +219,14 @@ def round_trip(rows: pa.Table, *, live: bool = False) -> pa.Table: for piece in (rows, rows.slice(1), rows.slice(0, 1)): if not piece.num_rows: continue - encoded = store.encode_rows(piece) + encoded = spiral_db.encode_rows(piece) assert encoded.schema.equals( - store.physical_schema(rows.schema), check_metadata=True + spiral_db.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( + got = spiral_db.decode_rows( as_spiral_returns(encoded, seed, small), manifest, schema ) want = pa.Table.from_arrays( @@ -280,7 +280,7 @@ def walk(field: Any, named: bool, in_map: bool = False) -> None: walk(f, True) -def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: +def refused(rows: pa.Table, *words: str) -> spiral_db.UnstorableInSpiralError: """Check that ``encode_rows`` refuses ``rows`` with a message holding every word. Args: @@ -290,8 +290,8 @@ def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: Returns: The error, for assertions on what it says (``error.path``). """ - with pytest.raises(store.UnstorableInSpiralError) as info: - _ = store.encode_rows(rows) + with pytest.raises(spiral_db.UnstorableInSpiralError) as info: + _ = spiral_db.encode_rows(rows) for word in words: assert word in str(info.value) return info.value @@ -319,7 +319,7 @@ def refused(rows: pa.Table, *words: str) -> store.UnstorableInSpiralError: ], ) def test_the_names_of_the_design(name: str, stored: str) -> None: - assert store.encode_name(name) == stored + assert spiral_db.encode_name(name) == stored assert decoded(stored) == name @@ -347,7 +347,7 @@ def adversarial_names(count: int) -> set[str]: 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} + encoded = {name: spiral_db.encode_name(name) for name in names} assert len(set(encoded.values())) == len(names) for name, stored in encoded.items(): assert decoded(stored) == name @@ -357,8 +357,8 @@ def test_names_round_trip_and_are_injective() -> None: 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] + once = [spiral_db.encode_name(n) for n in names] + twice = [spiral_db.encode_name(n) for n in once] assert len(set(twice)) == len(names) assert [decoded(decoded(t)) for t in twice] == names @@ -405,19 +405,19 @@ def test_the_key_is_not_a_value_column_of_the_same_name() -> None: 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) + encoded = spiral_db.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"): + with pytest.raises(spiral_db.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"): + with pytest.raises(spiral_db.UnstorableInSpiralError, match="UTF-8"): + _ = spiral_db.encode_name(name) + with pytest.raises(spiral_db.UnstorableInSpiralError, match="UTF-8"): _ = new(schema_of([("a", pa.int8()), (KEY, pa.large_binary())]), (name,)) @@ -429,8 +429,8 @@ def test_a_name_that_is_not_utf8_is_refused_at_every_depth() -> None: 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())])) + with pytest.raises(spiral_db.UnstorableInSpiralError, match="UTF-8"): + _ = spiral_db.logical_schema(schema_of([field, (KEY, pa.large_binary())])) def wrappings(inner: Any) -> list[Any]: @@ -447,10 +447,12 @@ def wrappings(inner: Any) -> list[Any]: 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())])) + with pytest.raises(spiral_db.UnstorableInSpiralError, match="more than once"): + _ = spiral_db.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( + _ = spiral_db.logical_schema( schema_of([("a", same_in_two_structs), (KEY, pa.large_binary())]) ) @@ -694,7 +696,7 @@ def test_zone_aware_timestamps_are_exact(unit: str, zone: str) -> None: 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)) + encoded = spiral_db.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 @@ -788,7 +790,7 @@ def test_what_a_null_list_or_map_hides_is_not_written() -> None: 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) + encoded: Any = spiral_db.encode_rows(table) assert len(encoded.column("l").chunk(0).values) == 1 assert encoded.column("m").chunk(0).keys.to_pylist() == ["b"] @@ -866,7 +868,7 @@ def test_a_null_list_over_non_null_items_is_kept() -> None: ], ids=str, ) -def test_a_type_the_store_does_not_keep_is_refused_at_every_depth( +def test_a_type_the_database_does_not_keep_is_refused_at_every_depth( arrow_type: pa.DataType, ) -> None: for wrapped in ( @@ -878,13 +880,13 @@ def test_a_type_the_store_does_not_keep_is_refused_at_every_depth( 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'"): + for call in (spiral_db.physical_schema, spiral_db.logical_schema, entries): + with pytest.raises(spiral_db.UnstorableInSpiralError, match="'bad'"): _ = call(schema) def test_every_refusal_is_in_one_table() -> None: - assert [r.what for r in store.REFUSALS] == [ + assert [r.what for r in spiral_db.REFUSALS] == [ "a null struct", "a struct with no fields", "a write of no rows", @@ -895,7 +897,7 @@ def test_every_refusal_is_in_one_table() -> None: "a duration", "an interval", ] - assert all(r.why for r in store.REFUSALS) + assert all(r.why for r in spiral_db.REFUSALS) def test_lifting_a_type_is_one_entry(monkeypatch: pytest.MonkeyPatch) -> None: @@ -904,13 +906,13 @@ def test_lifting_a_type_is_one_entry(monkeypatch: pytest.MonkeyPatch) -> None: table = keyed({"d": pa.array([1, None, -2], duration("us"))}) _ = refused(table, "duration", "refuses") monkeypatch.setattr( - store, + spiral_db, "REFUSALS", - tuple(r for r in store.REFUSALS if r.matches is not matches), + tuple(r for r in spiral_db.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) + monkeypatch.setattr(spiral_db, "_NATIVE", (*spiral_db._NATIVE, matches)) # pyright: ignore[reportPrivateUsage] + encoded = spiral_db.encode_rows(table) assert_same(decode(as_spiral_returns(encoded), table.schema), table) @@ -931,7 +933,7 @@ def test_a_null_key_is_refused_whatever_the_schema_says(nullable: bool) -> None: 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"): + with pytest.raises(spiral_db.StoredRowsError, match="null key"): _ = decode(pa.table({KEY: key, "a": column}), schema) @@ -952,9 +954,9 @@ 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)) +def test_a_table_the_database_cannot_hold_is_refused(fields: Any, words: str) -> None: + with pytest.raises(spiral_db.UnstorableInSpiralError, match=words): + _ = spiral_db.physical_schema(schema_of(fields)) # ------------------------------------------------------------------- logical types @@ -1009,12 +1011,12 @@ def test_a_logical_type_is_kept_by_its_identifier( 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 spiral_db.encode_rows(one).equals(spiral_db.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) + back = decode(as_spiral_returns(spiral_db.encode_rows(one)), one.schema) assert by_id(back).column("c").chunk(0).type == live finally: if registered: @@ -1027,9 +1029,9 @@ def schema(name: str, metadata: bytes) -> pa.Schema: 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 + assert spiral_db.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) + difference = spiral_db.schema_difference(base, other) assert difference is not None and "'c'" in difference @@ -1045,19 +1047,19 @@ def test_a_logical_type_below_a_plain_type_is_refused() -> None: 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) + with pytest.raises(spiral_db.UnstorableInSpiralError, match="nested"): + _ = spiral_db.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())])) + with pytest.raises(spiral_db.UnstorableInSpiralError, match="nested"): + _ = spiral_db.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)) + return as_spiral_returns(spiral_db.encode_rows(table)) def large_table(table: pa.Table) -> pa.Table: @@ -1088,15 +1090,15 @@ def test_rows_that_are_not_what_was_written_are_refused() -> None: schema, good = table.schema, _stored(table) manifest = new(schema) assert_same(decode(good, schema), large_table(table)) - store.require_stored_schema(good.schema, manifest) + spiral_db.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)) + calls.append(lambda: spiral_db.require_stored_schema(rows.schema, manifest)) for call in calls: - with pytest.raises(store.StoredRowsError) as info: + with pytest.raises(spiral_db.StoredRowsError) as info: call() assert all(w in str(info.value) for w in (f"'{name}'", *words)) @@ -1127,12 +1129,12 @@ def bad(name: str, array: Any, *words: str, value: bool = False) -> None: 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)'"): + with pytest.raises(spiral_db.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"): + with pytest.raises(spiral_db.StoredRowsError, match="repeated"): _ = decode(repeated, schema) @@ -1145,15 +1147,15 @@ def test_rows_are_given_the_recorded_schema_only() -> None: 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) + with pytest.raises(spiral_db.ManifestError, match="not the recorded schema"): + _ = spiral_db.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))) + rows = spiral_db.empty_rows(read(entries(schema))) assert rows.num_rows == 0 - assert rows.schema.equals(store.logical_schema(schema), check_metadata=True) + assert rows.schema.equals(spiral_db.logical_schema(schema), check_metadata=True) # ------------------------------------------------------------------------ manifest @@ -1187,8 +1189,8 @@ def test_a_manifest_of_200_columns_with_metadata() -> None: 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 manifest.schema.equals(spiral_db.logical_schema(schema), check_metadata=True) + for a, b in zip(spiral_db.logical_schema(schema), manifest.schema): assert field_difference(a, b, a.name) is None @@ -1206,9 +1208,9 @@ def reordered(field: Any) -> Any: 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 + original = spiral_db.logical_schema monkeypatch.setattr( - store, + spiral_db, "logical_schema", lambda s: schema_of([reordered(f) for f in original(s)], metadata=s.metadata), ) @@ -1217,7 +1219,7 @@ def reordered(field: Any) -> Any: 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 + assert spiral_db.schema_difference(one, two) is None def test_every_row_of_the_matrix_round_trips_in_one_manifest(tmp_path: Path) -> None: @@ -1237,7 +1239,7 @@ def test_every_row_of_the_matrix_round_trips_in_one_manifest(tmp_path: Path) -> schema = schema_of(order) got = read(entries(schema)).schema assert got.names == schema.names - for a, b in zip(store.logical_schema(schema), got): + for a, b in zip(spiral_db.logical_schema(schema), got): assert field_difference(a, b, a.name) is None @@ -1267,7 +1269,7 @@ def test_metadata_keys_that_look_like_the_marks_are_kept() -> None: 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 + assert spiral_db.schema_difference(schema_of(BASE), other) is None @pytest.mark.parametrize( @@ -1303,7 +1305,7 @@ def test_another_schema_is_a_difference(changed: Any) -> None: 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 + assert spiral_db.schema_difference(a, b) is not None def test_schema_metadata_and_more_columns_are_a_difference() -> None: @@ -1312,19 +1314,19 @@ def test_schema_metadata_and_more_columns_are_a_difference() -> None: schema.with_metadata({"k": "v"}), schema_of([*BASE, ("more", pa.int8())]), ): - assert store.schema_difference(schema, other) is not None + assert spiral_db.schema_difference(schema, other) is not None def test_a_manifest_of_another_path_is_refused() -> None: recorded = entries(schema_of(BASE), ("a", "b")) for path in (("a",), ("b", "a"), ("a", "b", ""), ("a_b",), ()): - with pytest.raises(store.ManifestError, match="recorded as"): - _ = store.read_manifest_bytes(recorded, path) + with pytest.raises(spiral_db.ManifestError, match="recorded as"): + _ = spiral_db.read_manifest_bytes(recorded, path) @pytest.mark.parametrize("part", ["a/b", "a\0", "\udc00"]) -def test_a_path_component_the_store_cannot_name_is_refused(part: str) -> None: - with pytest.raises(store.UnstorableInSpiralError): +def test_a_path_component_the_database_cannot_name_is_refused(part: str) -> None: + with pytest.raises(spiral_db.UnstorableInSpiralError): _ = new(schema_of(BASE), ("x", part)) @@ -1344,10 +1346,10 @@ def test_stored_names_come_from_the_manifest_not_from_the_rule( def renamed(name: str) -> str: return "new_" + name.encode().hex() - monkeypatch.setattr(store, "encode_name", renamed) + monkeypatch.setattr(spiral_db, "encode_name", renamed) manifest = read(metadata) assert "ox_a;2Eb" in manifest.physical.names - got = store.decode_rows(stored, manifest) + got = spiral_db.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 @@ -1371,7 +1373,7 @@ def _ipc(schema: pa.Schema) -> str: 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) + return spiral_db.physical_schema(schema_of(BASE)).set(index, field) def test_the_changed_payload_helper_builds_a_readable_manifest() -> None: @@ -1411,8 +1413,8 @@ def test_a_manifest_that_cannot_be_read_in_full_is_an_error( make: Callable[[bytes], bytes], ) -> None: recorded = make(entries(schema_of(BASE))) - with pytest.raises(store.ManifestError): - _ = store.read_manifest_bytes(recorded, PATH) + with pytest.raises(spiral_db.ManifestError): + _ = spiral_db.read_manifest_bytes(recorded, PATH) def test_a_large_manifest_is_kept() -> None: @@ -1427,12 +1429,12 @@ def test_a_large_manifest_is_kept() -> None: 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 + assert spiral_db.manifest_bytes(read(one)) == one def test_the_codec_needs_no_spiral_client() -> None: code = ( - "import sys, orcapod.databases.spiral_store\n" + "import sys, orcapod.databases.spiral_database_codec\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 @@ -1440,19 +1442,19 @@ def test_the_codec_needs_no_spiral_client() -> None: _NARROWED_MAP = """ import pyarrow as pa -from orcapod.databases import spiral_store as store +from orcapod.databases import spiral_database_codec as codec maps = pa.map_(pa.string(), pa.int64()) rows = pa.table( { - store.KEY_COLUMN: pa.array([b"a", b"b", b"c"], pa.large_binary()), + codec.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) +manifest = codec.new_manifest(("p", "rdb_v1"), "k", rows.schema) +got = codec.decode_rows(codec.encode_rows(rows), manifest, rows.schema) assert got.schema == rows.schema, got.schema assert got.to_pylist() == rows.to_pylist(), got.to_pylist() """ @@ -1484,26 +1486,26 @@ def test_a_record_id_repeated_in_one_write_is_refused() -> None: def test_a_manifest_in_chunks_round_trips_within_the_entry_limit() -> None: manifest = new(wide_schema(), PATH) - entries_ = store.manifest_entries(manifest) + entries_ = spiral_db.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 + assert spiral_db.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 + entries_ = spiral_db.manifest_entries(new(schema_of(BASE))) + chunks = {k: v for k, v in entries_.items() if k != spiral_db.MANIFEST_KEY} + assert spiral_db.read_manifest({}, PATH) is None + assert spiral_db.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)) + longer = spiral_db.manifest_entries(new(wide_schema(), PATH)) + shorter = spiral_db.manifest_entries(new(schema_of(BASE), PATH)) assert len(longer) > len(shorter) - assert store.read_manifest({**longer, **shorter}, PATH) == new(schema_of(BASE)) + assert spiral_db.read_manifest({**longer, **shorter}, PATH) == new(schema_of(BASE)) def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, bytes]: @@ -1516,15 +1518,18 @@ def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, byt Returns: The entries with the header rewritten. """ - header = {**json.loads(entries_[store.MANIFEST_KEY]), **changes} - return {**entries_, store.MANIFEST_KEY: json.dumps(header).encode()} + header = {**json.loads(entries_[spiral_db.MANIFEST_KEY]), **changes} + return {**entries_, spiral_db.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: {k: v for k, v in e.items() if k != f"{spiral_db.MANIFEST_KEY}/0"}, + lambda e: { + **e, + f"{spiral_db.MANIFEST_KEY}/0": e[f"{spiral_db.MANIFEST_KEY}/0"] + b" ", + }, + lambda e: {**e, spiral_db.MANIFEST_KEY: b"\xff"}, + lambda e: {**e, spiral_db.MANIFEST_KEY: b"[]"}, lambda e: _header_changed(e, format="other"), lambda e: _header_changed(e, chunks=0), lambda e: _header_changed(e, chunks="1"), @@ -1537,21 +1542,23 @@ def _header_changed(entries_: dict[str, bytes], **changes: Any) -> dict[str, byt 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) + with pytest.raises(spiral_db.ManifestError): + _ = spiral_db.read_manifest( + make(spiral_db.manifest_entries(new(wide_schema()))), PATH + ) # --------------------------------------- CodeRabbit on PR 590 (b433047e) -def test_a_schema_override_that_is_not_a_store_schema_is_a_manifest_error() -> None: +def test_a_schema_override_that_is_not_a_database_schema_is_a_manifest_error() -> None: """``decode_rows`` raises its documented ``ManifestError``, also for a schema that - is no store schema at all (no key column).""" + is no database table schema at all (no key column).""" table = keyed({"a": pa.array([1])}) manifest = new(table.schema) without_key = table.schema.remove(table.schema.get_field_index(KEY)) - with pytest.raises(store.ManifestError): - _ = store.decode_rows(_stored(table), manifest, without_key) + with pytest.raises(spiral_db.ManifestError): + _ = spiral_db.decode_rows(_stored(table), manifest, without_key) @pytest.mark.parametrize("where", ["schema", "physical"]) @@ -1563,11 +1570,11 @@ def test_a_recorded_name_that_is_not_utf8_is_a_manifest_error(where: str) -> Non bad: Any = pa.field(cast(Any, b"a\xff"), pa.int8()) recorded = _payload(schema=_ipc(schema_of([bad, (KEY, pa.large_binary())]))) else: - first = store.physical_schema(schema_of(BASE)).field(0) + first = spiral_db.physical_schema(schema_of(BASE)).field(0) renamed: Any = pa.field(cast(Any, b"a\xff"), first.type, first.nullable) recorded = _payload(physical=_ipc(_physical(0, renamed))) - with pytest.raises(store.ManifestError, match="UTF-8"): - _ = store.read_manifest_bytes(recorded, PATH) + with pytest.raises(spiral_db.ManifestError, match="UTF-8"): + _ = spiral_db.read_manifest_bytes(recorded, PATH) # --------------------------------------- CodeRabbit on PR 595 (49f1642d) @@ -1578,7 +1585,7 @@ def test_an_impossible_chunk_count_is_refused_before_any_key_is_listed( ) -> None: """A header naming more chunks than the metadata holds entries is refused at once: no key is built for each (a count of 10**12 would exhaust memory).""" - entries_ = store.manifest_entries(new(schema_of(BASE))) + entries_ = spiral_db.manifest_entries(new(schema_of(BASE))) real_range = range def bounded(*args: Any) -> Any: @@ -1587,28 +1594,28 @@ def bounded(*args: Any) -> Any: raise AssertionError(f"a key listed for each of {stop} declared chunks") return real_range(*args) - monkeypatch.setattr(store, "range", bounded, raising=False) - with pytest.raises(store.ManifestError, match="10000000000"): - _ = store.read_manifest(_header_changed(entries_, chunks=10**10), PATH) + monkeypatch.setattr(spiral_db, "range", bounded, raising=False) + with pytest.raises(spiral_db.ManifestError, match="10000000000"): + _ = spiral_db.read_manifest(_header_changed(entries_, chunks=10**10), PATH) monkeypatch.undo() # A complete manifest of many chunks still reads, and a surplus chunk of an earlier # manifest beside it is still ignored. - longer = store.manifest_entries(new(wide_schema(), PATH)) - assert store.read_manifest(longer, PATH) == new(wide_schema()) + longer = spiral_db.manifest_entries(new(wide_schema(), PATH)) + assert spiral_db.read_manifest(longer, PATH) == new(wide_schema()) @pytest.mark.parametrize("version", [1, -1, "0", 0.0, None, True]) def test_a_manifest_header_of_another_version_is_refused(version: Any) -> None: """The header's version is checked as the payload's is: an exact integer.""" - entries_ = store.manifest_entries(new(schema_of(BASE))) + entries_ = spiral_db.manifest_entries(new(schema_of(BASE))) changed = _header_changed(entries_, version=version) - with pytest.raises(store.ManifestError, match="header version"): - _ = store.read_manifest(changed, PATH) - without = json.loads(entries_[store.MANIFEST_KEY]) + with pytest.raises(spiral_db.ManifestError, match="header version"): + _ = spiral_db.read_manifest(changed, PATH) + without = json.loads(entries_[spiral_db.MANIFEST_KEY]) del without["version"] - missing = {**entries_, store.MANIFEST_KEY: json.dumps(without).encode()} - with pytest.raises(store.ManifestError, match="header version"): - _ = store.read_manifest(missing, PATH) + missing = {**entries_, spiral_db.MANIFEST_KEY: json.dumps(without).encode()} + with pytest.raises(spiral_db.ManifestError, match="header version"): + _ = spiral_db.read_manifest(missing, PATH) @pytest.mark.parametrize("annotated", [False, True]) @@ -1623,8 +1630,8 @@ def test_a_dictionary_of_a_logical_types_values_is_refused_as_unstorable( metadata = {NAME_KEY: b"test.dictionary", METADATA_KEY: b""} if annotated else None field = pa.field("bad", values, True, cast(Any, metadata)) schema = schema_of([("a", pa.int64()), field, (KEY, pa.large_binary())]) - for call in (store.physical_schema, store.logical_schema, entries): - with pytest.raises(store.UnstorableInSpiralError, match="'bad'"): + for call in (spiral_db.physical_schema, spiral_db.logical_schema, entries): + with pytest.raises(spiral_db.UnstorableInSpiralError, match="'bad'"): _ = call(schema) @@ -1654,16 +1661,16 @@ def test_extension_metadata_without_a_name_round_trips_through_chunks() -> None: ], schema=schema, ) - loaded = store.read_manifest(store.manifest_entries(new(schema)), PATH) + loaded = spiral_db.read_manifest(spiral_db.manifest_entries(new(schema)), PATH) assert loaded is not None assert loaded.schema.equals(schema, check_metadata=True) - got = store.decode_rows(store.encode_rows(rows), loaded) + got = spiral_db.decode_rows(spiral_db.encode_rows(rows), loaded) assert got.schema.equals(schema, check_metadata=True) assert got.schema.field("x").metadata == plain assert got.to_pylist() == rows.to_pylist() # The entry counts in a comparison: a schema without it is another schema. without = schema.set(1, pa.field("x", pa.int64())) - assert store.schema_difference(loaded.schema, without) is not None + assert spiral_db.schema_difference(loaded.schema, without) is not None @pytest.mark.parametrize("target", [7_999, 8_000, 8_001, 15_999, 16_000, 16_001]) @@ -1675,32 +1682,32 @@ def test_the_manifest_is_cut_every_8000_bytes(target: int) -> None: import hashlib schema = schema_of(BASE) - base = len(store.manifest_bytes(store.new_manifest(PATH, "", schema))) - manifest = store.new_manifest(PATH, "k" * (target - base), schema) - payload = store.manifest_bytes(manifest) + base = len(spiral_db.manifest_bytes(spiral_db.new_manifest(PATH, "", schema))) + manifest = spiral_db.new_manifest(PATH, "k" * (target - base), schema) + payload = spiral_db.manifest_bytes(manifest) assert len(payload) == target - entries_ = store.manifest_entries(manifest) + entries_ = spiral_db.manifest_entries(manifest) count = -(-target // 8_000) - chunks = [entries_[f"{store.MANIFEST_KEY}/{i}"] for i in range(count)] + chunks = [entries_[f"{spiral_db.MANIFEST_KEY}/{i}"] for i in range(count)] assert [len(c) for c in chunks] == [8_000] * (count - 1) + [ target - 8_000 * (count - 1) ] assert set(entries_) == { - store.MANIFEST_KEY, - *(f"{store.MANIFEST_KEY}/{i}" for i in range(count)), + spiral_db.MANIFEST_KEY, + *(f"{spiral_db.MANIFEST_KEY}/{i}" for i in range(count)), } - header = json.loads(entries_[store.MANIFEST_KEY]) + header = json.loads(entries_[spiral_db.MANIFEST_KEY]) assert header["chunks"] == count assert header["payload_digest"] == hashlib.sha256(payload).hexdigest() assert b"".join(chunks) == payload backwards = dict(reversed(list(entries_.items()))) - assert store.read_manifest(backwards, PATH) == manifest - last = f"{store.MANIFEST_KEY}/{count - 1}" + assert spiral_db.read_manifest(backwards, PATH) == manifest + last = f"{spiral_db.MANIFEST_KEY}/{count - 1}" missing = {k: v for k, v in entries_.items() if k != last} modified = {**entries_, last: entries_[last][:-1] + b"#"} for broken in (missing, modified): - with pytest.raises(store.ManifestError): - _ = store.read_manifest(broken, PATH) + with pytest.raises(spiral_db.ManifestError): + _ = spiral_db.read_manifest(broken, PATH) # ------------------------------------- CodeRabbit review of PR 691 (216f1982d) @@ -1723,10 +1730,10 @@ def _decimal128(coefficients: list[int], precision: int) -> Any: def test_a_stored_decimal_over_its_precision_is_refused( logical: Any, precision: int, over: int ) -> None: - """Thread on spiral_store.py:789: a stored coefficient with more digits than the - logical decimal's precision is a ``StoredRowsError`` naming the column, never a raw - Arrow error, and never a wrapped value (pyarrow's narrowing cast lets 10**12 into a - decimal32 as -7273799.68).""" + """Thread on spiral_database_codec.py:789: a stored coefficient with more digits + than the logical decimal's precision is a ``StoredRowsError`` naming the column, + never a raw Arrow error, and never a wrapped value (pyarrow's narrowing cast lets + 10**12 into a decimal32 as -7273799.68).""" D = decimal.Decimal table = keyed({"d": pa.array([D("1.25"), D("-3.50")], logical)}) good = _stored(table) @@ -1735,28 +1742,28 @@ def test_a_stored_decimal_over_its_precision_is_refused( rows = good.set_column( good.column_names.index("d"), "d", _decimal128([125, wide], precision) ) - with pytest.raises(store.StoredRowsError, match="'d'"): + with pytest.raises(spiral_db.StoredRowsError, match="'d'"): _ = decode(rows, table.schema) def test_a_small_list_over_its_offset_range_is_refused( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Thread on spiral_store.py:748: a decoded large list of maps rebuilt as a small - list whose items do not fit 32-bit offsets is a ``StoredRowsError``, never wrapped - offsets. Reaching it for real takes more than 2**31 map items in one chunk (some - 16 GB), so the large list's offsets are made to say so.""" + """Thread on spiral_database_codec.py:748: a decoded large list of maps rebuilt as a + small list whose items do not fit 32-bit offsets is a ``StoredRowsError``, never + wrapped offsets. Reaching it for real takes more than 2**31 map items in one chunk + (some 16 GB), so the large list's offsets are made to say so.""" entry = pa.map_(pa.large_string(), pa.int8()) given: Any = pa.array([[[("a", 1)]]], pa.large_list(entry)) target = pa.list_(pa.map_(pa.string(), pa.int8())) - real = store._offsets # pyright: ignore[reportPrivateUsage] + real = spiral_db._offsets # pyright: ignore[reportPrivateUsage] def offsets(array: Any) -> Any: if pa.types.is_large_list(array.type): return np.array([0, 2**31], np.int64) return real(array) - assert store._retyped(given, target).to_pylist() == given.to_pylist() # pyright: ignore[reportPrivateUsage] - monkeypatch.setattr(store, "_offsets", offsets) - with pytest.raises(store.StoredRowsError, match="2147483648 items"): - _ = store._retyped(given, target) # pyright: ignore[reportPrivateUsage] + assert spiral_db._retyped(given, target).to_pylist() == given.to_pylist() # pyright: ignore[reportPrivateUsage] + monkeypatch.setattr(spiral_db, "_offsets", offsets) + with pytest.raises(spiral_db.StoredRowsError, match="2147483648 items"): + _ = spiral_db._retyped(given, target) # pyright: ignore[reportPrivateUsage] diff --git a/tests/test_databases/test_spiral_store_identity.py b/tests/test_databases/test_spiral_database_identity.py similarity index 64% rename from tests/test_databases/test_spiral_store_identity.py rename to tests/test_databases/test_spiral_database_identity.py index 55fae7171..784e83aa3 100644 --- a/tests/test_databases/test_spiral_store_identity.py +++ b/tests/test_databases/test_spiral_database_identity.py @@ -1,4 +1,4 @@ -"""SpiralDB store table names and their identity record (ITL-1837; spec ITL-1446 round 2). +"""writable SpiralDB database table names and their identity record (ITL-1837; spec ITL-1446 round 2). The name rule itself, digest and hint, is main's shared one (``test_store_table_names.py``); these tests cover SpiralDB's budget of it and the record in a table's metadata. @@ -16,8 +16,8 @@ import pyarrow as pa import pytest -from orcapod.databases import spiral_store -from orcapod.databases import spiral_store_identity as names +from orcapod.databases import spiral_database_codec +from orcapod.databases import spiral_database_identity as names from orcapod.databases import store_table_names H = "0123456789abcdef" * 4 @@ -32,13 +32,15 @@ def test_the_digest_is_sha256_of_the_canonical_json_of_the_components() -> None: json.dumps(list(RESULT), ensure_ascii=False, separators=(",", ":")).encode() ).hexdigest() assert store_table_names.store_table_digest(RESULT) == expected - assert names.spiral_store_table_name(RESULT).endswith("_" + expected) + assert names.spiral_table_name(RESULT).endswith("_" + expected) @pytest.mark.parametrize("path", [RESULT, PIPELINE, ("a",), ("É" * 300, "x" * 500)]) def test_a_name_is_short_and_plain(path: tuple[str, ...]) -> None: - """A name is ``o1__<64 hex>``, within 164 characters, for short and long paths.""" - name = names.spiral_store_table_name(path) + """A name is ``o1__<64 hex>``, within 164 characters, for short and long + paths. + """ + name = names.spiral_table_name(path) assert NAME.match(name), name assert len(name) <= 3 + 96 + 1 + 64 <= 255 @@ -52,24 +54,18 @@ def test_the_hint_keeps_lower_case_letters_and_digits() -> None: # one character to one: each other character, the separator included, is one '_' assert store_table_names.table_name_hint(("é", "a/b"), hint_length=96) == "__a_b" assert store_table_names.table_name_hint(("é", "z"), hint_length=96) == "__z" - assert len(names.spiral_store_table_name(("x" * 200,))) - len("o1__") - 64 == 96 + assert len(names.spiral_table_name(("x" * 200,))) - len("o1__") - 64 == 96 def test_the_name_is_deterministic_and_depends_on_every_component_and_its_order() -> ( None ): """A name follows every component and their order, and nothing else.""" - assert names.spiral_store_table_name(RESULT) == names.spiral_store_table_name( - list(RESULT) - ) - assert names.spiral_store_table_name(RESULT) != names.spiral_store_table_name( - RESULT[::-1] - ) + assert names.spiral_table_name(RESULT) == names.spiral_table_name(list(RESULT)) + assert names.spiral_table_name(RESULT) != names.spiral_table_name(RESULT[::-1]) for i in range(len(RESULT)): changed = RESULT[:i] + (RESULT[i] + "x",) + RESULT[i + 1 :] - assert names.spiral_store_table_name(changed) != names.spiral_store_table_name( - RESULT - ) + assert names.spiral_table_name(changed) != names.spiral_table_name(RESULT) def test_components_are_kept_apart() -> None: @@ -83,9 +79,7 @@ def test_components_are_kept_apart() -> None: (("x",), ("x", "")), ] for left, right in pairs: - assert names.spiral_store_table_name(left) != names.spiral_store_table_name( - right - ) + assert names.spiral_table_name(left) != names.spiral_table_name(right) def test_no_two_of_many_adversarial_paths_share_a_name() -> None: @@ -98,7 +92,7 @@ def test_no_two_of_many_adversarial_paths_share_a_name() -> None: "".join(rng.choice(alphabet) for _ in range(rng.randint(0, 4))) for _ in range(rng.randint(1, 3)) ) - name = names.spiral_store_table_name(path) + name = names.spiral_table_name(path) assert seen.setdefault(name, path) == path @@ -117,49 +111,53 @@ def test_no_two_of_many_adversarial_paths_share_a_name() -> None: def test_a_table_under_a_prefix_has_the_prefix_s_name_prefix( path: tuple[str, ...], prefix: tuple[str, ...] ) -> None: - """Every table under a path prefix has the prefix's name prefix, also past 96 characters.""" - assert names.spiral_store_table_name(path).startswith( - names.spiral_store_table_name_prefix(prefix) + """Every table under a path prefix has the prefix's name prefix, also past 96 + characters. + """ + assert names.spiral_table_name(path).startswith( + names.spiral_table_name_prefix(prefix) ) -def test_the_name_prefix_of_nothing_is_every_store_table() -> None: - """The name prefix of the empty path prefix is the one every store table has.""" - assert names.spiral_store_table_name_prefix(()) == "o1_" +def test_the_name_prefix_of_nothing_is_every_database_table() -> None: + """The name prefix of the empty path prefix is the one every database table has.""" + assert names.spiral_table_name_prefix(()) == "o1_" @pytest.mark.parametrize("path", [(), ("a", 1), ("\ud800",)]) def test_a_path_that_cannot_be_named_is_refused(path: tuple[object, ...]) -> None: """An empty path, a component that is not text and one that is not UTF-8 are refused.""" with pytest.raises(ValueError, match="path"): - _ = names.spiral_store_table_name(path) # pyright: ignore[reportArgumentType] # refused on purpose + _ = names.spiral_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") + """A table's record holds its format, path, layout and data context, and reads + back. + """ + record = names.table_identity_metadata(PIPELINE, "std:v1:default") assert record == { - "orcapod.store": b"orcapod.spiral_store.draft", + "orcapod.table_format": b"orcapod.spiral_database.draft", "orcapod.path": json.dumps( list(PIPELINE), ensure_ascii=False, separators=(",", ":") ).encode(), "orcapod.layout": b"pdb_v2", "orcapod.data_context": b"std:v1:default", } - found = names.read_store_table_metadata(record) - assert found == names.StoreTableRecord(PIPELINE, "pdb_v2", "std:v1:default") + found = names.read_table_identity_metadata(record) + assert found == names.TableRecord(PIPELINE, "pdb_v2", "std:v1:default") assert found is not None - names.require_store_table_path(found, PIPELINE) + names.require_table_path(found, PIPELINE) def test_every_entry_fits_the_service_s_entry_limit() -> None: """Every entry of a record fits SpiralDB's entry limit; a longer path is refused.""" # The JSON of a one-component path is the component and 4 bytes: ``["..."]``. longest = ("x" * (8192 - len("orcapod.path") - 4),) - record = names.store_table_metadata(longest, "std:v1:default") + record = names.table_identity_metadata(longest, "std:v1:default") assert all(len(k.encode()) + len(v) <= 8192 for k, v in record.items()) with pytest.raises(ValueError, match="8192"): - _ = names.store_table_metadata((longest[0] + "x",), "std:v1:default") + _ = names.table_identity_metadata((longest[0] + "x",), "std:v1:default") def test_a_valid_component_can_still_be_too_long_for_the_identity_record() -> None: @@ -167,25 +165,25 @@ def test_a_valid_component_can_still_be_too_long_for_the_identity_record() -> No limit, not by the syntax: the manifest, which is chunked, still keeps it.""" path = ("x" * 8192, "rdb_v1") assert store_table_names.require_store_path_domain(path) == path - manifest = spiral_store.new_manifest(path, "k", _schema()) - entries = spiral_store.manifest_entries(manifest) - assert spiral_store.read_manifest(entries, path) == manifest + manifest = spiral_database_codec.new_manifest(path, "k", _schema()) + entries = spiral_database_codec.manifest_entries(manifest) + assert spiral_database_codec.read_manifest(entries, path) == manifest with pytest.raises( ValueError, match="'orcapod.path' is 8217 bytes, over SpiralDB's 8192" ): - _ = names.store_table_metadata(path, "std:v1:default") + _ = names.table_identity_metadata(path, "std:v1:default") def test_a_table_without_orcapod_metadata_is_unmarked() -> None: """A table with none of the record's entries is unmarked.""" - assert names.read_store_table_metadata({}) is None - assert names.read_store_table_metadata({"someone.else": b"1"}) is None + assert names.read_table_identity_metadata({}) is None + assert names.read_table_identity_metadata({"someone.else": b"1"}) is None @pytest.mark.parametrize( "change", [ - {"orcapod.store": b"orcapod.spiral_store.v1"}, + {"orcapod.table_format": b"orcapod.spiral_database.v1"}, {"orcapod.path": b"not json"}, {"orcapod.path": b'{"a": 1}'}, {"orcapod.path": b"[]"}, @@ -195,62 +193,69 @@ def test_a_table_without_orcapod_metadata_is_unmarked() -> None: {"orcapod.path": b"\xff"}, ], ) -def test_a_record_that_is_not_this_store_s_is_refused(change: dict[str, bytes]) -> None: - """A record of another format, or with an unreadable or inconsistent entry, is refused.""" - record = {**names.store_table_metadata(PIPELINE, "std:v1:default"), **change} - with pytest.raises(names.SpiralStoreTableCollisionError): - _ = names.read_store_table_metadata(record) +def test_a_record_that_is_not_this_database_s_is_refused( + change: dict[str, bytes], +) -> None: + """A record of another format, or with an unreadable or inconsistent entry, is + refused. + """ + record = {**names.table_identity_metadata(PIPELINE, "std:v1:default"), **change} + with pytest.raises(names.SpiralTableCollisionError): + _ = names.read_table_identity_metadata(record) @pytest.mark.parametrize( "missing", - ["orcapod.store", "orcapod.path", "orcapod.layout", "orcapod.data_context"], + ["orcapod.table_format", "orcapod.path", "orcapod.layout", "orcapod.data_context"], ) def test_a_partial_record_is_refused(missing: str) -> None: """A record lacking one of its entries is refused.""" - record = names.store_table_metadata(PIPELINE, "std:v1:default") + record = names.table_identity_metadata(PIPELINE, "std:v1:default") del record[missing] - with pytest.raises(names.SpiralStoreTableCollisionError): - _ = names.read_store_table_metadata(record) + with pytest.raises(names.SpiralTableCollisionError): + _ = names.read_table_identity_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") + found = names.read_table_identity_metadata( + names.table_identity_metadata(RESULT, "std:v1:default") ) assert found is not None - with pytest.raises(names.SpiralStoreTableCollisionError, match="rdb_v1"): - names.require_store_table_path(found, PIPELINE) + with pytest.raises(names.SpiralTableCollisionError, match="rdb_v1"): + names.require_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) + _ = names.table_identity_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"), + **names.table_identity_metadata(RESULT, "std:v1:default"), "orcapod.path": b'["\\ud800","rdb_v1"]', } - with pytest.raises(names.SpiralStoreTableCollisionError, match="UTF-8"): - _ = names.read_store_table_metadata(record) + with pytest.raises(names.SpiralTableCollisionError, match="UTF-8"): + _ = names.read_table_identity_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") + # 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_table_identity_metadata( + names.table_identity_metadata(("a b", "rdb_v1"), "std:v1:default") ) assert found is not None - with pytest.raises(names.SpiralStoreTableCollisionError) as raised: - names.require_store_table_path(found, ("a", "b", "rdb_v1")) + with pytest.raises(names.SpiralTableCollisionError) as raised: + names.require_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) @@ -263,39 +268,39 @@ def test_the_collision_message_keeps_components_apart() -> None: 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"), + **names.table_identity_metadata(RESULT, "std:v1:default"), "orcapod.path": path_json, } - with pytest.raises(names.SpiralStoreTableCollisionError): - _ = names.read_store_table_metadata(record) + with pytest.raises(names.SpiralTableCollisionError): + _ = names.read_table_identity_metadata(record) def test_the_spiraldb_name_is_the_shared_rule_with_spiraldb_s_budget() -> None: """The name is main's shared store rule at hint 96 and the whole digest: the vector ``test_store_table_names.py`` pins for SpiralDB, and no rule of its own.""" path = ("función", "数据", "rdb_v1") - assert names.spiral_store_table_name(path) == ( + assert names.spiral_table_name(path) == ( "o1_funci_n____rdb_v1_" "4c0b0f48110dc57f910431847088e2e11d05b6bf2b26c3e8dfb8dd9dabf2c43b" ) - assert names.spiral_store_table_name(path) == store_table_names.store_table_name( + assert names.spiral_table_name(path) == store_table_names.store_table_name( path, hint_length=96, digest_length=64 ) -def test_the_store_format_is_marked_provisional() -> None: - """Tables are written in a draft format until the store is switched on, so a table +def test_the_table_format_is_marked_provisional() -> None: + """Tables are written in a draft format until the database is switched on, so a table of this format is told apart from one of the format eventually fixed.""" - assert names.STORE_FORMAT.endswith(".draft") + assert names.TABLE_FORMAT.endswith(".draft") def test_the_collision_error_names_the_table_its_caller_gives() -> None: """The caller that knows the table adds it; the reason stays readable on its own.""" - plain = names.SpiralStoreTableCollisionError("its record lacks ['orcapod.path']") - assert str(plain) == "not this store's table: its record lacks ['orcapod.path']" + plain = names.SpiralTableCollisionError("its record lacks ['orcapod.path']") + assert str(plain) == "not this database's table: its record lacks ['orcapod.path']" assert plain.table is None - placed = names.SpiralStoreTableCollisionError("x", table="p/d/o1_t") - assert str(placed) == "table p/d/o1_t: not this store's table: x" + placed = names.SpiralTableCollisionError("x", table="p/d/o1_t") + assert str(placed) == "table p/d/o1_t: not this database's table: x" assert (placed.reason, placed.table) == ("x", "p/d/o1_t") @@ -320,7 +325,7 @@ def test_the_collision_error_names_the_table_its_caller_gives() -> None: def _schema() -> pa.Schema: return pa.schema( [ - pa.field(spiral_store.KEY_COLUMN, pa.large_binary(), False), + pa.field(spiral_database_codec.KEY_COLUMN, pa.large_binary(), False), pa.field("x", pa.int64()), ] ) @@ -329,8 +334,8 @@ def _schema() -> pa.Schema: def _manifest_payload(path: object) -> bytes: """A manifest payload recording ``path``, as a writer outside the domain would.""" body = json.loads( - spiral_store.manifest_bytes( - spiral_store.new_manifest(("ok", "rdb_v1"), "k", _schema()) + spiral_database_codec.manifest_bytes( + spiral_database_codec.new_manifest(("ok", "rdb_v1"), "k", _schema()) ) ) body["record_path"] = path @@ -346,18 +351,21 @@ def test_the_record_and_the_manifest_refuse_the_same_paths( with pytest.raises(ValueError, match="path"): _ = store_table_names.require_store_path_domain(path) # pyright: ignore[reportArgumentType] # refused on purpose with pytest.raises(ValueError, match="path"): - _ = names.store_table_metadata(path, "std:v1:default") # pyright: ignore[reportArgumentType] # refused on purpose - with pytest.raises(spiral_store.UnstorableInSpiralError): - _ = spiral_store.new_manifest(path, "k", _schema()) # pyright: ignore[reportArgumentType] # refused on purpose + _ = names.table_identity_metadata(path, "std:v1:default") # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(spiral_database_codec.UnstorableInSpiralError): + _ = spiral_database_codec.new_manifest(path, "k", _schema()) # pyright: ignore[reportArgumentType] # refused on purpose record = { - **names.store_table_metadata(RESULT, "std:v1:default"), + **names.table_identity_metadata(RESULT, "std:v1:default"), "orcapod.path": json.dumps(list(path)).encode(), "orcapod.layout": (str(path[-1]) if path else "").encode("utf-8", "replace"), } - with pytest.raises(names.SpiralStoreTableCollisionError): - _ = names.read_store_table_metadata(record) - with pytest.raises(spiral_store.ManifestError): - _ = spiral_store.read_manifest_bytes(_manifest_payload(list(path)), path) # pyright: ignore[reportArgumentType] # refused on purpose + with pytest.raises(names.SpiralTableCollisionError): + _ = names.read_table_identity_metadata(record) + with pytest.raises(spiral_database_codec.ManifestError): + _ = spiral_database_codec.read_manifest_bytes( + _manifest_payload(list(path)), + path, # pyright: ignore[reportArgumentType] # refused on purpose + ) @pytest.mark.parametrize("path", _INSIDE) @@ -366,13 +374,13 @@ def test_the_record_and_the_manifest_accept_the_same_paths( ) -> None: """Finding 2: a path inside the domain is written and read back by both.""" assert store_table_names.require_store_path_domain(path) == path - found = names.read_store_table_metadata( - names.store_table_metadata(path, "std:v1:default") + found = names.read_table_identity_metadata( + names.table_identity_metadata(path, "std:v1:default") ) assert found is not None and found.path == path - manifest = spiral_store.new_manifest(path, "k", _schema()) - entries = spiral_store.manifest_entries(manifest) - assert spiral_store.read_manifest(entries, path) == manifest + manifest = spiral_database_codec.new_manifest(path, "k", _schema()) + entries = spiral_database_codec.manifest_entries(manifest) + assert spiral_database_codec.read_manifest(entries, path) == manifest # ------------------------------------- CodeRabbit review of PR 691 (216f1982d) @@ -408,46 +416,50 @@ def __getitem__(self, index: int | slice) -> str | Sequence[str]: def test_the_layout_is_the_last_component_of_the_path_recorded() -> None: - """Thread on spiral_store_identity.py:147: the layout is taken from the validated + """Thread on spiral_database_identity.py:147: the layout is taken from the validated snapshot of the path, so a path that reads differently later records one path.""" - record = names.store_table_metadata(_ShiftingPath(), "std:v1:default") - found = names.read_store_table_metadata(record) + record = names.table_identity_metadata(_ShiftingPath(), "std:v1:default") + found = names.read_table_identity_metadata(record) assert found is not None assert (found.path, found.layout) == (("base", "rdb_v1"), "rdb_v1") def test_the_record_keeps_the_order_of_its_path_components() -> None: - """Thread on test_spiral_store_identity.py:315: the same components in two orders + """Thread on test_spiral_database_identity.py:315: the same components in two orders are two recorded paths, each read back in the order given; the layout is fixed.""" first, second = ("base", "part", "rdb_v1"), ("part", "base", "rdb_v1") - one = names.store_table_metadata(first, "std:v1:default") - two = names.store_table_metadata(second, "std:v1:default") + one = names.table_identity_metadata(first, "std:v1:default") + two = names.table_identity_metadata(second, "std:v1:default") assert one[names.PATH_KEY] != two[names.PATH_KEY] assert one[names.LAYOUT_KEY] == two[names.LAYOUT_KEY] == b"rdb_v1" for path, record in ((first, one), (second, two)): - found = names.read_store_table_metadata(record) + found = names.read_table_identity_metadata(record) assert found is not None and found.path == path @pytest.mark.parametrize("kind", ["", "k", "é
"]) def test_a_manifest_kind_is_read_as_any_utf8_text(kind: str) -> None: - """Thread on spiral_store.py:937: an empty or non-ASCII kind still reads back.""" + """Thread on spiral_database_codec.py:937: an empty or non-ASCII kind still reads + back. + """ path = ("ok", "rdb_v1") - manifest = spiral_store.new_manifest(path, kind, _schema()) + manifest = spiral_database_codec.new_manifest(path, kind, _schema()) assert ( - spiral_store.read_manifest_bytes(spiral_store.manifest_bytes(manifest), path) + spiral_database_codec.read_manifest_bytes( + spiral_database_codec.manifest_bytes(manifest), path + ) == manifest ) def test_a_manifest_kind_with_no_utf8_form_is_refused_on_read() -> None: - """Thread on spiral_store.py:937: a JSON escape can give a kind with a lone + """Thread on spiral_database_codec.py:937: a JSON escape can give a kind with a lone surrogate, which ``new_manifest`` refuses; the reader refuses it too.""" path = ("ok", "rdb_v1") - payload = spiral_store.manifest_bytes( - spiral_store.new_manifest(path, "k", _schema()) + payload = spiral_database_codec.manifest_bytes( + spiral_database_codec.new_manifest(path, "k", _schema()) ) escaped = payload.replace(b'"kind":"k"', b'"kind":"\\udc00"') assert escaped != payload - with pytest.raises(spiral_store.ManifestError, match="kind"): - _ = spiral_store.read_manifest_bytes(escaped, path) + with pytest.raises(spiral_database_codec.ManifestError, match="kind"): + _ = spiral_database_codec.read_manifest_bytes(escaped, path) diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py index 0c3cc384a..424ce80b8 100644 --- a/tests/test_databases/test_spiral_lease.py +++ b/tests/test_databases/test_spiral_lease.py @@ -494,10 +494,10 @@ def lose_reply(table: fake.FakeKeyedTable, rows: pa.Table) -> fake.FakeKeyedTabl @pytest.mark.parametrize("reverse", [False, True]) -def test_numbered_lease_tables_are_hidden_but_store_tables_are_visible( +def test_numbered_lease_tables_are_hidden_but_database_tables_are_visible( client: fake.FakeClient, monkeypatch: pytest.MonkeyPatch, reverse: bool ) -> None: - """Generations are hidden from listings; store and look-alike tables stay visible + """Generations are hidden from listings; database and look-alike tables stay visible and cannot be cleared.""" holder = acquire(client, _PROJECT, _DATASET, owner="holder") lease_name = spiral_lease_table_name(1) diff --git a/tests/test_databases/test_spiraldb_connector_integration.py b/tests/test_databases/test_spiraldb_connector_integration.py index 010316e3d..bcfe89996 100644 --- a/tests/test_databases/test_spiraldb_connector_integration.py +++ b/tests/test_databases/test_spiraldb_connector_integration.py @@ -577,21 +577,21 @@ def upsert(name: str) -> None: assert made.get_metadata() == {"a": b"1", "b": b"1"} -# ------------------------------------------------ the store codec (ITL-1497) +# ------------------------------------------------ the database 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 + """Rows of a database table: names the codec escapes, and every kept kind of value.""" + from orcapod.databases import spiral_database_codec 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()), + spiral_database_codec.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]), @@ -635,33 +635,37 @@ def _codec_rows() -> pa.Table: return pa.table(columns) -def test_the_store_codec_round_trips(place: _Place) -> None: +def test_the_database_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 + from orcapod.databases import spiral_database_codec 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)]) + manifest = spiral_database_codec.new_manifest( + ("conformance", "rdb_v1"), "test", rows.schema + ) + encoded = spiral_database_codec.encode_rows(rows) + key = pa.schema( + [pa.field(spiral_database_codec.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 + place.dataset, "database_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) + decoded = spiral_database_codec.decode_rows(read_back, manifest) order = pa.array( sorted( range(decoded.num_rows), - key=lambda i: decoded[spiral_store.KEY_COLUMN][i].as_py(), + key=lambda i: decoded[spiral_database_codec.KEY_COLUMN][i].as_py(), ), pa.int64(), ) got = decoded.take(order) - want = rows.cast(spiral_store.logical_schema(rows.schema)) + want = rows.cast(spiral_database_codec.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() @@ -688,14 +692,14 @@ def test_the_store_codec_round_trips(place: _Place) -> None: ], ids=lambda t: f"{t.schema.names[0]!r}: {t.schema.types[0]}", ) -def test_what_the_store_codec_avoids_is_refused( +def test_what_the_database_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 + place.dataset, "database_codec_refusals", key, exist_ok=True ) n = column.num_rows rows = column.add_column( @@ -712,7 +716,7 @@ def test_a_duration_is_stored_and_read_back_as_given(place: _Place) -> None: and value (the fake's ``unsupported``; 0.16.78 refused it). Written to the table of the refusals above, which already holds this column and row: no new table.""" column = pa.table({"d": pa.array([1], pa.duration("s"))}) - got = _written_and_read(place, "store_codec_refusals", column) + got = _written_and_read(place, "database_codec_refusals", column) assert got.schema.field("d").type == pa.duration("s") assert got.column("d").to_pylist() == [dt.timedelta(seconds=1)] diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py similarity index 79% rename from tests/test_databases/test_spiraldb_store_mode.py rename to tests/test_databases/test_spiraldb_writable_mode.py index 7a054b8e9..bfdec8dd0 100644 --- a/tests/test_databases/test_spiraldb_store_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -1,10 +1,11 @@ -"""A SpiralDB connector in store mode, under ``ConnectorArrowDatabase`` (ITL-1840). +"""A SpiralDB connector in writable mode, under ``ConnectorArrowDatabase`` (ITL-1840). On the fake (``fake_spiral_sdk``); no live SpiralDB. A ``SpiralDBConnector`` built -with ``store=True``. Direct writes hold the dataset's writer lease for the whole test -(``store(held=True)``), as a job run does for its own (ITL-1844). The tests cover each table kind's -layout written and read back, the write rules of ITL-1386, refusals of tables that are -not the store's, the data-context checks and the listing the stale-layout check uses. +with ``writable=True``. Direct writes hold the dataset's writer lease for the whole test +(``writable_connector(held=True)``), as a job run does for its own (ITL-1844). The tests cover each +table kind's layout written and read back, the write rules of ITL-1386, refusals of +tables that are not the database's, the data-context checks and the listing the +stale-layout check uses. """ from __future__ import annotations @@ -27,11 +28,11 @@ from orcapod.core.operators import SelectDataColumns from orcapod.core.sources.cached_source import CachedSource from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector -from orcapod.databases import spiral_store as codec -from orcapod.databases import spiral_store_identity as identity -from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError -from orcapod.databases.spiraldb_store_tables import StoreTables -from orcapod.databases.spiraldb_write_scope import store_writes, take_lease +from orcapod.databases import spiral_database_codec as codec +from orcapod.databases import spiral_database_identity as identity +from orcapod.databases.spiral_database_identity import SpiralTableCollisionError +from orcapod.databases.spiraldb_tables import SpiralDBTables +from orcapod.databases.spiraldb_write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( InputValidationError, @@ -80,12 +81,12 @@ def _release_test_leases() -> None: raise failure -def store( +def writable_connector( project: str = "p", dataset: str = "d", *, held: bool = True ) -> SpiralDBConnector: - """A store connector; ``held`` writes it directly under the dataset's writer lease, + """A writable connector; ``held`` writes it directly under the dataset's writer lease, taken once per test (a job run takes its own: pass ``held=False``).""" - connector = SpiralDBConnector(project, dataset, store=True) + connector = SpiralDBConnector(project, dataset, writable=True) if held: lease = _test_leases.get((project, dataset)) if lease is None: @@ -95,8 +96,8 @@ def store( return connector -def tables_of(connector: SpiralDBConnector) -> StoreTables: - tables = connector._store_tables() # pyright: ignore[reportPrivateUsage] +def tables_of(connector: SpiralDBConnector) -> SpiralDBTables: + tables = connector._writable_tables() # pyright: ignore[reportPrivateUsage] assert tables is not None return tables @@ -143,7 +144,7 @@ def _tables() -> list[dict[str, Any]]: @pytest.mark.usefixtures("root") def test_rows_round_trip() -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) written = rows(["r1", "r0", "r2"]) db.add_records(RESULT, written, record_id_column="__record_id") assert db.table_exists(RESULT) # pending @@ -162,14 +163,14 @@ def test_rows_round_trip() -> None: @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 = ConnectorArrowDatabase(writable_connector()).at("team", "store") db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") db.flush() full = ("team", "store", *RESULT) - table = _table(identity.spiral_store_table_name(full)) + table = _table(identity.spiral_table_name(full)) metadata = table.get_metadata() - record = identity.read_store_table_metadata(metadata) - assert record == identity.StoreTableRecord(full, "rdb_v1", CONTEXT) + record = identity.read_table_identity_metadata(metadata) + assert record == identity.TableRecord(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 @@ -179,19 +180,19 @@ def test_the_table_is_named_from_its_full_path_and_records_it() -> None: @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_v2") - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(long_path, rows(["r0"]), record_id_column="__record_id") db.flush() - assert len(identity.spiral_store_table_name(long_path)) <= 164 + assert len(identity.spiral_table_name(long_path)) <= 164 assert db.list_table_paths(("f" * 300,)) == [long_path] @pytest.mark.usefixtures("root") def test_a_new_connector_reads_what_another_wrote() -> None: - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, rows(["r0"]), record_id_column="__record_id", flush=True ) - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(writable_connector()) 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 @@ -201,13 +202,13 @@ def test_a_new_connector_reads_what_another_wrote() -> None: @pytest.mark.parametrize("order", ["as_written", "reversed"]) def test_rows_with_the_columns_in_another_order_append(order: str) -> None: """Columns match by name: an append with the columns in any order is one table.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) second = rows(["r1"], offset=10) if order == "reversed": second = second.select(list(reversed(second.column_names))) db.add_records(RESULT, second, record_id_column="__record_id", flush=True) - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None @@ -225,7 +226,7 @@ def test_rows_with_the_columns_in_another_order_append(order: str) -> None: def test_a_stored_id_is_refused_without_buffering_other_rows() -> None: """A write to a stored id raises unless ``skip_duplicates``; nothing of the add is buffered.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0", "r1"]), record_id_column="__record_id") db.flush() with pytest.raises(ValueError, match="already exist.*stored"): @@ -245,7 +246,7 @@ def test_a_stored_id_is_refused_without_buffering_other_rows() -> None: @pytest.mark.usefixtures("root") def test_a_pending_id_is_refused_unless_skipped() -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") with pytest.raises(ValueError, match="already exist in the pending batch"): db.add_records(RESULT, rows(["r0"], offset=5), record_id_column="__record_id") @@ -266,7 +267,7 @@ def test_a_pending_id_is_refused_unless_skipped() -> None: @pytest.mark.usefixtures("root") def test_skip_duplicates_keeps_stored_rows_and_writes_the_rest() -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) 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") @@ -287,8 +288,8 @@ def test_an_id_another_writer_stored_since_the_add_keeps_its_first_commit( ) -> None: """Accepted when added, stored by another writer before this flush: the stored row is kept (a SpiralDB append would replace it), the other keys are written.""" - a = ConnectorArrowDatabase(store()) - b = ConnectorArrowDatabase(store()) + a = ConnectorArrowDatabase(writable_connector()) + b = ConnectorArrowDatabase(writable_connector()) b.add_records(RESULT, rows(["seed"]), record_id_column="__record_id", flush=True) a.add_records( RESULT, @@ -298,7 +299,7 @@ def test_an_id_another_writer_stored_since_the_add_keeps_its_first_commit( ) b.add_records(RESULT, rows(["x"]), record_id_column="__record_id", flush=True) a.flush() - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None @@ -319,7 +320,7 @@ def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> N """``existing_record_ids``: one scan of the key column alone, with no filter (no range: how the service orders binary values is not relied on), and a set intersection.""" - connector = store() + connector = writable_connector() db = ConnectorArrowDatabase(connector) db.add_records( RESULT, rows(["r0", "r1", "r2", "r3"]), record_id_column="__record_id" @@ -340,10 +341,10 @@ def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> N @pytest.mark.usefixtures("root") def test_another_schema_is_refused() -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) 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()) + fresh = ConnectorArrowDatabase(writable_connector()) with pytest.raises((ValueError, InputValidationError), match="(?i)schema|column"): fresh.add_records(RESULT, other, record_id_column="__record_id", flush=True) @@ -351,7 +352,7 @@ def test_another_schema_is_refused() -> None: @pytest.mark.usefixtures("root") def test_a_column_of_other_field_metadata_is_refused_on_append() -> None: """Storage metadata must match on append (ITL-1334, ITL-1386).""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) first = rows(["r0"]) field = first.schema.field("a.b").with_metadata({"unit": "m"}) first = first.set_column(2, field, first.column("a.b")) @@ -360,7 +361,7 @@ def test_a_column_of_other_field_metadata_is_refused_on_append() -> None: other = second.schema.field("a.b").with_metadata({"unit": "s"}) second = second.set_column(2, other, second.column("a.b")) with pytest.raises(InputValidationError, match="a.b"): - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, second, record_id_column="__record_id" ) @@ -380,10 +381,10 @@ def test_a_column_of_other_field_metadata_is_refused_on_append() -> None: 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( +def test_rows_the_database_cannot_keep_are_refused_before_anything_is_written( bad: pa.Table, ) -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises((ValueError, codec.UnstorableInSpiralError)): db.add_records(RESULT, bad, record_id_column="__record_id") assert _tables() == [] @@ -394,7 +395,7 @@ def test_a_column_the_codec_cannot_keep_is_named_by_require_storable() -> None: """A job attaching the database is refused before it runs, naming the column.""" from orcapod.errors import UnstorableColumnError - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(UnstorableColumnError, match="d"): db.require_storable(pa.schema([pa.field("d", pa.duration("s"))])) db.require_storable(rows(["r0"]).schema) @@ -420,34 +421,34 @@ def _make_table(name: str, metadata: dict[str, bytes], *, with_rows: bool) -> No def test_a_table_of_another_path_under_the_name_is_refused() -> None: other = ("another", "rdb_v1") _make_table( - identity.spiral_store_table_name(RESULT), - identity.store_table_metadata(other, CONTEXT), + identity.spiral_table_name(RESULT), + identity.table_identity_metadata(other, CONTEXT), with_rows=False, ) - db = ConnectorArrowDatabase(store()) - with pytest.raises(SpiralStoreTableCollisionError, match="another"): + db = ConnectorArrowDatabase(writable_connector()) + with pytest.raises(SpiralTableCollisionError, match="another"): _ = db.table_exists(RESULT) - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) @pytest.mark.usefixtures("root") def test_a_foreign_table_with_rows_and_no_record_is_refused() -> None: - _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) - db = ConnectorArrowDatabase(store()) - with pytest.raises(SpiralStoreTableCollisionError, match="no store manifest"): + _make_table(identity.spiral_table_name(RESULT), {}, with_rows=True) + db = ConnectorArrowDatabase(writable_connector()) + with pytest.raises(SpiralTableCollisionError, match="no table manifest"): _ = db.table_exists(RESULT) - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): _ = db.get_all_records(RESULT) - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") @pytest.mark.usefixtures("root") def test_an_empty_table_without_a_record_is_adopted() -> None: """A creation that stopped before the first write.""" - _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) - db = ConnectorArrowDatabase(store()) + _make_table(identity.spiral_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(writable_connector()) 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") @@ -466,10 +467,10 @@ def test_an_empty_table_without_a_record_is_adopted() -> None: def test_an_empty_table_with_another_key_is_refused_untouched( key: "pa.Field[Any]", ) -> None: - name = identity.spiral_store_table_name(RESULT) + name = identity.spiral_table_name(RESULT) _ = _client().project("p").create_keyed_table("d", name, pa.schema([key])) - db = ConnectorArrowDatabase(store()) - with pytest.raises(SpiralStoreTableCollisionError, match="key"): + db = ConnectorArrowDatabase(writable_connector()) + with pytest.raises(SpiralTableCollisionError, match="key"): db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert _table(name).get_metadata() == {} @@ -477,7 +478,7 @@ def test_an_empty_table_with_another_key_is_refused_untouched( @pytest.mark.usefixtures("root") def test_a_path_too_long_to_record_is_refused_before_any_table_is_made() -> None: path = ("x" * 9000, "rdb_v1") - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(ValueError, match="path|entry"): db.add_records(path, rows(["r0"]), record_id_column="__record_id", flush=True) assert _tables() == [] @@ -490,18 +491,18 @@ def test_a_recorded_table_with_no_rows_is_new_to_any_first_writer() -> None: other = rows(["r0"]).drop_columns(["s"]) manifest = codec.new_manifest(RESULT, "rdb_v1", other.schema) _make_table( - identity.spiral_store_table_name(RESULT), + identity.spiral_table_name(RESULT), { - **identity.store_table_metadata(RESULT, CONTEXT), + **identity.table_identity_metadata(RESULT, CONTEXT), **codec.manifest_entries(manifest), }, with_rows=False, ) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) assert not db.table_exists(RESULT) written = rows(["r0", "r1"]) db.add_records(RESULT, written, record_id_column="__record_id", flush=True) - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None and by_id(got).equals(by_id(written)) @@ -517,14 +518,14 @@ def test_a_recorded_empty_table_with_a_corrupt_manifest_is_refused() -> None: **entries, f"{codec.MANIFEST_KEY}/0": entries[f"{codec.MANIFEST_KEY}/0"] + b" ", } - name = identity.spiral_store_table_name(RESULT) + name = identity.spiral_table_name(RESULT) _make_table( name, - {**identity.store_table_metadata(RESULT, CONTEXT), **corrupt}, + {**identity.table_identity_metadata(RESULT, CONTEXT), **corrupt}, with_rows=False, ) - db = ConnectorArrowDatabase(store()) - with pytest.raises(SpiralStoreTableCollisionError): + db = ConnectorArrowDatabase(writable_connector()) + with pytest.raises(SpiralTableCollisionError): db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id", flush=True) assert ( _table(name).get_metadata()[f"{codec.MANIFEST_KEY}/0"] @@ -542,9 +543,9 @@ def test_a_data_context_this_orcapod_cannot_resolve_is_refused_before_anything( ) -> None: """A table recording a data context key no reader can resolve would be unreadable: such rows (an unknown key, or a short one) are refused when they are added, before - they are buffered, and by a write that reaches the store directly, before any table + they are buffered, and by a write that reaches the database directly, before any table is created.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(InputValidationError, match="data context"): db.add_records( RESULT, rows(["r0"], context=context), record_id_column="__record_id" @@ -552,7 +553,7 @@ def test_a_data_context_this_orcapod_cannot_resolve_is_refused_before_anything( assert not db.table_exists(RESULT) assert db.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") is None db.flush() - tables = tables_of(store()) + tables = tables_of(writable_connector()) name = tables.table_name(RESULT) with pytest.raises(InputValidationError, match="data context"): tables.write(name, rows(["r0"], context=context)) @@ -563,7 +564,7 @@ def test_a_data_context_this_orcapod_cannot_resolve_is_refused_before_anything( def test_two_data_contexts_buffered_for_one_table_are_refused_before_it_is_made() -> ( None ): - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") with pytest.raises(InputValidationError, match="data context"): db.add_records( @@ -577,26 +578,26 @@ def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> """Rows of another data context than the table records are refused when they are added (naming both keys), before they are buffered: a flush asked for with them writes nothing, not even another table's pending batch.""" - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, rows(["old"]), record_id_column="__record_id", flush=True ) recorded = "std:v0:legacy" - _table(identity.spiral_store_table_name(RESULT)).set_metadata( - identity.store_table_metadata(RESULT, recorded) + _table(identity.spiral_table_name(RESULT)).set_metadata( + identity.table_identity_metadata(RESULT, recorded) ) other = (*RESULT[:-1], "rdb_v9") - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(other, rows(["valid"]), record_id_column="__record_id") with pytest.raises(InputValidationError) as raised: db.add_records( RESULT, rows(["bad"]), record_id_column="__record_id", flush=True ) assert recorded in str(raised.value) and CONTEXT in str(raised.value) - assert not ConnectorArrowDatabase(store()).table_exists(other) + assert not ConnectorArrowDatabase(writable_connector()).table_exists(other) assert db.table_exists(other) db.flush() - assert ConnectorArrowDatabase(store()).table_exists(other) - stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + assert ConnectorArrowDatabase(writable_connector()).table_exists(other) + stored = _client().keyed_table("p", "d", identity.spiral_table_name(RESULT)) keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() assert keys == [b"old"] @@ -605,19 +606,19 @@ def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> def test_a_table_of_another_data_context_made_after_buffering_is_refused_at_flush() -> ( None ): - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["mine"]), record_id_column="__record_id") - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, rows(["old"]), record_id_column="__record_id", flush=True ) recorded = "std:v0:legacy" - _table(identity.spiral_store_table_name(RESULT)).set_metadata( - identity.store_table_metadata(RESULT, recorded) + _table(identity.spiral_table_name(RESULT)).set_metadata( + identity.table_identity_metadata(RESULT, recorded) ) with pytest.raises(InputValidationError) as raised: db.flush() assert recorded in str(raised.value) and CONTEXT in str(raised.value) - stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + stored = _client().keyed_table("p", "d", identity.spiral_table_name(RESULT)) keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() assert keys == [b"old"] @@ -628,7 +629,7 @@ def test_logical_types_are_read_with_the_data_context_the_table_records( ) -> None: import orcapod.contexts as contexts - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) asked: list[object] = [] real = contexts.resolve_context @@ -638,7 +639,7 @@ def resolve(context_info: Any = None) -> Any: return real(context_info) monkeypatch.setattr(contexts, "resolve_context", resolve) - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(writable_connector()) assert fresh.get_all_records(RESULT, record_id_column="__record_id") is not None assert CONTEXT in asked @@ -667,12 +668,12 @@ def _with_path_column(table: pa.Table, *, live: bool) -> pa.Table: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("first_live", [True, False]) def test_a_logical_type_live_or_in_storage_form_is_one_column(first_live: bool) -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) first = _with_path_column(rows(["r0"]), live=first_live) second = _with_path_column(rows(["r1"]), live=not first_live) db.add_records(RESULT, first, record_id_column="__record_id", flush=True) db.add_records(RESULT, second, record_id_column="__record_id", flush=True) - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None and got.num_rows == 2 @@ -690,9 +691,9 @@ def test_a_storage_form_identifier_no_type_is_registered_for_is_kept_as_given() }, ) table = rows(["r0"]).append_column(field, pa.array(["x"], pa.large_string())) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, table, record_id_column="__record_id", flush=True) - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None @@ -718,7 +719,7 @@ def test_a_storage_form_identifier_no_type_is_registered_for_is_kept_as_given() @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ["forward", "reversed"]) def test_tables_are_listed_by_their_recorded_paths(order: str) -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) for path in PATHS if order == "forward" else list(reversed(PATHS)): db.add_records(path, rows(["r0"]), record_id_column="__record_id") db.flush() @@ -740,7 +741,7 @@ def test_tables_are_listed_by_their_recorded_paths(order: str) -> None: @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()) + db = ConnectorArrowDatabase(writable_connector()) for path in PATHS: db.add_records(path, rows(["r0"]), record_id_column="__record_id") db.flush() @@ -755,36 +756,36 @@ def test_stale_layouts_are_found_by_their_recorded_paths() -> None: def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: _make_table( "o1_my_fn_" + "0" * 64, - identity.store_table_metadata(RESULT, CONTEXT), + identity.table_identity_metadata(RESULT, CONTEXT), with_rows=True, ) - with pytest.raises(SpiralStoreTableCollisionError, match="another name"): - _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + with pytest.raises(SpiralTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) -OTHER_FORMAT = "orcapod.spiral_store.v1" +OTHER_FORMAT = "orcapod.spiral_database.v1" OTHER = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") OTHER_LISTED = (*OTHER[:-1], f"rdb_v1/{OTHER_FORMAT}") def _make_other_format_table(path: tuple[str, ...]) -> None: - """A table of another store format, its record complete and readable.""" + """A table of another table format, its record complete and readable.""" metadata = { - **identity.store_table_metadata(path, CONTEXT), - identity.STORE_KEY: OTHER_FORMAT.encode(), + **identity.table_identity_metadata(path, CONTEXT), + identity.FORMAT_KEY: OTHER_FORMAT.encode(), } - _make_table(identity.spiral_store_table_name(path), metadata, with_rows=True) + _make_table(identity.spiral_table_name(path), metadata, with_rows=True) @pytest.mark.usefixtures("root") @pytest.mark.parametrize("order", ["current_first", "other_first"]) -def test_a_table_of_another_store_format_is_listed_with_a_marked_last_component( +def test_a_table_of_another_table_format_is_listed_with_a_marked_last_component( order: str, ) -> None: """Only that table is marked; the listing of the others goes on.""" current = ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") outside = ("my_fnx", H, "rdb_v1") - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) if order == "other_first": _make_other_format_table(OTHER) _make_other_format_table(outside) @@ -799,18 +800,18 @@ def test_a_table_of_another_store_format_is_listed_with_a_marked_last_component( @pytest.mark.usefixtures("root") -def test_the_whole_store_lists_a_table_of_another_store_format() -> None: +def test_the_whole_database_lists_a_table_of_another_table_format() -> None: _make_other_format_table(OTHER) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(PATHS[3], rows(["r0"]), record_id_column="__record_id", flush=True) assert db.list_table_paths() == sorted([OTHER_LISTED, PATHS[3]]) @pytest.mark.usefixtures("root") -def test_a_table_of_another_store_format_is_a_stale_table() -> None: +def test_a_table_of_another_table_format_is_a_stale_table() -> None: """A side-effect node refuses before acting; any other node reports and runs.""" _make_other_format_table(OTHER) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [ OTHER_LISTED ] @@ -826,12 +827,12 @@ def test_a_table_of_another_store_format_is_a_stale_table() -> None: @pytest.mark.usefixtures("root") -def test_a_table_of_another_store_format_opened_by_its_path_is_refused() -> None: +def test_a_table_of_another_table_format_opened_by_its_path_is_refused() -> None: _make_other_format_table(OTHER) - db = ConnectorArrowDatabase(store()) - with pytest.raises(SpiralStoreTableCollisionError, match="format"): + db = ConnectorArrowDatabase(writable_connector()) + with pytest.raises(SpiralTableCollisionError, match="format"): _ = db.table_exists(OTHER) - with pytest.raises(SpiralStoreTableCollisionError, match="format"): + with pytest.raises(SpiralTableCollisionError, match="format"): db.add_records(OTHER, rows(["r0"]), record_id_column="__record_id", flush=True) @@ -848,46 +849,89 @@ def test_a_table_of_another_store_format_opened_by_its_path_is_refused() -> None ], ids=["table_exists", "get_all_records", "get_table_schema", "add_records"], ) -def test_a_listed_path_of_another_store_format_cannot_be_opened(open_: Any) -> None: +def test_a_listed_path_of_another_table_format_cannot_be_opened(open_: Any) -> None: _make_other_format_table(OTHER) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) for listed in (db.list_table_paths(("my_fn",)), db.list_table_paths()): assert listed == [OTHER_LISTED] - with pytest.raises(ValueError, match="another store format") as raised: + with pytest.raises(ValueError, match="another table format") as raised: _ = open_(db, OTHER_LISTED) assert OTHER_FORMAT in str(raised.value) - assert not isinstance(raised.value, SpiralStoreTableCollisionError) + assert not isinstance(raised.value, SpiralTableCollisionError) + + +EARLIER_DRAFT_FORMAT = "orcapod.spiral_store.draft" + + +def _make_earlier_draft_table(path: tuple[str, ...], *, old_key: bool) -> None: + """A table written by an earlier draft of the format: its format value, under the + earlier draft's key (``old_key``) or the current one.""" + metadata = dict(identity.table_identity_metadata(path, CONTEXT)) + if old_key: + del metadata[identity.FORMAT_KEY] + key = identity.EARLIER_DRAFT_FORMAT_KEY if old_key else identity.FORMAT_KEY + metadata[key] = EARLIER_DRAFT_FORMAT.encode() + _make_table(identity.spiral_table_name(path), metadata, with_rows=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("old_key", [False, True], ids=["old value", "old key"]) +def test_a_table_of_an_earlier_draft_is_another_format_never_read_or_written( + old_key: bool, +) -> None: + """A table recording ``orcapod.spiral_store.draft``, under ``orcapod.table_format`` + or under the earlier draft's key ``orcapod.store``: listed as another table format, + refused when opened, its metadata and rows unchanged.""" + _make_earlier_draft_table(OTHER, old_key=old_key) + name = identity.spiral_table_name(OTHER) + metadata = _table(name).get_metadata() + before = _table(name).scan(["__record_id", "v"]).to_table() + db = ConnectorArrowDatabase(writable_connector()) + listed = (*OTHER[:-1], f"rdb_v1/{EARLIER_DRAFT_FORMAT}") + assert db.list_table_paths(("my_fn",)) == [listed] + assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [listed] + refusal = f"its format is b'{EARLIER_DRAFT_FORMAT}'" + with pytest.raises(SpiralTableCollisionError, match=refusal): + _ = db.table_exists(OTHER) + with pytest.raises(SpiralTableCollisionError, match=refusal): + _ = db.get_all_records(OTHER) + with pytest.raises(SpiralTableCollisionError, match=refusal): + db.add_records(OTHER, rows(["r0"]), record_id_column="__record_id", flush=True) + with pytest.raises(ValueError, match="another table format"): + _ = db.get_all_records(listed) + assert _table(name).get_metadata() == metadata + assert _table(name).scan(["__record_id", "v"]).to_table().equals(before) @pytest.mark.usefixtures("root") @pytest.mark.parametrize( "metadata", [ - {identity.STORE_KEY: OTHER_FORMAT.encode()}, + {identity.FORMAT_KEY: OTHER_FORMAT.encode()}, { - **identity.store_table_metadata(OTHER, CONTEXT), - identity.STORE_KEY: OTHER_FORMAT.encode(), + **identity.table_identity_metadata(OTHER, CONTEXT), + identity.FORMAT_KEY: OTHER_FORMAT.encode(), identity.PATH_KEY: b"[not json", }, { - **identity.store_table_metadata(OTHER, CONTEXT), - identity.STORE_KEY: b"\xff\xfe", + **identity.table_identity_metadata(OTHER, CONTEXT), + identity.FORMAT_KEY: b"\xff\xfe", }, ], ids=["partial", "unreadable_path", "undecodable_format"], ) -def test_a_doubtful_record_of_another_store_format_still_refuses_the_listing( +def test_a_doubtful_record_of_another_table_format_still_refuses_the_listing( metadata: dict[str, bytes], ) -> None: - _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) - with pytest.raises(SpiralStoreTableCollisionError): - _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + _make_table(identity.spiral_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralTableCollisionError): + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) @pytest.mark.usefixtures("root") def test_a_table_listed_before_its_record_is_listed_after_it() -> None: - _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) - db = ConnectorArrowDatabase(store()) + _make_table(identity.spiral_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(writable_connector()) assert db.list_table_paths(("my_fn",)) == [] db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert db.list_table_paths(("my_fn",)) == [RESULT] @@ -904,18 +948,18 @@ def _rename(table_name: str, new_name: str) -> None: @pytest.mark.usefixtures("root") def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) assert db.list_table_paths(("my_fn",)) == [RESULT] other = (*RESULT[:-1], "rdb_v9") _rename( - identity.spiral_store_table_name(RESULT), - identity.spiral_store_table_name(other), + identity.spiral_table_name(RESULT), + identity.spiral_table_name(other), ) - with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + with pytest.raises(SpiralTableCollisionError, match="another name"): _ = db.list_table_paths(("my_fn",)) - with pytest.raises(SpiralStoreTableCollisionError, match="another name"): - _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + with pytest.raises(SpiralTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) # ------------------------------------------------------ concurrent first writers @@ -937,12 +981,12 @@ def other_first(table_name: str) -> Any: def _interleaved(first_rows: pa.Table, second_rows: pa.Table) -> Any: """Writer 1 judges the table absent; writer 2 then creates and fills it; then writer 1 goes on. Returns writer 1's database.""" - first = store() + first = writable_connector() db1 = ConnectorArrowDatabase(first) db1.add_records(RESULT, first_rows, record_id_column="__record_id") def the_other_writer(_: str) -> None: - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, second_rows, record_id_column="__record_id", flush=True ) @@ -958,9 +1002,9 @@ def _reordered(table: pa.Table) -> pa.Table: def test_a_writer_never_overwrites_another_writers_manifest() -> None: other_schema = rows(["b0"]).drop_columns(["s"]) db1 = _interleaved(rows(["a0"]), other_schema) - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): db1.flush() - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None and by_id(got).equals(by_id(other_schema)) @@ -979,30 +1023,30 @@ def test_a_writer_of_an_equivalent_manifest_appends_beside_another( other = _reordered(other) db1 = _interleaved(first, other) db1.flush() - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None assert set(got["__record_id"].to_pylist()) == {b"a0", b"b0"} # The writer's own connector reads the columns as the table records them. mine = db1.get_table_schema(RESULT) - fresh = ConnectorArrowDatabase(store()).get_table_schema(RESULT) + fresh = ConnectorArrowDatabase(writable_connector()).get_table_schema(RESULT) assert mine is not None and fresh is not None and mine.names == fresh.names @pytest.mark.usefixtures("root") def test_an_identity_of_another_path_made_meanwhile_is_never_recorded_over() -> None: - other = identity.store_table_metadata(("another", "rdb_v1"), CONTEXT) - connector = store() + other = identity.table_identity_metadata(("another", "rdb_v1"), CONTEXT) + connector = writable_connector() db = ConnectorArrowDatabase(connector) db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id") _made_meanwhile(connector, lambda name: _make_table(name, other, with_rows=False)) - with pytest.raises(SpiralStoreTableCollisionError, match="another"): + with pytest.raises(SpiralTableCollisionError, match="another"): db.flush() - metadata = _table(identity.spiral_store_table_name(RESULT)).get_metadata() - assert identity.read_store_table_metadata( + metadata = _table(identity.spiral_table_name(RESULT)).get_metadata() + assert identity.read_table_identity_metadata( metadata - ) == identity.read_store_table_metadata(other) + ) == identity.read_table_identity_metadata(other) assert codec.MANIFEST_KEY not in metadata @@ -1011,7 +1055,7 @@ def test_an_identity_of_another_path_made_meanwhile_is_never_recorded_over() -> def test_a_first_writer_keeps_the_rows_another_writer_stored_meanwhile( skip_duplicates: bool, ) -> None: - connector = store() + connector = writable_connector() db = ConnectorArrowDatabase(connector) db.add_records( RESULT, @@ -1021,13 +1065,13 @@ def test_a_first_writer_keeps_the_rows_another_writer_stored_meanwhile( ) def the_other_writer(_: str) -> None: - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, rows(["r1"]), record_id_column="__record_id", flush=True ) _made_meanwhile(connector, the_other_writer) db.flush() - got = ConnectorArrowDatabase(store()).get_all_records( + got = ConnectorArrowDatabase(writable_connector()).get_all_records( RESULT, record_id_column="__record_id" ) assert got is not None @@ -1039,8 +1083,8 @@ def the_other_writer(_: str) -> None: @pytest.mark.usefixtures("root") -def test_raw_access_is_refused_in_store_mode() -> None: - connector = store() +def test_raw_access_is_refused_in_database_mode() -> None: + connector = writable_connector() for call in ( lambda: connector.lookup_table("x"), lambda: list(connector.scan_batches("x")), @@ -1049,7 +1093,7 @@ def test_raw_access_is_refused_in_store_mode() -> None: lambda: connector.get_column_info("x"), lambda: connector.get_arrow_schema("x"), ): - with pytest.raises(ValueError, match="store-mode"): + with pytest.raises(ValueError, match="writable"): _ = call() for write in ( lambda: connector.create_table_if_not_exists("x", [], "__record_id"), @@ -1073,12 +1117,14 @@ def test_a_plain_connector_still_writes_nothing() -> None: @pytest.mark.usefixtures("root") -def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() -> None: - connector = store() +def test_a_closed_writable_connector_refuses_every_call_and_releases_its_tables() -> ( + None +): + connector = writable_connector() db = ConnectorArrowDatabase(connector) shared = connector.share_client() connector.close() - assert connector._store is None # pyright: ignore[reportPrivateUsage] + assert connector._tables is None # pyright: ignore[reportPrivateUsage] for call in ( lambda: db.table_exists(RESULT), lambda: db.list_table_paths(), @@ -1087,8 +1133,8 @@ def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() - ): with pytest.raises(RuntimeError, match="closed"): _ = call() - # the connector sharing its client keeps its own reference; it has its own store - # tables, so the test's lease is attached to them too (as a run attaches it) + # the connector sharing its client keeps its own reference; it has its own + # database tables, so the test's lease is attached to them too (as a run attaches it) tables_of(shared).hold_lease(_test_leases[("p", "d")][0]) other = ConnectorArrowDatabase(shared) other.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) @@ -1097,17 +1143,19 @@ def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() - @pytest.mark.usefixtures("root") def test_an_existing_empty_table_is_read_as_no_rows() -> None: - connector = store() + connector = writable_connector() tables = tables_of(connector) name = tables.table_name(RESULT) with pytest.raises(KeyError): _ = list(tables.scan(name)) - _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) - fresh = tables_of(store()) + _make_table( + name, identity.table_identity_metadata(RESULT, CONTEXT), with_rows=False + ) + fresh = tables_of(writable_connector()) assert fresh.table_name(RESULT) == name assert not fresh.has_table(name) assert list(fresh.scan(name)) == [] - assert ConnectorArrowDatabase(store()).get_all_records(RESULT) is None + assert ConnectorArrowDatabase(writable_connector()).get_all_records(RESULT) is None # ------------------------------------------------- every table kind, end to end @@ -1171,14 +1219,14 @@ def _cleared() -> Iterator[None]: @pytest.mark.parametrize("orchestrator", ["sync", "async"]) def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(store(held=False)) + database = ConnectorArrowDatabase(writable_connector(held=False)) _ = _job(database, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) # A cached source read outside a job run writes under a lease held here. - with store_writes([database], owner="test"): + with database_writes([database], owner="test"): cached = _cached(database).as_table() assert sorted(calls) == [1, 2, 3] and sorted(delivered) == [2, 4, 6] - fresh = ConnectorArrowDatabase(store(held=False)) + fresh = ConnectorArrowDatabase(writable_connector(held=False)) paths = fresh.list_table_paths() assert sorted(p[-1] for p in paths) == sorted(LAYOUTS) for path in paths: @@ -1194,7 +1242,7 @@ def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: assert calls == [] and delivered == [] assert sorted(again.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] assert sorted(again.nodes["sel"].as_table()["double"].to_pylist()) == [2, 4, 6] - with store_writes([fresh], owner="test"): + with database_writes([fresh], owner="test"): assert _cached(fresh).as_table().equals(cached) @@ -1204,7 +1252,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( orchestrator: str, ) -> None: run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} - database = ConnectorArrowDatabase(store(held=False)) + database = ConnectorArrowDatabase(writable_connector(held=False)) _ = _job(database, SOURCE_ROWS[:2]).run(orchestrator=run[orchestrator]()) before = { p: database.get_all_records(p, record_id_column="__rid") @@ -1215,7 +1263,7 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( assert sorted(p[-1] for p in before) == sorted(k for k in LAYOUTS if k != "sdb_v2") calls.clear() delivered.clear() - fresh = ConnectorArrowDatabase(store(held=False)) + fresh = ConnectorArrowDatabase(writable_connector(held=False)) _ = _job(fresh, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) assert calls == [3] and delivered == [6] for path, earlier in before.items(): @@ -1235,12 +1283,12 @@ def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( ids=["empty", "slash", "nul", "not utf-8"], ) @pytest.mark.parametrize("where", ["record path", "base path"]) -def test_a_path_outside_the_store_path_domain_is_refused_before_anything( +def test_a_path_outside_the_database_path_domain_is_refused_before_anything( component: str, where: str ) -> None: - """The store applies the one path domain its identity record and manifest apply + """The database applies the one path domain its identity record and manifest apply (``require_store_path_domain``), in the record path and in the base path alike.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(ValueError, match="component"): if where == "record path": db.add_records( @@ -1275,7 +1323,7 @@ def _binary_ids(ids: list[bytes], *, offset: int = 0) -> pa.Table: def _signed_byte_order(monkeypatch: pytest.MonkeyPatch) -> None: """Make the fake compare binary values as signed bytes, not unsigned: a service - order the store must not rely on.""" + order the database must not rely on.""" unsigned = fake._ordered # pyright: ignore[reportPrivateUsage] def ordered(value: Any) -> Any: @@ -1309,7 +1357,7 @@ def test_stored_ids_are_found_whatever_order_the_service_gives_binary_values( binary values in another order than Python's never hides a stored id; no stored row is replaced, strict or skipping duplicates, in either input order.""" _signed_byte_order(monkeypatch) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) original = _binary_ids(ids) _add(db, original, flush=True) again = _binary_ids(ids, offset=100) @@ -1318,7 +1366,7 @@ def test_stored_ids_are_found_whatever_order_the_service_gives_binary_values( else: with pytest.raises(ValueError, match="already exist"): _add(db, again) - for reader in (db, ConnectorArrowDatabase(store())): + for reader in (db, ConnectorArrowDatabase(writable_connector())): got = _get(reader) assert got is not None and by_id(got).equals(by_id(original)) @@ -1329,12 +1377,12 @@ def test_a_failed_first_append_leaves_no_table_known( ) -> None: """Finding 2: a first write whose append fails keeps nothing: the writer judges the table again, as a fresh one does (recorded, no rows: new).""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with monkeypatch.context() as patch: _failing_append(patch, after_commit=False) with pytest.raises(fake.SpiralError, match="injected append failure"): _add(db, rows(["r0"]), flush=True) - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(writable_connector()) assert _get(db) is None and _get(fresh) is None assert not db.table_exists(RESULT) and not fresh.table_exists(RESULT) @@ -1345,12 +1393,12 @@ def test_a_failed_first_append_lets_another_writer_record_the_table_anew( ) -> None: """Finding 2: after a failed first append, another writer records the empty table with other columns; the first writer reads the table as that writer recorded it.""" - first = ConnectorArrowDatabase(store()) + first = ConnectorArrowDatabase(writable_connector()) with monkeypatch.context() as patch: _failing_append(patch, after_commit=False) with pytest.raises(fake.SpiralError, match="injected append failure"): _add(first, rows(["r0"]), flush=True) - second = ConnectorArrowDatabase(store()) + second = ConnectorArrowDatabase(writable_connector()) other = rows(["r1"]).rename_columns( ["__record_id", "__data_context", "other", "__pod_ts", "s"] ) @@ -1369,7 +1417,7 @@ def test_an_append_stored_before_its_error_reached_the_client_is_judged_again( """Finding 2: the service stored the rows, then the append raised. Nothing kept from before the error is trusted: the rows are found, and are never stored twice or replaced.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) if not first_write: _add(db, rows(["r0"]), flush=True) given = rows(["r1"], offset=10) @@ -1378,12 +1426,12 @@ def test_an_append_stored_before_its_error_reached_the_client_is_judged_again( with pytest.raises(fake.SpiralError, match="injected append failure"): _add(db, given, flush=True) expected = given if first_write else pa.concat_tables([rows(["r0"]), given]) - for reader in (db, ConnectorArrowDatabase(store())): + for reader in (db, ConnectorArrowDatabase(writable_connector())): assert reader.table_exists(RESULT) got = _get(reader) assert got is not None and by_id(got).equals(by_id(expected)) with pytest.raises(ValueError, match="already exist"): - _add(ConnectorArrowDatabase(store()), rows(["r1"], offset=99)) + _add(ConnectorArrowDatabase(writable_connector()), rows(["r1"], offset=99)) @pytest.mark.usefixtures("root") @@ -1391,13 +1439,13 @@ def test_a_failed_append_to_a_table_with_rows_keeps_them( monkeypatch: pytest.MonkeyPatch, ) -> None: """Finding 2, a later write: the stored rows stay, and the table is read again.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0", "r1"]), flush=True) with monkeypatch.context() as patch: _failing_append(patch, after_commit=False) with pytest.raises(fake.SpiralError, match="injected append failure"): _add(db, rows(["r2"], offset=2), flush=True) - for reader in (db, ConnectorArrowDatabase(store())): + for reader in (db, ConnectorArrowDatabase(writable_connector())): got = _get(reader) assert got is not None and by_id(got).equals(by_id(rows(["r0", "r1"]))) @@ -1448,12 +1496,12 @@ def test_an_identifier_the_reader_also_reads_is_still_another_identifier( current = _with_path_column(rows(["r1"]), live=False) _reads_an_older_identifier(monkeypatch, current, OLDER) older = OLDER - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, first, flush=committed) with pytest.raises(InputValidationError, match="'p'"): _add(db, _older_identifier(current, older)) db.flush() - got = _get(ConnectorArrowDatabase(store())) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] @@ -1466,12 +1514,12 @@ def test_an_older_identifier_found_only_at_flush_is_refused( current = _with_path_column(rows(["r0"]), live=False) _reads_an_older_identifier(monkeypatch, current, OLDER) older = _older_identifier(_with_path_column(rows(["r1"]), live=False), OLDER) - buffered = ConnectorArrowDatabase(store()) + buffered = ConnectorArrowDatabase(writable_connector()) _add(buffered, older) - _add(ConnectorArrowDatabase(store()), current, flush=True) + _add(ConnectorArrowDatabase(writable_connector()), current, flush=True) with pytest.raises(InputValidationError, match="'p'"): buffered.flush() - got = _get(ConnectorArrowDatabase(store())) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] @@ -1483,17 +1531,17 @@ def test_a_table_renamed_away_is_never_used_through_its_earlier_name( """Finding 4: after the table is renamed and a foreign table made under its name, the handle that knew it refuses the foreign table on read and on write, as a fresh handle does: the name is resolved on every call.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) - name = identity.spiral_store_table_name(RESULT) + name = identity.spiral_table_name(RESULT) _rename(name, "renamed_away") fake.FakeClient().project("p").create_keyed_table( "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) ) - with pytest.raises(SpiralStoreTableCollisionError): - _get(ConnectorArrowDatabase(store())) + with pytest.raises(SpiralTableCollisionError): + _get(ConnectorArrowDatabase(writable_connector())) db.refresh_table(RESULT) - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): if through == "read": _get(db) else: @@ -1503,12 +1551,14 @@ def test_a_table_renamed_away_is_never_used_through_its_earlier_name( @pytest.mark.usefixtures("root") def test_a_table_replaced_under_its_name_is_read_as_the_replacement() -> None: """Finding 4: what a table records is kept by its id, never by its name: another - store table of the same path made under the name is read as itself.""" - db = ConnectorArrowDatabase(store()) + database table of the same path made under the name is read as itself.""" + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) - name = identity.spiral_store_table_name(RESULT) + name = identity.spiral_table_name(RESULT) _rename(name, "renamed_away") - _add(ConnectorArrowDatabase(store()), rows(["r5"], offset=5), flush=True) + _add( + ConnectorArrowDatabase(writable_connector()), rows(["r5"], offset=5), flush=True + ) got = _get(db) assert got is not None and got.column("__record_id").to_pylist() == [b"r5"] @@ -1543,7 +1593,7 @@ def test_a_storage_form_column_is_resolved_under_the_rows_data_context( "resolve_context", lambda key=None: alternate if key == alternate_key else resolve(key), # pyright: ignore[reportUnknownLambdaType] ) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, first, flush=True) _add(db, second, flush=True) got = _get(db) @@ -1559,7 +1609,7 @@ def _raise_value_error(*args: Any) -> Any: def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> None: """Should fix: ``get_table_schema`` of a stored table is the manifest's, field metadata included, equal to the schema while the rows are queued.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) data = rows(["r0"]) field = data.schema.field("a.b").with_metadata({b"unit": b"m"}) data = data.set_column( @@ -1568,7 +1618,7 @@ def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> No _add(db, data) queued = db.get_table_schema(RESULT) db.flush() - for reader in (db, ConnectorArrowDatabase(store())): + for reader in (db, ConnectorArrowDatabase(writable_connector())): stored = reader.get_table_schema(RESULT) assert stored is not None and queued is not None assert stored.equals(queued, check_metadata=True) @@ -1580,10 +1630,10 @@ def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> No @pytest.mark.usefixtures("root", "_cleared") @pytest.mark.parametrize("entry", ["run", "run_async"]) -def test_a_store_backed_job_holds_its_rows_and_reports_observer_losses( +def test_a_database_backed_job_holds_its_rows_and_reports_observer_losses( entry: str, ) -> None: - """Should fix: a job on the store through both public entry points; a rerun holds + """Should fix: a job on the database through both public entry points; a rerun holds the rows it ran, and an observer's lost events are reported.""" import asyncio import warnings @@ -1593,7 +1643,7 @@ def test_a_store_backed_job_holds_its_rows_and_reports_observer_losses( _database, # pyright: ignore[reportPrivateUsage] ) - database = ConnectorArrowDatabase(store(held=False)) + database = ConnectorArrowDatabase(writable_connector(held=False)) job = _job(database, SOURCE_ROWS) def run(**kwargs: Any) -> Any: @@ -1631,7 +1681,7 @@ def older_first(root: Path, monkeypatch: pytest.MonkeyPatch) -> ConnectorArrowDa _reads_an_older_identifier( monkeypatch, _with_path_column(rows(["r0"]), live=False), OLDER ) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, _older_rows(["r0"]), flush=True) return db @@ -1649,7 +1699,7 @@ def test_a_first_write_with_an_older_identifier_reads_back_with_it( """Round 2, P1: a table first written with an older identifier the type reads is read back, by the writer and a fresh handle, with the identifier bytes it was written with (one declaration rule for the read and the write).""" - for reader in (older_first, ConnectorArrowDatabase(store())): + for reader in (older_first, ConnectorArrowDatabase(writable_connector())): got = _get(reader) assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] assert _p_identifier(got.schema) == OLDER @@ -1660,7 +1710,7 @@ def test_the_schema_of_a_table_written_with_an_older_identifier_keeps_it( ) -> None: """Round 2, P1: ``get_table_schema`` reports the identifier bytes as recorded, never the current ones the type would state live.""" - for reader in (older_first, ConnectorArrowDatabase(store())): + for reader in (older_first, ConnectorArrowDatabase(writable_connector())): schema = reader.get_table_schema(RESULT) assert schema is not None and _p_identifier(schema) == OLDER @@ -1672,11 +1722,11 @@ def test_rows_with_the_same_older_identifier_append( """Round 2, P1: a later batch with the same older bytes is accepted at add and at flush (the stored layout and the pending rows in one form), by the first writer and by a fresh handle; the current identifier is still refused beside it.""" - db = ConnectorArrowDatabase(store()) if fresh else older_first + db = ConnectorArrowDatabase(writable_connector()) if fresh else older_first _add(db, _older_rows(["r1"]), flush=True) with pytest.raises(InputValidationError, match="'p'"): _add(db, _with_path_column(rows(["r2"]), live=False)) - for reader in (db, ConnectorArrowDatabase(store())): + for reader in (db, ConnectorArrowDatabase(writable_connector())): got = _get(reader) assert got is not None assert sorted(_record_ids(got)) == [b"r0", b"r1"] @@ -1712,7 +1762,7 @@ def test_one_operation_opens_the_name_once( after the caller's schema check, and reads the keys again from that last snapshot (another writer may have stored one since: an append would replace its row).""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0", "r1"]), flush=True) counts = _counted(monkeypatch) _add(db, rows(["r2", "r3"], offset=2)) @@ -1740,14 +1790,14 @@ def test_ids_checked_by_two_handles_are_written_once( flush writes it, and the second reads the keys again and keeps the first row, never replacing it (the handle reused within an operation is never an earlier operation's).""" - connector = store() + connector = writable_connector() first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) _add(first, rows(["r0"]), flush=True) _add(first, rows(["r1"], offset=1)) _add(second, rows(["r1"], offset=50)) first.flush() second.flush() - got = _get(ConnectorArrowDatabase(store())) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { b"r0": 0, @@ -1762,7 +1812,7 @@ def test_a_retry_after_a_failed_append_reads_the_keys_again( """Round 2, P2: after an append that stored its rows and then raised, a retry on the same handle reads the keys again: the stored id is refused, or kept when skipped.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) with monkeypatch.context() as patch: _failing_append(patch, after_commit=True) @@ -1781,8 +1831,8 @@ def test_a_retry_after_a_failed_append_reads_the_keys_again( def _replace_with_a_foreign_table() -> None: - """Rename the store table away and make a table of another key under its name.""" - name = identity.spiral_store_table_name(RESULT) + """Rename the database table away and make a table of another key under its name.""" + name = identity.spiral_table_name(RESULT) _rename(name, "renamed_away") _ = ( fake.FakeClient() @@ -1798,9 +1848,9 @@ def test_a_key_committed_during_the_schema_check_is_kept() -> None: """Round 3, finding 1: another writer stores a key while the caller's schema check runs; the flush reads the keys again after the check and keeps that writer's row, never replacing it.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) - peer = ConnectorArrowDatabase(store()) + peer = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r1"], offset=90)) def commit_first(_schema: pa.Schema) -> None: @@ -1821,7 +1871,7 @@ def test_a_table_replaced_during_the_schema_check_is_refused() -> None: """Round 3, finding 2: the table is renamed away and a foreign table made under its name while the caller's schema check runs; the flush refuses the replacement and never appends to the table renamed away.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) _add(db, rows(["r1"], offset=1)) @@ -1829,7 +1879,7 @@ def replace_table(_schema: pa.Schema) -> None: _replace_with_a_foreign_table() with db.guard_table_schema(RESULT, replace_table): - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): db.flush() old = fake.FakeClient().keyed_table("p", "d", "renamed_away") assert old.scan().to_table().num_rows == 1 @@ -1840,20 +1890,20 @@ def test_a_read_inside_the_schema_check_looks_the_name_up_again() -> None: """Round 3, finding 3: a public read made by the caller's schema check never reuses the enclosing flush's handle: after the table is replaced it refuses the replacement, as a read after the flush does.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) _add(db, rows(["r1"], offset=1)) def read_after_replacing(_schema: pa.Schema) -> None: _replace_with_a_foreign_table() - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): _ = _get(db) raise RuntimeError("stop before the write") with db.guard_table_schema(RESULT, read_after_replacing): with pytest.raises(RuntimeError, match="stop before the write"): db.flush() - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): _ = _get(db) @@ -1883,13 +1933,13 @@ def test_rows_of_another_data_context_than_the_pending_ones_are_refused_at_add( first, second = CONTEXT, alternate_key if first_alternate: first, second = second, first - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0", "r1"], context=first)) with pytest.raises(InputValidationError) as raised: _add(db, rows(["r2"], context=second, offset=2)) assert first in str(raised.value) and second in str(raised.value) db.flush() - got = _get(ConnectorArrowDatabase(store())) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None assert sorted(_record_ids(got)) == [b"r0", b"r1"] assert set(got.column("__data_context").to_pylist()) == {first} @@ -1903,7 +1953,7 @@ def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: before anything is written: it used to write columns the manifest does not record, and the next read failed.""" written = rows(["r0"]) - ConnectorArrowDatabase(store()).add_records( + ConnectorArrowDatabase(writable_connector()).add_records( RESULT, written, record_id_column="__record_id", flush=True ) current = codec.new_manifest(RESULT, "rdb_v1", written.schema) @@ -1913,15 +1963,15 @@ def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: for logical, f in zip(current.schema, current.physical) ] ) - other = codec.StoreManifest(RESULT, current.kind, current.schema, renamed) - name = identity.spiral_store_table_name(RESULT) + other = codec.TableManifest(RESULT, current.kind, current.schema, renamed) + name = identity.spiral_table_name(RESULT) _table(name).set_metadata( { - **identity.store_table_metadata(RESULT, CONTEXT), + **identity.table_identity_metadata(RESULT, CONTEXT), **codec.manifest_entries(other), } ) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) with pytest.raises(ValueError, match="other names") as raised: _add(db, rows(["r1", "r2"], offset=1), flush=True) assert "'s'" in str(raised.value) @@ -1939,10 +1989,12 @@ def test_an_empty_table_judged_in_an_operation_stays_empty_after_another_writes( first write fills it (it used to raise ``KeyError``, as for no table).""" import threading - connector = store() + connector = writable_connector() tables = tables_of(connector) name = tables.table_name(RESULT) - _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) + _make_table( + name, identity.table_identity_metadata(RESULT, CONTEXT), with_rows=False + ) failures: list[BaseException] = [] def write_elsewhere() -> None: @@ -1960,7 +2012,7 @@ def write_elsewhere() -> None: writer.join() assert failures == [] assert list(tables.scan(name)) == [] - got = _get(ConnectorArrowDatabase(store())) + got = _get(ConnectorArrowDatabase(writable_connector())) assert got is not None and _record_ids(got) == [b"r0"] @@ -1977,9 +2029,9 @@ def test_a_first_writer_compares_the_table_with_its_own_observation( first_seen = rows(["x"]).drop_columns(["s"]) _make_table( - identity.spiral_store_table_name(RESULT), + identity.spiral_table_name(RESULT), { - **identity.store_table_metadata(RESULT, CONTEXT), + **identity.table_identity_metadata(RESULT, CONTEXT), **codec.manifest_entries( codec.new_manifest(RESULT, "rdb_v1", first_seen.schema) ), @@ -1988,18 +2040,18 @@ def test_a_first_writer_compares_the_table_with_its_own_observation( ) peers = rows(["x"]).drop_columns(["a.b"]) peers_manifest = codec.new_manifest(RESULT, "rdb_v1", peers.schema) - connector = store() + connector = writable_connector() tables = tables_of(connector) name = tables.table_name(RESULT) new_manifest = codec.new_manifest interfered: list[bool] = [] - def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.TableManifest: if not interfered: interfered.append(True) _table(name).set_metadata( { - **identity.store_table_metadata(RESULT, CONTEXT), + **identity.table_identity_metadata(RESULT, CONTEXT), **codec.manifest_entries(peers_manifest), } ) @@ -2010,7 +2062,7 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) with tables.operation(): - with pytest.raises(SpiralStoreTableCollisionError): + with pytest.raises(SpiralTableCollisionError): tables.write(name, rows(["a0"])) assert interfered == [True] kept = codec.read_manifest(_table(name).get_metadata(), RESULT) @@ -2019,14 +2071,14 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: @pytest.mark.usefixtures("root") -def test_a_store_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( +def test_a_database_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( monkeypatch: pytest.MonkeyPatch, ) -> None: """spiral-sdk 0.16.79 and later warn on every keyed-table open and creation, attributed to the module that calls the SDK (the fake warns the same way); Orcapod - ignores that warning for its connector's own calls only. So the store's creation, + ignores that warning for its connector's own calls only. So the database's creation, opens by name and opens by id must all be the connector's: with every warning an - error, an add, a flush and a listing raise none (the store used to create a table + error, an add, a flush and a listing raise none (the database used to create a table and open one by id itself, and raised). A direct call from elsewhere still warns.""" import warnings @@ -2047,14 +2099,16 @@ def call(*args: Any, **kwargs: Any) -> Any: spy("_create_keyed_table") with warnings.catch_warnings(): warnings.simplefilter("error") - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0", "r1"]), flush=True) _add(db, rows(["r2"], offset=2), flush=True) - assert ConnectorArrowDatabase(store()).list_table_paths() == [RESULT] + assert ConnectorArrowDatabase(writable_connector()).list_table_paths() == [ + RESULT + ] got = _get(db) assert got is not None and sorted(_record_ids(got)) == [b"r0", b"r1", b"r2"] with pytest.raises(DeprecationWarning, match="Keyed tables are deprecated"): - _ = _table(identity.spiral_store_table_name(RESULT)) + _ = _table(identity.spiral_table_name(RESULT)) assert called.keys() == {"_open_keyed_table_by_id", "_create_keyed_table"} @@ -2079,7 +2133,9 @@ def test_a_stored_table_a_lookup_cannot_read_fails_a_continue_run( run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} def build() -> Any: - job = PipelineJob(name=JOB, database=ConnectorArrowDatabase(store(held=False))) + job = PipelineJob( + name=JOB, database=ConnectorArrowDatabase(writable_connector(held=False)) + ) with job: source = DictSource( data=SOURCE_ROWS, @@ -2093,10 +2149,10 @@ def build() -> Any: _ = build().run(orchestrator=run[orchestrator](error_policy="continue")) calls.clear() - def unreadable(self: StoreTables, table_name: str) -> Iterator[pa.RecordBatch]: + def unreadable(self: SpiralDBTables, table_name: str) -> Iterator[pa.RecordBatch]: raise RuntimeError("the service could not read the table") - monkeypatch.setattr(StoreTables, "scan", unreadable) + monkeypatch.setattr(SpiralDBTables, "scan", unreadable) observer = _CrashRecorder() with pytest.raises(OrcapodDatabaseReadError) as raised: _ = build().run( @@ -2111,36 +2167,42 @@ def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( monkeypatch: pytest.MonkeyPatch, ) -> None: """Recorded, then its first append failed: no rows, so nothing stored there.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) - def failing(self: StoreTables, table: Any, found: Any, encoded: pa.Table) -> None: + def failing( + self: SpiralDBTables, table: Any, found: Any, encoded: pa.Table + ) -> None: raise RuntimeError("the append failed") with monkeypatch.context() as patched: - patched.setattr(StoreTables, "_append", failing) + patched.setattr(SpiralDBTables, "_append", failing) with pytest.raises(Exception, match="the append failed"): db.add_records( RESULT, rows(["r0"]), record_id_column="__record_id", flush=True ) - assert identity.spiral_store_table_name(RESULT) in [t["name"] for t in _tables()] - fresh = ConnectorArrowDatabase(store()) + assert identity.spiral_table_name(RESULT) in [t["name"] for t in _tables()] + fresh = ConnectorArrowDatabase(writable_connector()) assert fresh.list_table_paths(("my_fn",)) == [] assert tables_of_another_layout(fresh, ("my_fn",), result_revision="rev1") == [] # Pending rows are listed; once written, the table is listed by its rows. fresh.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") assert fresh.list_table_paths(("my_fn",)) == [RESULT] fresh.flush() - assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [RESULT] + assert ConnectorArrowDatabase(writable_connector()).list_table_paths( + ("my_fn",) + ) == [RESULT] @pytest.mark.usefixtures("root") -def test_an_empty_table_of_another_store_format_is_not_listed() -> None: +def test_an_empty_table_of_another_table_format_is_not_listed() -> None: metadata = { - **identity.store_table_metadata(OTHER, CONTEXT), - identity.STORE_KEY: OTHER_FORMAT.encode(), + **identity.table_identity_metadata(OTHER, CONTEXT), + identity.FORMAT_KEY: OTHER_FORMAT.encode(), } - _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=False) - assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [] + _make_table(identity.spiral_table_name(OTHER), metadata, with_rows=False) + assert ( + ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) == [] + ) @pytest.mark.usefixtures("root") @@ -2154,7 +2216,7 @@ def with_metadata(table: pa.Table) -> pa.Table: ] return table.cast(pa.schema(fields)) - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, with_metadata(rows(["r0"])), flush=True) _add(db, with_metadata(rows(["r1"], offset=1))) seen: list[pa.Schema] = [] @@ -2178,14 +2240,14 @@ def test_a_table_whose_metadata_cannot_be_read_fails_the_lookup_as_a_read_error( """Finding the table is a read too: a fresh reader whose metadata read fails raises ``OrcapodDatabaseReadError``, as a failing scan does, never the service's own error.""" - db = ConnectorArrowDatabase(store()) + db = ConnectorArrowDatabase(writable_connector()) _add(db, rows(["r0"]), flush=True) def unreadable(self: Any) -> dict[str, bytes]: raise RuntimeError("the service could not read the metadata") monkeypatch.setattr(fake.FakeKeyedTable, "get_metadata", unreadable) - fresh = ConnectorArrowDatabase(store()) + fresh = ConnectorArrowDatabase(writable_connector()) with pytest.raises(OrcapodDatabaseReadError) as raised: if lookup == "by_id": _ = fresh.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") @@ -2197,21 +2259,21 @@ def unreadable(self: Any) -> dict[str, bytes]: @pytest.mark.usefixtures("root") def test_a_lookup_of_a_table_that_is_not_this_paths_still_raises_a_collision() -> None: """A collision found while finding the table keeps its own type.""" - _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) - with pytest.raises(SpiralStoreTableCollisionError): - _ = ConnectorArrowDatabase(store()).get_all_records(RESULT) + _make_table(identity.spiral_table_name(RESULT), {}, with_rows=True) + with pytest.raises(SpiralTableCollisionError): + _ = ConnectorArrowDatabase(writable_connector()).get_all_records(RESULT) @pytest.mark.usefixtures("root") -def test_a_record_with_an_empty_store_format_refuses_the_listing() -> None: +def test_a_record_with_an_empty_table_format_refuses_the_listing() -> None: """An empty format is a malformed record, not another format to list.""" metadata = { - **identity.store_table_metadata(OTHER, CONTEXT), - identity.STORE_KEY: b"", + **identity.table_identity_metadata(OTHER, CONTEXT), + identity.FORMAT_KEY: b"", } - _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) - with pytest.raises(SpiralStoreTableCollisionError, match="no store format"): - _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + _make_table(identity.spiral_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralTableCollisionError, match="no table format"): + _ = ConnectorArrowDatabase(writable_connector()).list_table_paths(("my_fn",)) @pytest.mark.usefixtures("root") @@ -2227,22 +2289,22 @@ def test_a_first_write_refuses_an_empty_table_recorded_meanwhile_under_another_c codec.new_manifest(RESULT, "rdb_v1", written.schema) ) _make_table( - identity.spiral_store_table_name(RESULT), - {**identity.store_table_metadata(RESULT, CONTEXT), **manifest_entries}, + identity.spiral_table_name(RESULT), + {**identity.table_identity_metadata(RESULT, CONTEXT), **manifest_entries}, with_rows=False, ) - connector = store() + connector = writable_connector() tables = tables_of(connector) name = tables.table_name(RESULT) new_manifest = codec.new_manifest interfered: list[bool] = [] - def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.TableManifest: if not interfered: interfered.append(True) _table(name).set_metadata( { - **identity.store_table_metadata(RESULT, other_context), + **identity.table_identity_metadata(RESULT, other_context), **manifest_entries, } ) @@ -2253,6 +2315,6 @@ def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: with pytest.raises(InputValidationError): tables.write(name, written) assert interfered == [True] - kept = identity.read_store_table_metadata(_table(name).get_metadata()) + kept = identity.read_table_identity_metadata(_table(name).get_metadata()) assert kept is not None and kept.data_context_key == other_context assert _table(name).scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_spiraldb_store_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py similarity index 73% rename from tests/test_databases/test_spiraldb_store_runs.py rename to tests/test_databases/test_spiraldb_writable_runs.py index e0662bd89..f837d0e9d 100644 --- a/tests/test_databases/test_spiraldb_store_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1,8 +1,8 @@ -"""Job runs on a SpiralDB store: every table kind, the writer lease, save and load +"""Job runs on a writable SpiralDB database: every table kind, the writer lease, save and load (ITL-1844). On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a store -(``SpiralDBConnector(..., store=True)``) and on Delta, and every stored table is +(``SpiralDBConnector(..., writable=True)``) and on Delta, and every stored table is compared: same paths, same rows, apart from the columns a run fills with its own time or a random id. """ @@ -33,13 +33,13 @@ from orcapod.databases import ( spiraldb_connector, spiraldb_lease, - spiraldb_store_registry, + spiraldb_writable_registry, spiraldb_write_scope, ) from orcapod.databases.extension_aware_database import ExtensionAwareDatabase -from orcapod.databases.spiraldb_write_scope import store_writes, take_lease +from orcapod.databases.spiraldb_write_scope import database_writes, take_lease from orcapod.databases.store_table_names import is_spiral_lease_table_name -from orcapod.errors import SpiralDBStoreLeaseRequiredError +from orcapod.errors import SpiralDBLeaseRequiredError from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.pipeline import node_run from orcapod.semantic_types.universal_converter import UniversalTypeConverter @@ -149,11 +149,11 @@ def root(tmp_path: Path) -> Iterator[Path]: delivered.clear() -def _store(dataset: str = "d") -> ConnectorArrowDatabase: - return ConnectorArrowDatabase(SpiralDBConnector("p", dataset, store=True)) +def _database(dataset: str = "d") -> ConnectorArrowDatabase: + return ConnectorArrowDatabase(SpiralDBConnector("p", dataset, writable=True)) -def _store_tables(dataset: str = "d") -> list[str]: +def _database_tables(dataset: str = "d") -> list[str]: return sorted( t["name"] for t in fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] @@ -184,17 +184,17 @@ def _types(table: pa.Table) -> dict[str, pa.DataType]: return {f.name: f.type for f in table.schema if f.name not in VOLATILE} -def _same_tables(store: Any, delta: Any) -> None: +def _same_tables(spiral_db: Any, delta: Any) -> None: """Same paths, and in each the same rows, apart from the volatile columns.""" - paths = sorted(store.list_table_paths()) + paths = sorted(spiral_db.list_table_paths()) assert paths == sorted(delta.list_table_paths()) for path in paths: - on_store = store.get_all_records(path) + on_spiral = spiral_db.get_all_records(path) on_delta = delta.get_all_records(path) - assert on_store is not None and on_delta is not None, path - assert on_store.schema.names == on_delta.schema.names, path - assert _types(on_store) == _types(on_delta), path - assert _comparable(on_store) == _comparable(on_delta), path + assert on_spiral is not None and on_delta is not None, path + assert on_spiral.schema.names == on_delta.schema.names, path + assert _types(on_spiral) == _types(on_delta), path + assert _comparable(on_spiral) == _comparable(on_delta), path def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: @@ -224,13 +224,13 @@ def _run(job: PipelineJob, entry: str, **kwargs: Any) -> Any: def test_every_table_kind_is_stored_as_on_delta( root: Path, entry: str, order: str ) -> None: - store = _store() + spiral_db = _database() delta = DeltaTableDatabase(root / "delta") - for database in (store, delta): + for database in (spiral_db, delta): _ = _run(_job(database, order=order), entry) - assert sorted(p[-1] for p in store.list_table_paths()) == sorted(LAYOUTS) - _same_tables(store, delta) - # Each run took the store's lease once and released it. + assert sorted(p[-1] for p in spiral_db.list_table_paths()) == sorted(LAYOUTS) + _same_tables(spiral_db, delta) + # Each run took the database's lease once and released it. assert len(_lease_tables()) == LEASES[entry] @@ -240,15 +240,15 @@ def test_every_table_kind_is_stored_as_on_delta( def test_a_separate_result_database_is_stored_as_on_delta( root: Path, entry: str, dataset: str ) -> None: - """Results in a separate store, on another dataset (two leases) or on the same + """Results in a separate result database, on another dataset (two leases) or on the same dataset through another connector (one lease).""" - store, results = _store(), _store("r" if dataset == "other" else "d") + spiral_db, results = _database(), _database("r" if dataset == "other" else "d") delta = DeltaTableDatabase(root / "delta") delta_results = DeltaTableDatabase(root / "delta_results") - _ = _run(_job(store, result_database=results), entry) + _ = _run(_job(spiral_db, result_database=results), entry) _ = _run(_job(delta, result_database=delta_results), entry) if dataset == "other": - _same_tables(store, delta) + _same_tables(spiral_db, delta) _same_tables(results, delta_results) assert len(_lease_tables("d")) == LEASES[entry] assert len(_lease_tables("r")) == LEASES[entry] @@ -256,7 +256,7 @@ def test_a_separate_result_database_is_stored_as_on_delta( on_delta = sorted( [*delta.list_table_paths(), *delta_results.list_table_paths()] ) - assert sorted(store.list_table_paths()) == on_delta + assert sorted(spiral_db.list_table_paths()) == on_delta assert len(_lease_tables("d")) == LEASES[entry] @@ -267,22 +267,22 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( ) -> None: """A second run with one more row computes it alone; a REPLAY run of the operator reads the operator cache back, on both databases alike.""" - store = _store() + spiral_db = _database() delta = DeltaTableDatabase(root / "delta") - for database in (store, delta): + for database in (spiral_db, delta): _ = _run(_job(database, table=_rows(3)), entry) calls.clear() - for database in (store, delta): + for database in (spiral_db, delta): _ = _run(_job(database, table=_rows(4)), entry) assert calls == [(4, 8), (4, 8)] - _same_tables(store, delta) + _same_tables(spiral_db, delta) replayed = [] - for database in (store, delta): + for database in (spiral_db, delta): job = _job(database, table=_rows(4), cache_mode=CacheMode.REPLAY) _ = _run(job, entry) replayed.append(_comparable(job.nodes["select"].as_table())) assert replayed[0] == replayed[1] and len(replayed[0]) == 4 - _same_tables(store, delta) + _same_tables(spiral_db, delta) # ------------------------------------------------------------------ load only @@ -290,16 +290,16 @@ def test_a_new_input_and_a_replay_are_stored_as_on_delta( @pytest.mark.usefixtures("root") def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None: - store = _store() - job = _job(store) + spiral_db = _database() + job = _job(spiral_db) _ = job.run() saved = root / "job.json" job.save(saved) text = saved.read_text() - assert '"store": true' in text + assert '"writable": true' in text assert not any(word in text.lower() for word in ("secret", "token", "private")) leases = _lease_tables() - loaded = PipelineJob.load(saved, database=_store()) + loaded = PipelineJob.load(saved, database=_database()) for label in ("combine", "select"): stored = loaded.nodes[label].as_source().as_table() assert stored.num_rows == 3, label @@ -313,28 +313,30 @@ def test_a_loaded_job_reads_and_load_only_runs_take_no_lease(root: Path) -> None @pytest.mark.parametrize("entry", ENTRIES) def test_a_load_only_run_over_a_cached_source_holds_its_lease(entry: str) -> None: """A cached source writes its cache when checked or read, so a load-only run takes - the lease of the cache's store; it writes no node's table.""" - store = _store() - _ = _job(store).run() - before = {p: store.get_all_records(p) for p in store.list_table_paths()} - job = _job(store, table=_rows(4)) + the lease of the cache's database; it writes no node's table.""" + spiral_db = _database() + _ = _job(spiral_db).run() + before = {p: spiral_db.get_all_records(p) for p in spiral_db.list_table_paths()} + job = _job(spiral_db, table=_rows(4)) _ = _run(job, entry, load_only=True) assert len(_lease_tables()) == 1 + LEASES[entry] for path, rows in before.items(): - now = store.get_all_records(path) + now = spiral_db.get_all_records(path) assert now is not None and rows is not None expected = 4 if path[-1] == "sdb_v2" else rows.num_rows assert now.num_rows == expected, path @pytest.mark.usefixtures("root") -@pytest.mark.parametrize(("saved_store", "given_store"), [(True, False), (False, True)]) +@pytest.mark.parametrize( + ("saved_writable", "given_writable"), [(True, False), (False, True)] +) def test_load_refuses_a_spiraldb_connector_of_the_other_kind( - root: Path, saved_store: bool, given_store: bool + root: Path, saved_writable: bool, given_writable: bool ) -> None: saved = root / "job.json" - if saved_store: - _job(_store()).save(saved) + if saved_writable: + _job(_database()).save(saved) else: delta = DeltaTableDatabase(root / "delta") _job(delta).save(saved) @@ -343,27 +345,54 @@ def test_load_refuses_a_spiraldb_connector_of_the_other_kind( SpiralDBConnector("p", "d") ).to_config() saved.write_text(json.dumps(data)) - given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=given_store)) - with pytest.raises(ValueError, match="bindings.database.*store"): + given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + with pytest.raises(ValueError, match="bindings.database.*writable"): + _ = PipelineJob.load(saved, database=given) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("given_writable", [True, False]) +def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( + root: Path, given_writable: bool +) -> None: + """``store`` is not an option of this version: ``writable`` is.""" + saved = root / "job.json" + _job(_database()).save(saved) + data = json.loads(saved.read_text()) + connector = data["bindings"]["database"]["connector"] + del connector["writable"] + connector["store"] = True + saved.write_text(json.dumps(data)) + given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + with pytest.raises(ValueError, match=r"'store' key.*writable=True"): _ = PipelineJob.load(saved, database=given) @pytest.mark.usefixtures("root") -def test_the_store_flag_is_saved_without_credentials() -> None: - assert SpiralDBConnector("p", "d", store=True).to_config() == { +def test_a_spiraldb_connector_config_with_a_store_key_is_refused() -> None: + config = SpiralDBConnector("p", "d", writable=True).to_config() + del config["writable"] + config["store"] = True + with pytest.raises(ValueError, match=r"'store' key.*writable=True"): + _ = SpiralDBConnector.from_config(config) + + +@pytest.mark.usefixtures("root") +def test_the_writable_flag_is_saved_without_credentials() -> None: + assert SpiralDBConnector("p", "d", writable=True).to_config() == { "connector_type": "spiraldb", "project_id": "p", "dataset": "d", "overrides": None, - "store": True, + "writable": True, } - assert "store" not in SpiralDBConnector("p", "d").to_config() + assert "writable" not in SpiralDBConnector("p", "d").to_config() rebuilt = SpiralDBConnector.from_config( - SpiralDBConnector("p", "d", store=True).to_config() + SpiralDBConnector("p", "d", writable=True).to_config() ) - assert rebuilt._store_tables() is not None # pyright: ignore[reportPrivateUsage] - with pytest.raises(TypeError, match="store must be True or False"): - _ = SpiralDBConnector("p", "d", store="yes") # pyright: ignore[reportArgumentType] + assert rebuilt._writable_tables() is not None # pyright: ignore[reportPrivateUsage] + with pytest.raises(TypeError, match="writable must be True or False"): + _ = SpiralDBConnector("p", "d", writable="yes") # pyright: ignore[reportArgumentType] # ------------------------------------------------------------------ the lease @@ -387,7 +416,7 @@ def counted() -> bool: def _held_by_another_writer(dataset: str = "d") -> Callable[[], None]: """Hold the dataset's lease as another writer would; returns its release.""" _, release = take_lease( - SpiralDBConnector("p", dataset, store=True), "another writer" + SpiralDBConnector("p", dataset, writable=True), "another writer" ) return release @@ -399,11 +428,11 @@ def test_a_second_writer_is_refused_before_anything( entry: str, load_only: bool ) -> None: release = _held_by_another_writer() - job = _job(_store()) + job = _job(_database()) checks = _count_source_checks(job) with pytest.raises(spiraldb_lease.LeaseBusyError, match="another writer"): _ = _run(job, entry, load_only=load_only) - assert _store_tables() == [] + assert _database_tables() == [] assert calls == [] and delivered == [] # Refused before any source was checked (a cached source writes its cache then). assert checks == [] @@ -418,12 +447,12 @@ def test_a_second_writer_is_refused_before_anything( @pytest.mark.usefixtures("root") def test_a_second_writer_on_the_result_database_is_refused() -> None: release = _held_by_another_writer("r") - job = _job(_store(), result_database=_store("r")) + job = _job(_database(), result_database=_database("r")) with pytest.raises(spiraldb_lease.LeaseBusyError): _ = job.run() - assert _store_tables("d") == [] and _store_tables("r") == [] + assert _database_tables("d") == [] and _database_tables("r") == [] # The lease the run took on its own database was released. - _, own = take_lease(SpiralDBConnector("p", "d", store=True), "check") + _, own = take_lease(SpiralDBConnector("p", "d", writable=True), "check") own() release() @@ -435,10 +464,10 @@ def test_the_lease_is_released_when_a_run_fails(entry: str) -> None: def boom(x: int) -> int: raise RuntimeError("boom") - store = _store() - job = PipelineJob(name=JOB, database=store) + spiral_db = _database() + job = PipelineJob(name=JOB, database=spiral_db) with job: - source = _cached(store, _rows()) + source = _cached(spiral_db, _rows()) boom.pod(source.select_data_columns(["x"]), label="boom") orchestrator = ( SyncPipelineOrchestrator(error_policy="fail_fast") @@ -459,18 +488,18 @@ def boom(x: int) -> int: def test_a_failed_release_after_a_run_raises_and_the_tables_are_complete( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - store = _store() + spiral_db = _database() def failing(client: Any, lease: Any) -> None: raise spiraldb_lease.LeaseError("release lost") monkeypatch.setattr(spiraldb_lease, "release", failing) with pytest.raises(spiraldb_lease.LeaseError, match="release lost"): - _ = _job(store).run() + _ = _job(spiral_db).run() monkeypatch.undo() delta = DeltaTableDatabase(root / "delta") _ = _job(delta).run() - fresh = _store() + fresh = _database() assert sorted(p[-1] for p in fresh.list_table_paths()) == sorted(LAYOUTS) _same_tables(fresh, delta) @@ -493,12 +522,12 @@ def lost(*args: Any, **kwargs: Any) -> Any: monkeypatch.setattr(spiraldb_lease, "release", release_with_reopen_lost) with pytest.raises(spiraldb_lease.LeaseError) as raised: - _ = _job(_store()).run() + _ = _job(_database()).run() assert isinstance(raised.value.__cause__, TimeoutError) monkeypatch.undo() delta = DeltaTableDatabase(root / "delta") _ = _job(delta).run() - _same_tables(_store(), delta) + _same_tables(_database(), delta) @pytest.mark.usefixtures("root") @@ -512,10 +541,10 @@ def boom(x: int) -> int: def failing(client: Any, lease: Any) -> None: raise spiraldb_lease.LeaseError("release lost") - store = _store() - job = PipelineJob(name=JOB, database=store) + spiral_db = _database() + job = PipelineJob(name=JOB, database=spiral_db) with job: - boom.pod(_cached(store, _rows()).select_data_columns(["x"]), label="boom") + boom.pod(_cached(spiral_db, _rows()).select_data_columns(["x"]), label="boom") monkeypatch.setattr(spiraldb_lease, "release", failing) with pytest.raises(RuntimeError, match="boom") as raised: _ = job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast")) @@ -523,13 +552,13 @@ def failing(client: Any, lease: Any) -> None: @pytest.mark.usefixtures("root") -def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: - store = _store() +def test_a_database_write_outside_a_run_is_refused_before_anything() -> None: + spiral_db = _database() with pytest.raises( - SpiralDBStoreLeaseRequiredError, match="through the connectors of a job run" + SpiralDBLeaseRequiredError, match="through the connectors of a job run" ): - _ = _cached(store, _rows()).as_table() - store.add_records( + _ = _cached(spiral_db, _rows()).as_table() + spiral_db.add_records( ("t", "rdb_v1"), pa.table( { @@ -540,9 +569,9 @@ def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: ), record_id_column="__record_id", ) - with pytest.raises(SpiralDBStoreLeaseRequiredError): - store.flush() - assert _store_tables() == [] and _lease_tables() == [] + with pytest.raises(SpiralDBLeaseRequiredError): + spiral_db.flush() + assert _database_tables() == [] and _lease_tables() == [] # ------------------------------------------- spiral-sdk's keyed-table deprecation @@ -550,15 +579,15 @@ def test_a_store_write_outside_a_run_is_refused_before_anything() -> None: @pytest.mark.usefixtures("root") @pytest.mark.parametrize("entry", ENTRIES) -def test_a_job_run_on_a_store_raises_no_keyed_table_deprecation(entry: str) -> None: - """Every keyed-table open and create of a run (store tables, the schema table and +def test_a_job_run_on_a_database_raises_no_keyed_table_deprecation(entry: str) -> None: + """Every keyed-table open and create of a run (database tables, the schema table and the lease generations) goes through the connector's helpers, which ignore the SDK's keyed-table deprecation; a second run reopens every table.""" with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) for _ in range(2): - _ = _run(_job(_store(), result_database=_store("r")), entry) - assert sorted(p[-1] for p in _store().list_table_paths()) != [] + _ = _run(_job(_database(), result_database=_database("r")), entry) + assert sorted(p[-1] for p in _database().list_table_paths()) != [] assert len(_lease_tables("d")) == 2 * LEASES[entry] @@ -566,7 +595,7 @@ def test_a_job_run_on_a_store_raises_no_keyed_table_deprecation(entry: str) -> N def test_the_lease_raises_no_keyed_table_deprecation() -> None: """Acquire, check, release, a refused second writer and a clear by id: each open and create of a generation table is the connector's.""" - connector = SpiralDBConnector("p", "d", store=True) + connector = SpiralDBConnector("p", "d", writable=True) with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) check, release = take_lease(connector, "first") @@ -595,8 +624,8 @@ def test_the_lease_raises_no_keyed_table_deprecation() -> None: def test_a_retried_attachment_flush_runs_under_its_dataset_lease() -> None: """An attachment whose flush failed is retried by the next run, also after the node was attached elsewhere; that run leases the old attachment's dataset too.""" - job = _job(_store()) - old = _store("a").at(JOB) + job = _job(_database()) + old = _database("a").at(JOB) job.nodes["select"].attach_databases( pipeline_database=old, cache_mode=CacheMode.LOG ) @@ -612,13 +641,13 @@ def failing_once() -> None: old.flush = failing_once # pyright: ignore[reportAttributeAccessIssue] # this attachment's flush fails once with pytest.raises(Exception, match="flush lost"): _ = job.run() - assert _store_tables("a") == [] + assert _database_tables("a") == [] job.nodes["select"].attach_databases( - pipeline_database=_store("b").at(JOB), cache_mode=CacheMode.LOG + pipeline_database=_database("b").at(JOB), cache_mode=CacheMode.LOG ) _ = job.run() # The retry wrote the old attachment's operator cache, under a lease of its dataset. - assert [p[-1] for p in _store("a").list_table_paths()] == ["odb_v3"] + assert [p[-1] for p in _database("a").list_table_paths()] == ["odb_v3"] assert len(_lease_tables("a")) == 2 @@ -630,14 +659,16 @@ def _wrapped(database: Any) -> ExtensionAwareDatabase: @pytest.mark.usefixtures("root") -@pytest.mark.parametrize(("saved_store", "given_store"), [(True, False), (False, True)]) +@pytest.mark.parametrize( + ("saved_writable", "given_writable"), [(True, False), (False, True)] +) def test_load_refuses_a_wrapped_spiraldb_connector_of_the_other_kind( - root: Path, saved_store: bool, given_store: bool + root: Path, saved_writable: bool, given_writable: bool ) -> None: """The mode check sees through an ``ExtensionAwareDatabase`` view.""" saved = root / "job.json" - if saved_store: - _job(_store()).save(saved) + if saved_writable: + _job(_database()).save(saved) else: _job(DeltaTableDatabase(root / "delta")).save(saved) data = json.loads(saved.read_text()) @@ -646,36 +677,36 @@ def test_load_refuses_a_wrapped_spiraldb_connector_of_the_other_kind( ).to_config() saved.write_text(json.dumps(data)) given = _wrapped( - ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=given_store)) + ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) ) - with pytest.raises(ValueError, match="bindings.database.*store"): + with pytest.raises(ValueError, match="bindings.database.*writable"): _ = PipelineJob.load(saved, database=given) @pytest.mark.usefixtures("root") -def test_a_wrapped_store_of_the_same_kind_loads(root: Path) -> None: +def test_a_wrapped_database_of_the_same_kind_loads(root: Path) -> None: saved = root / "job.json" - _ = _job(_store()).run() - _job(_store()).save(saved) - loaded = PipelineJob.load(saved, database=_wrapped(_store())) + _ = _job(_database()).run() + _job(_database()).save(saved) + loaded = PipelineJob.load(saved, database=_wrapped(_database())) assert loaded.nodes["combine"].as_source().as_table().num_rows == 3 @pytest.mark.usefixtures("root") -def test_a_job_on_a_wrapped_store_holds_its_lease_and_stores_as_on_delta( +def test_a_job_on_a_wrapped_database_holds_its_lease_and_stores_as_on_delta( root: Path, ) -> None: - """Lease discovery sees a store under an ``ExtensionAwareDatabase`` view: the run + """Lease discovery sees a writable SpiralDB database under an ``ExtensionAwareDatabase`` view: the run takes the dataset's lease, writes every table kind, and a second writer waits on it.""" - store = _store() + spiral_db = _database() delta = DeltaTableDatabase(root / "delta") - _ = _job(_wrapped(store)).run() + _ = _job(_wrapped(spiral_db)).run() _ = _job(delta).run() assert len(_lease_tables()) == 1 - _same_tables(store, delta) + _same_tables(spiral_db, delta) release = _held_by_another_writer() with pytest.raises(spiraldb_lease.LeaseBusyError): - _ = _job(_wrapped(_store())).run() + _ = _job(_wrapped(_database())).run() release() @@ -684,7 +715,7 @@ def test_the_lease_key_keeps_the_service_address_of_construction() -> None: """Changing the caller's overrides after construction moves neither the client, the lease nor the saved configuration to another service.""" overrides = {"server.url": "https://one.example"} - connector = SpiralDBConnector("p", "d", store=True, overrides=overrides) + connector = SpiralDBConnector("p", "d", writable=True, overrides=overrides) key = connector._writer_lease_key() # pyright: ignore[reportPrivateUsage] overrides["server.url"] = "https://two.example" assert connector._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] @@ -702,23 +733,23 @@ def test_the_lease_key_keeps_the_service_address_of_construction() -> None: "given", ["https://api.fake.invalid", "https://api.fake.invalid/"] ) def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: - """A store connector with no address and one given the default address (also with + """A writable connector with no address and one given the default address (also with a final slash) reach one service: a run over both takes one lease, held by both stores; another service keeps its own lease.""" - plain = SpiralDBConnector("p", "d", store=True) - addressed = SpiralDBConnector("p", "d", {"server.url": given}, store=True) + plain = SpiralDBConnector("p", "d", writable=True) + addressed = SpiralDBConnector("p", "d", {"server.url": given}, writable=True) other = SpiralDBConnector( - "p", "d", {"server.url": "https://other.invalid"}, store=True + "p", "d", {"server.url": "https://other.invalid"}, writable=True ) databases = [ConnectorArrowDatabase(c) for c in (plain, addressed, other)] key = plain._writer_lease_key() # pyright: ignore[reportPrivateUsage] assert addressed._writer_lease_key() == key # pyright: ignore[reportPrivateUsage] assert other._writer_lease_key() != key # pyright: ignore[reportPrivateUsage] - with spiraldb_write_scope.store_writes(databases[:2], owner="test"): + with spiraldb_write_scope.database_writes(databases[:2], owner="test"): assert len(_lease_tables()) == 1 - held = [c._store_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + held = [c._writable_tables()._lease_check for c in (plain, addressed)] # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] assert held[0] is not None and held[0] is held[1] - assert all(c._store_tables()._lease_check is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] + assert all(c._writable_tables()._lease_check is None for c in (plain, addressed)) # pyright: ignore[reportPrivateUsage, reportOptionalMemberAccess] @pytest.mark.usefixtures("root") @@ -730,7 +761,7 @@ def test_a_client_without_its_resolved_address_is_refused( takes the lease: no address is guessed, and no lease is taken.""" from types import SimpleNamespace - connector = SpiralDBConnector("p", "d", store=True) + connector = SpiralDBConnector("p", "d", writable=True) client = connector._client # pyright: ignore[reportPrivateUsage] stand_in = ( SimpleNamespace() @@ -739,7 +770,7 @@ def test_a_client_without_its_resolved_address_is_refused( ) monkeypatch.setattr(connector, "_client", stand_in) with pytest.raises(RuntimeError, match="resolved"): - with store_writes([ConnectorArrowDatabase(connector)], owner="test"): + with database_writes([ConnectorArrowDatabase(connector)], owner="test"): pass assert _lease_tables() == [] monkeypatch.setattr(connector, "_client", client) @@ -747,13 +778,13 @@ def test_a_client_without_its_resolved_address_is_refused( @pytest.mark.usefixtures("root") def test_a_write_through_another_connector_during_a_run_is_refused() -> None: - """While a run holds the dataset's lease, a store connector of its own (not one the + """While a run holds the dataset's lease, a writable connector of its own (not one the run holds) is still refused, and writes nothing.""" seen: list[BaseException] = [] @function_pod(output_keys="z") def write_elsewhere(x: int) -> int: - other = ConnectorArrowDatabase(SpiralDBConnector("p", "d", store=True)) + other = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=True)) row = pa.table( { "__data_context": pa.array(["std:v1:default"], pa.large_string()), @@ -763,17 +794,17 @@ def write_elsewhere(x: int) -> int: other.add_record(("elsewhere",), b"r", row, flush=False) try: other.flush() - except SpiralDBStoreLeaseRequiredError as exc: + except SpiralDBLeaseRequiredError as exc: seen.append(exc) return x - store = _store() - job = PipelineJob(name=JOB, database=store) + spiral_db = _database() + job = PipelineJob(name=JOB, database=spiral_db) with job: - write_elsewhere.pod(_cached(store, _rows()).select_data_columns(["x"])) + write_elsewhere.pod(_cached(spiral_db, _rows()).select_data_columns(["x"])) _ = job.run() assert len(seen) == 3 - assert _store().list_table_paths(("elsewhere",)) == [] + assert _database().list_table_paths(("elsewhere",)) == [] @pytest.mark.usefixtures("root") @@ -794,33 +825,35 @@ def interrupt_first(client: Any, lease: Any) -> None: real(client, lease) monkeypatch.setattr(spiraldb_lease, "release", interrupt_first) - databases = [_store("d"), _store("r")] + databases = [_database("d"), _database("r")] if body_fails: with pytest.raises(KeyboardInterrupt) as raised: - with store_writes(databases, owner="test"): + with database_writes(databases, owner="test"): raise RuntimeError("body") cause = raised.value.__cause__ assert isinstance(cause, RuntimeError) and str(cause) == "body" else: with pytest.raises(KeyboardInterrupt): - with store_writes(databases, owner="test"): + with database_writes(databases, owner="test"): pass monkeypatch.undo() # The lease released after the interruption (the first one taken, released last # in reverse order) can be taken again. - _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") + _, again = take_lease(SpiralDBConnector("p", "d", writable=True), "after") again() -def test_a_job_with_no_store_connector_in_the_process_takes_no_lease_and_walks_nothing( +def test_a_job_with_no_writable_connector_in_the_process_takes_no_lease_and_walks_nothing( monkeypatch: pytest.MonkeyPatch, ) -> None: - """With no SpiralDB store connector in the process, a run builds no lease scope and + """With no writable SpiralDB connector in the process, a run builds no lease scope and walks no graph for one: every entry (sync, async, node run, load-only) on a job with a cached source, a function node, a logged operator node and a sink.""" - monkeypatch.setattr(spiraldb_store_registry, "_store_connectors", weakref.WeakSet()) + monkeypatch.setattr( + spiraldb_writable_registry, "_writable_connectors", weakref.WeakSet() + ) walks: list[None] = [] - real_walk = node_run.store_scope_databases + real_walk = node_run.write_scope_databases def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: walks.append(None) @@ -829,8 +862,8 @@ def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: def no_lease(*args: Any, **kwargs: Any) -> Any: raise AssertionError("a lease scope was built") - monkeypatch.setattr(node_run, "store_scope_databases", counting_walk) - monkeypatch.setattr(spiraldb_write_scope, "store_writes", no_lease) + monkeypatch.setattr(node_run, "write_scope_databases", counting_walk) + monkeypatch.setattr(spiraldb_write_scope, "database_writes", no_lease) calls.clear() delivered.clear() job = _job(InMemoryArrowDatabase()) @@ -844,22 +877,22 @@ def no_lease(*args: Any, **kwargs: Any) -> Any: assert calls != [] -def test_a_store_connector_in_the_process_makes_the_run_walk_for_leases( +def test_a_writable_connector_in_the_process_makes_the_run_walk_for_leases( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """The early return is only for a process without a store connector: with one, the - run walks its graph (and takes the store's lease, as the other tests show).""" + """The early return is only for a process without a writable connector: with one, the + run walks its graph (and takes the database's lease, as the other tests show).""" walks: list[None] = [] - real_walk = node_run.store_scope_databases + real_walk = node_run.write_scope_databases def counting_walk(*args: Any, **kwargs: Any) -> list[Any]: walks.append(None) return real_walk(*args, **kwargs) - monkeypatch.setattr(node_run, "store_scope_databases", counting_walk) - store = _store() - assert spiraldb_store_registry.any_store_connector() - _ = _job(store).run() + monkeypatch.setattr(node_run, "write_scope_databases", counting_walk) + spiral_db = _database() + assert spiraldb_writable_registry.any_writable_connector() + _ = _job(spiral_db).run() assert len(walks) == 1 assert len(_lease_tables()) == 1 @@ -895,7 +928,7 @@ def counting_getattr(obj: Any, name: str, *default: Any) -> Any: with monkeypatch.context() as patch: patch.setattr(node_run, "getattr", counting_getattr, raising=False) - node_run.store_scope_databases(nodes, load_only=load_only) + node_run.write_scope_databases(nodes, load_only=load_only) return len(counted) / len(nodes) small, large = reads_per_node(50), reads_per_node(400) @@ -905,55 +938,57 @@ def counting_getattr(obj: Any, name: str, *default: Any) -> Any: # ------------------------------------------------- review of 291798da3 (ITL-1844) -def test_a_job_on_a_shared_store_connector_takes_the_lease_after_its_original_is_gone( +def test_a_job_on_a_shared_writable_connector_takes_the_lease_after_its_original_is_gone( root: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """A store connector's ``share_client`` copy is a registered store connector: with - the original closed and collected (and no other store connector in the process), + """A writable connector's ``share_client`` copy is a registered writable connector: with + the original closed and collected (and no other writable connector in the process), a job on the copy still takes the lease and stores as on Delta.""" import gc - monkeypatch.setattr(spiraldb_store_registry, "_store_connectors", weakref.WeakSet()) - original = SpiralDBConnector("p", "d", store=True) + monkeypatch.setattr( + spiraldb_writable_registry, "_writable_connectors", weakref.WeakSet() + ) + original = SpiralDBConnector("p", "d", writable=True) shared = original.share_client() original.close() del original _ = gc.collect() - store = ConnectorArrowDatabase(shared) + spiral_db = ConnectorArrowDatabase(shared) delta = DeltaTableDatabase(root / "delta") - assert _job(store).run().ok + assert _job(spiral_db).run().ok assert _job(delta).run().ok - _same_tables(store, delta) + _same_tables(spiral_db, delta) @pytest.mark.usefixtures("root") -def test_a_job_on_a_store_connector_and_its_shared_copy_runs( +def test_a_job_on_a_writable_connector_and_its_shared_copy_runs( monkeypatch: pytest.MonkeyPatch, ) -> None: """A connector and its ``share_client`` copy bound in one run: the run takes ONE - lease of the dataset and attaches it to the store tables of both.""" - from orcapod.databases.spiraldb_store_tables import StoreTables + lease of the dataset and attaches it to the database tables of both.""" + from orcapod.databases.spiraldb_tables import SpiralDBTables - connector = SpiralDBConnector("p", "d", store=True) - store = ConnectorArrowDatabase(connector) + connector = SpiralDBConnector("p", "d", writable=True) + spiral_db = ConnectorArrowDatabase(connector) shared = connector.share_client() results = ConnectorArrowDatabase(shared) held: list[tuple[object, object]] = [] - real_hold = StoreTables.hold_lease + real_hold = SpiralDBTables.hold_lease def recording_hold(self: Any, check: Any) -> None: held.append((self, check)) real_hold(self, check) - monkeypatch.setattr(StoreTables, "hold_lease", recording_hold) - assert _job(store, result_database=results.at("results")).run().ok + monkeypatch.setattr(SpiralDBTables, "hold_lease", recording_hold) + assert _job(spiral_db, result_database=results.at("results")).run().ok assert results.list_table_paths(("results",)) != [] assert len(_lease_tables()) == 1 - tables = [connector._store_tables(), shared._store_tables()] # pyright: ignore[reportPrivateUsage] + tables = [connector._writable_tables(), shared._writable_tables()] # pyright: ignore[reportPrivateUsage] assert len(held) == 2 and held[0][1] is held[1][1] assert {id(t) for t, _ in held} == {id(t) for t in tables} # Released at the end: another writer can take the lease. - _, again = take_lease(SpiralDBConnector("p", "d", store=True), "after") + _, again = take_lease(SpiralDBConnector("p", "d", writable=True), "after") again() @@ -965,9 +1000,9 @@ def test_an_interrupted_let_go_still_releases_every_lease( """An interruption while a lease is let go of locally does not skip its remote release nor the other leases': every lease can be taken again, and the interruption raises (chained from a failed body's error).""" - from orcapod.databases.spiraldb_store_tables import StoreTables + from orcapod.databases.spiraldb_tables import SpiralDBTables - real = StoreTables.let_go_of_lease + real = SpiralDBTables.let_go_of_lease interrupted: list[None] = [] def interrupt_first(self: Any, check: Any) -> None: @@ -976,10 +1011,10 @@ def interrupt_first(self: Any, check: Any) -> None: raise KeyboardInterrupt real(self, check) - monkeypatch.setattr(StoreTables, "let_go_of_lease", interrupt_first) - databases = [_store("d"), _store("r")] + monkeypatch.setattr(SpiralDBTables, "let_go_of_lease", interrupt_first) + databases = [_database("d"), _database("r")] with pytest.raises(KeyboardInterrupt) as raised: - with store_writes(databases, owner="test"): + with database_writes(databases, owner="test"): if body_fails: raise RuntimeError("body") if body_fails: @@ -987,10 +1022,10 @@ def interrupt_first(self: Any, check: Any) -> None: assert isinstance(cause, RuntimeError) and str(cause) == "body" monkeypatch.undo() for dataset in ("d", "r"): - _, again = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + _, again = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") again() # The same databases run again: no lease was left attached to their tables. - with store_writes(databases, owner="next run"): + with database_writes(databases, owner="next run"): pass @@ -1012,33 +1047,33 @@ def fail_then_interrupt(client: Any, lease: Any) -> None: monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) with pytest.raises(KeyboardInterrupt) as raised: - with store_writes([_store("d"), _store("r")], owner="test"): + with database_writes([_database("d"), _database("r")], owner="test"): pass assert len(seen) == 2 assert any("first release failed" in note for note in raised.value.__notes__) -def test_a_decorator_result_database_on_a_store_is_leased(root: Path) -> None: +def test_a_decorator_result_database_on_a_database_is_leased(root: Path) -> None: """A function pod's own result database (``@function_pod(result_database=...)``) - on a store is written under the run's lease on a cache miss, and a pod cache + on a writable SpiralDB database is written under the run's lease on a cache miss, and a pod cache database (``pod_cache_database``) too.""" - on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) - pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", store=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + pod_cache = ConnectorArrowDatabase(SpiralDBConnector("p", "g", writable=True)) @function_pod( output_keys=("total",), - result_database=on_store.at("decorator"), + result_database=on_spiral.at("decorator"), pod_cache_database=pod_cache.at("pod"), ) def add(x: int, y: int) -> int: return x + y - store = _store() - job = PipelineJob(name=JOB, database=store) + spiral_db = _database() + job = PipelineJob(name=JOB, database=spiral_db) with job: - add.pod(_cached(store, _rows()), label="add") + add.pod(_cached(spiral_db, _rows()), label="add") assert job.run().ok - assert on_store.list_table_paths(("decorator",)) != [] + assert on_spiral.list_table_paths(("decorator",)) != [] assert pod_cache.list_table_paths(("pod",)) != [] @@ -1047,7 +1082,7 @@ def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: """A ``share_client`` copy is another connector: while a run holds the lease through the original, a write through the copy (not part of the run) is refused and nothing is written.""" - connector = SpiralDBConnector("p", "d", store=True) + connector = SpiralDBConnector("p", "d", writable=True) outside = ConnectorArrowDatabase(connector.share_client()) row = pa.table( { @@ -1055,11 +1090,11 @@ def test_a_write_through_a_shared_copy_outside_the_run_is_refused() -> None: "v": pa.array([1], pa.int64()), } ) - with store_writes([ConnectorArrowDatabase(connector)], owner="run"): + with database_writes([ConnectorArrowDatabase(connector)], owner="run"): outside.add_record(("elsewhere",), b"r", row, flush=False) - with pytest.raises(SpiralDBStoreLeaseRequiredError): + with pytest.raises(SpiralDBLeaseRequiredError): outside.flush() - assert _store().list_table_paths(("elsewhere",)) == [] + assert _database().list_table_paths(("elsewhere",)) == [] @pytest.mark.usefixtures("root") @@ -1069,20 +1104,20 @@ def test_a_bound_function_pod_stream_built_outside_the_job_is_leased( entry: str, cache: str ) -> None: """A function pod stream built outside the job (it becomes a bound slot) whose - pod caches on a store (``result_database``, or a ``CachedFunctionPod`` through + pod caches on a writable SpiralDB database (``result_database``, or a ``CachedFunctionPod`` through ``pod_cache_database``) writes under the run's lease.""" - on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) def add(x: int, y: int) -> int: return x + y if cache == "result_database": pod = function_pod( - output_keys=("total",), result_database=on_store.at("outside") + output_keys=("total",), result_database=on_spiral.at("outside") )(add) else: pod = function_pod( - output_keys=("total",), pod_cache_database=on_store.at("outside") + output_keys=("total",), pod_cache_database=on_spiral.at("outside") )(add) outside = pod.pod( @@ -1094,11 +1129,11 @@ def add(x: int, y: int) -> int: record_id_columns=["unit", "trial"], ) ) - job = PipelineJob(name=JOB, database=_store()) + job = PipelineJob(name=JOB, database=_database()) with job: SelectDataColumns(["total"])(outside, label="select") _ = _run(job, entry) - assert on_store.list_table_paths(("outside",)) != [] + assert on_spiral.list_table_paths(("outside",)) != [] # ------------------------------------------------- review of e1581afe9 (ITL-1844) @@ -1106,12 +1141,12 @@ def add(x: int, y: int) -> int: @pytest.mark.usefixtures("root") def test_an_interrupted_hold_is_let_go_of(monkeypatch: pytest.MonkeyPatch) -> None: - """An interruption once a lease is attached to a store's tables (before the scope + """An interruption once a lease is attached to a database's tables (before the scope has recorded them) still lets go of it: the next run on the same databases is not refused.""" - from orcapod.databases.spiraldb_store_tables import StoreTables + from orcapod.databases.spiraldb_tables import SpiralDBTables - real = StoreTables.hold_lease + real = SpiralDBTables.hold_lease interrupted: list[None] = [] def attach_then_interrupt(self: Any, check: Any) -> None: @@ -1120,13 +1155,13 @@ def attach_then_interrupt(self: Any, check: Any) -> None: interrupted.append(None) raise KeyboardInterrupt - monkeypatch.setattr(StoreTables, "hold_lease", attach_then_interrupt) - databases = [_store("d")] + monkeypatch.setattr(SpiralDBTables, "hold_lease", attach_then_interrupt) + databases = [_database("d")] with pytest.raises(KeyboardInterrupt): - with store_writes(databases, owner="interrupted"): + with database_writes(databases, owner="interrupted"): pass monkeypatch.undo() - with store_writes(databases, owner="next run"): + with database_writes(databases, owner="next run"): pass @@ -1149,13 +1184,13 @@ def take_then_interrupt(*args: Any, **kwargs: Any) -> Any: return result monkeypatch.setattr(spiraldb_write_scope, "take_lease", take_then_interrupt) - databases = [_store(dataset) for dataset in datasets] + databases = [_database(dataset) for dataset in datasets] with pytest.raises(KeyboardInterrupt): - with store_writes(databases, owner="interrupted"): + with database_writes(databases, owner="interrupted"): pass monkeypatch.undo() for dataset in datasets: - _, release = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") release() @@ -1181,39 +1216,41 @@ def fail_then_interrupt(client: Any, lease: Any) -> None: monkeypatch.setattr(spiraldb_lease, "release", fail_then_interrupt) stopped = body("body stopped") with pytest.raises(KeyboardInterrupt) as raised: - with store_writes([_store("d"), _store("r")], owner="test"): + with database_writes([_database("d"), _database("r")], owner="test"): raise stopped assert raised.value is released assert raised.value.__cause__ is stopped assert any("first release failed" in note for note in raised.value.__notes__) monkeypatch.undo() for dataset in ("d", "r"): - _, release = take_lease(SpiralDBConnector("p", dataset, store=True), "after") + _, release = take_lease(SpiralDBConnector("p", dataset, writable=True), "after") release() @pytest.mark.usefixtures("root") -@pytest.mark.parametrize("job_database", ["in-memory", "store"]) -def test_an_ephemeral_result_database_on_a_store_is_leased(job_database: str) -> None: - """A job's ephemeral result database (``set_ephemeral_database``) on a store is +@pytest.mark.parametrize("job_database", ["in-memory", "spiral"]) +def test_an_ephemeral_result_database_on_a_database_is_leased( + job_database: str, +) -> None: + """A job's ephemeral result database (``set_ephemeral_database``) on a writable SpiralDB database is written under the run's lease: the run succeeds, its results are stored there, and the lease is released.""" from orcapod.types import NodeConfig - database = InMemoryArrowDatabase() if job_database == "in-memory" else _store() - ephemeral = _store("e") + database = InMemoryArrowDatabase() if job_database == "in-memory" else _database() + ephemeral = _database("e") job = PipelineJob(name=JOB, database=database) with job: combine.pod(_cached(InMemoryArrowDatabase(), _rows()), label="combine") job.set_ephemeral_database(ephemeral) job.nodes["combine"].node_config = NodeConfig(is_result_ephemeral=True) assert job.run().ok - fresh = _store("e") + fresh = _database("e") paths = fresh.list_table_paths() assert len(paths) == 1 stored = fresh.get_all_records(paths[0]) assert stored is not None and stored.num_rows == len(_rows()) - _, release = take_lease(SpiralDBConnector("p", "e", store=True), "after") + _, release = take_lease(SpiralDBConnector("p", "e", writable=True), "after") release() @@ -1241,16 +1278,16 @@ def twice(x: int) -> int: @pytest.mark.usefixtures("root") def test_a_held_table_does_not_lease_its_upstream_pods_database() -> None: """A run over a table that holds its rows reads no pod behind it (ITL-1121), so it - takes no lease of that pod's store: it runs while another writer holds it, and the + takes no lease of that pod's database: it runs while another writer holds it, and the pod is not called.""" - on_store = ConnectorArrowDatabase(SpiralDBConnector("p", "f", store=True)) + on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) called: list[int] = [] def add(x: int, y: int) -> int: called.append(x) return x + y - pod = function_pod(output_keys=("total",), result_database=on_store.at("behind"))( + pod = function_pod(output_keys=("total",), result_database=on_spiral.at("behind"))( add ) behind = pod.pod( @@ -1263,7 +1300,7 @@ def add(x: int, y: int) -> int: ) ) node = _twice_over(_held_table_over(behind)) - _, release = take_lease(SpiralDBConnector("p", "f", store=True), "another") + _, release = take_lease(SpiralDBConnector("p", "f", writable=True), "another") try: _ = node.run() finally: @@ -1275,10 +1312,10 @@ def add(x: int, y: int) -> int: @pytest.mark.usefixtures("root") def test_a_cached_source_behind_a_held_table_is_still_leased() -> None: """A run checks every source it finds, also behind a held table, and a check can - write a cached source's cache: its store stays among the run's leased databases.""" - connector = SpiralDBConnector("p", "g", store=True) + write a cached source's cache: its database stays among the run's leased databases.""" + connector = SpiralDBConnector("p", "g", writable=True) cache = ConnectorArrowDatabase(connector) node = _twice_over(_held_table_over(_cached(cache.at("c"), _rows()))) - databases = node_run.store_scope_databases([node], load_only=False) - leased = spiraldb_write_scope.store_connectors(databases) + databases = node_run.write_scope_databases([node], load_only=False) + leased = spiraldb_write_scope.writable_connectors(databases) assert any(c is connector for c in leased) diff --git a/tests/test_databases/type_matrix.py b/tests/test_databases/type_matrix.py index 126e2bb48..e8f08384d 100644 --- a/tests/test_databases/type_matrix.py +++ b/tests/test_databases/type_matrix.py @@ -1108,8 +1108,9 @@ def measure_all(root: Path) -> dict[tuple[str, str], Cell]: The databases: `InMemoryArrowDatabase` (in-memory), `DeltaTableDatabase` (Delta), and `ConnectorArrowDatabase` over `SQLiteConnector` and `PostgreSQLConnector`. Orcapod reads -SpiralDB and writes it only as a job's store ([SpiralDB as a Job's Database](../concepts/spiraldb-store.md)), not compared here. See [The database](../concepts/pipeline-job.md#the-database) for how a -job uses one. +SpiralDB and writes it only as a writable SpiralDB database ([SpiralDB as a Job's +Database](../concepts/spiraldb-database.md)), not compared here. See [The +database](../concepts/pipeline-job.md#the-database) for how a job uses one. Some refusals depend on the values or names as well as the type: diff --git a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py similarity index 85% rename from tests/test_dev_scripts/test_itl_1844_store_evaluation.py rename to tests/test_dev_scripts/test_itl_1844_database_evaluation.py index 979114355..a5e9c43d4 100644 --- a/tests/test_dev_scripts/test_itl_1844_store_evaluation.py +++ b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py @@ -1,4 +1,4 @@ -"""The ITL-1844 store evaluation script reports success only for the expected outcomes.""" +"""The ITL-1844 database evaluation script reports success only for the expected outcomes.""" from __future__ import annotations @@ -17,13 +17,15 @@ / "docs" / "dev" / "scripts" - / "itl_1844_store_evaluation.py" + / "itl_1844_database_evaluation.py" ) @pytest.fixture(scope="module") def script() -> ModuleType: - spec = importlib.util.spec_from_file_location("itl_1844_store_evaluation", _SCRIPT) + spec = importlib.util.spec_from_file_location( + "itl_1844_database_evaluation", _SCRIPT + ) assert spec is not None and spec.loader is not None module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) @@ -32,11 +34,11 @@ def script() -> ModuleType: def _expected() -> dict[str, dict[str, Any]]: return { - "first run": {"ok": True, "calls_on_store": 6}, - "new row": {"ok": True, "calls_on_store": 1, "delivered_on_store": 1}, + "first run": {"ok": True, "calls_on_spiral": 6}, + "new row": {"ok": True, "calls_on_spiral": 1, "delivered_on_spiral": 1}, "replay": {"ok": True}, "separate results": {"ok": True}, - "save and load": {"ok": True, "store_flag_saved": True, "load_only_rows": 7}, + "save and load": {"ok": True, "writable_flag_saved": True, "load_only_rows": 7}, "second writer": {"refused": True, "nothing_written": True}, } @@ -48,10 +50,10 @@ def test_the_expected_outcomes_succeed(script: ModuleType) -> None: @pytest.mark.parametrize( ("scenario", "key", "value"), [ - ("first run", "calls_on_store", 5), - ("new row", "calls_on_store", 7), - ("new row", "delivered_on_store", 7), - ("save and load", "store_flag_saved", False), + ("first run", "calls_on_spiral", 5), + ("new row", "calls_on_spiral", 7), + ("new row", "delivered_on_spiral", 7), + ("save and load", "writable_flag_saved", False), ("save and load", "load_only_rows", 0), ("separate results", "ok", False), ("second writer", "refused", False), @@ -116,7 +118,7 @@ def get_all_records(self, path: tuple[str, ...]) -> pa.Table | None: def test_separate_results_are_compared_table_by_table(script: ModuleType) -> None: - """Each store result table (under ``/results``) is compared with the same + """Each SpiralDB result table (under ``/results``) is compared with the same path in the result database, and every other table with Delta: a wrong row in one result table fails the scenario even when the table count matches.""" one = pa.table({"v": pa.array([1], pa.int64())}) @@ -147,13 +149,13 @@ def failing(*args: object) -> None: monkeypatch.setattr(script, "lease_tables", down) monkeypatch.setattr(script, "store_tables", down) monkeypatch.setattr(script, "evaluate", failing) - monkeypatch.setattr(sys, "argv", ["itl_1844_store_evaluation.py", "fake"]) + monkeypatch.setattr(sys, "argv", ["itl_1844_database_evaluation.py", "fake"]) assert script.main() == 1 report = json.loads(capsys.readouterr().out) assert report["ok"] is False assert report["error"] == "ConnectionError: scenario failed" assert set(report["inventory_errors"]) == { "lease tables before", - "store tables", + "database tables", "lease tables after", } diff --git a/tests/test_pipeline/test_observer_databases.py b/tests/test_pipeline/test_observer_databases.py index 467ba36f3..508189494 100644 --- a/tests/test_pipeline/test_observer_databases.py +++ b/tests/test_pipeline/test_observer_databases.py @@ -1,4 +1,4 @@ -"""Observer setup rejects SpiralDB stores before any recording can start.""" +"""Observer setup rejects SpiralDB databases before any recording can start.""" from __future__ import annotations @@ -41,7 +41,7 @@ class _DerivedExtensionWrapper(ExtensionAwareDatabase): class _DerivedSpiralConnector(SpiralDBConnector): - """A SpiralDB connector subclass still uses the same store.""" + """A SpiralDB connector subclass still uses the same database.""" class _SlottedExtensionWrapper(ExtensionAwareDatabase): @@ -100,10 +100,10 @@ def capture_install() -> Iterator[Mock]: @pytest.fixture(params=["wrapper-slot", "connector-slot"]) -def slotted_spiral_store( +def slotted_spiral_database( request: pytest.FixtureRequest, spiral_connector: SpiralDBConnector ) -> ArrowDatabaseProtocol: - """Build a SpiralDB store with one of the inspected references in a slot.""" + """Build a SpiralDB database with one of the inspected references in a slot.""" if cast(str, request.param) == "wrapper-slot": return _SlottedExtensionWrapper( ConnectorArrowDatabase(spiral_connector), UniversalTypeConverter() @@ -112,7 +112,7 @@ def slotted_spiral_store( def _wrap(db: ArrowDatabaseProtocol) -> ExtensionAwareDatabase: - """Wrap a store in the extension-aware read layer.""" + """Wrap a database in the extension-aware read layer.""" return ExtensionAwareDatabase(db, UniversalTypeConverter()) @@ -126,7 +126,7 @@ def _wrap(db: ArrowDatabaseProtocol) -> ExtensionAwareDatabase: "doubly-wrapped", ] ) -def store_view( +def database_view( request: pytest.FixtureRequest, ) -> Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol]: """Build each supported arrangement of scopes and extension wrappers.""" @@ -143,19 +143,19 @@ def store_view( _OBSERVERS = [StatusObserver, LoggingObserver] _REFUSAL = ( - r"^Observers cannot record to a SpiralDB store in this version\. " + r"^Observers cannot record to a SpiralDB database in this version\. " + r"Give the observer another database, for example Delta\.$" ) @pytest.mark.parametrize("observer_class", _OBSERVERS) -def test_spiral_store_is_refused_at_setup( +def test_spiral_database_is_refused_at_setup( observer_class: type[StatusObserver] | type[LoggingObserver], spiral_connector: SpiralDBConnector, - store_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], + database_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], capture_install: Mock, ) -> None: - db = store_view(ConnectorArrowDatabase(spiral_connector)) + db = database_view(ConnectorArrowDatabase(spiral_connector)) with ( patch.object(spiral_connector, "get_table_names") as get_table_names, patch.object(spiral_connector, "create_table_if_not_exists") as create_table, @@ -172,7 +172,7 @@ def test_spiral_store_is_refused_at_setup( @pytest.mark.parametrize("observer_class", _OBSERVERS) -def test_spiral_store_subclasses_are_refused( +def test_spiral_database_subclasses_are_refused( observer_class: type[StatusObserver] | type[LoggingObserver], tmp_path: Path, capture_install: Mock, @@ -191,34 +191,34 @@ def test_spiral_store_subclasses_are_refused( @pytest.mark.parametrize("observer_class", _OBSERVERS) -def test_spiral_store_with_slotted_reference_is_refused( +def test_spiral_database_with_slotted_reference_is_refused( observer_class: type[StatusObserver] | type[LoggingObserver], - slotted_spiral_store: ArrowDatabaseProtocol, + slotted_spiral_database: ArrowDatabaseProtocol, capture_install: Mock, ) -> None: with pytest.raises(SpiralDBObserverNotSupportedError, match=_REFUSAL): - _ = observer_class(slotted_spiral_store) + _ = observer_class(slotted_spiral_database) capture_install.assert_not_called() @pytest.mark.parametrize("use_resolver", [False, True]) -def test_nested_composite_refuses_slotted_spiral_store_before_capture( +def test_nested_composite_refuses_slotted_spiral_database_before_capture( use_resolver: bool, - slotted_spiral_store: ArrowDatabaseProtocol, + slotted_spiral_database: ArrowDatabaseProtocol, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, capture_install: Mock, ) -> None: - class RegisteredStore: + class RegisteredDatabase: @classmethod def from_config(cls, _config: dict[str, object]) -> ArrowDatabaseProtocol: - return slotted_spiral_store + return slotted_spiral_database monkeypatch.setattr( serialization, "DATABASE_REGISTRY", serialization.DATABASE_REGISTRY.copy() ) - serialization.register_database("test_slotted_spiral", RegisteredStore) + serialization.register_database("test_slotted_spiral", RegisteredDatabase) delta_path = tmp_path / "delta" config: dict[str, object] = { "type": "composite", @@ -316,14 +316,14 @@ def resolve( if not logging_first: children.reverse() - with pytest.raises(SpiralDBObserverNotSupportedError, match=r"SpiralDB store"): + with pytest.raises(SpiralDBObserverNotSupportedError, match=r"SpiralDB database"): _ = CompositeObserver.from_config({"observers": children}) capture_install.assert_not_called() @pytest.mark.parametrize("observer_class", _OBSERVERS) -def test_spiral_store_resolved_from_config_is_refused( +def test_spiral_database_resolved_from_config_is_refused( observer_class: type[StatusObserver] | type[LoggingObserver], spiral_connector: SpiralDBConnector, monkeypatch: pytest.MonkeyPatch, @@ -345,11 +345,11 @@ def test_spiral_store_resolved_from_config_is_refused( @pytest.mark.parametrize("observer_class", _OBSERVERS) @pytest.mark.parametrize("backend", ["memory", "delta", "sqlite", "noop"]) -def test_other_stores_are_accepted( +def test_other_databases_are_accepted( observer_class: type[StatusObserver] | type[LoggingObserver], backend: str, tmp_path: Path, - store_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], + database_view: Callable[[ArrowDatabaseProtocol], ArrowDatabaseProtocol], capture_install: Mock, ) -> None: with SQLiteConnector() as sqlite: @@ -359,7 +359,7 @@ def test_other_stores_are_accepted( "sqlite": ConnectorArrowDatabase(sqlite), "noop": NoOpArrowDatabase(), } - observer = observer_class(store_view(roots[backend])) + observer = observer_class(database_view(roots[backend])) composite = CompositeObserver(observer).contextualize("node") composite.on_run_start("test-run") composite.on_run_end("test-run") From 047dbe2909c433a38ae3f6055e21d0ea250f1c53 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:06:29 -0800 Subject: [PATCH 48/50] fix(spiraldb): review of de39bbc4c: lease refusal keeps the save state, load-only leases no pod stream, writable must be a bool (ITL-1844) - A run refused its writer lease no longer clears the last run's save state: the flag is cleared once the leases are held, before the sources are checked. - A load-only run takes no lease of a function pod stream built outside the job (it reads none: the input refusal is its error, never LeaseBusyError); cached-source caches stay leased. - A saved SpiralDB connector whose writable is not a boolean is refused at load, whatever database is given. - Rename leftovers: the evaluation report key database_tables, the load docstring says writable or plain. - The same-dataset separate result database test compares every table's rows and types with Delta. Co-Authored-By: Claude Opus 5.5 --- .../scripts/itl_1844_database_evaluation.py | 6 +- src/orcapod/pipeline/job.py | 14 +-- src/orcapod/pipeline/node_run.py | 12 ++- src/orcapod/pipeline/serialization.py | 11 ++- .../test_spiraldb_writable_runs.py | 92 ++++++++++++++++++- .../test_itl_1844_database_evaluation.py | 2 +- 6 files changed, 117 insertions(+), 20 deletions(-) diff --git a/docs/dev/scripts/itl_1844_database_evaluation.py b/docs/dev/scripts/itl_1844_database_evaluation.py index e33ec9b5f..7bf6606a6 100644 --- a/docs/dev/scripts/itl_1844_database_evaluation.py +++ b/docs/dev/scripts/itl_1844_database_evaluation.py @@ -369,7 +369,7 @@ def succeeded(scenarios: dict[str, Any]) -> bool: ) -def store_tables(project: str, dataset: str, stamp: str) -> list[dict[str, str]]: +def database_tables(project: str, dataset: str, stamp: str) -> list[dict[str, str]]: """Every database table of this evaluation's jobs, by name and layout. Listed under each job name only: a listing of the whole dataset is refused when the @@ -452,10 +452,10 @@ def main() -> int: report["ok"] = False # Every table this run made, also after a failed scenario; an inventory that # fails (the service still down) is reported apart and never hides the report. - report["store_tables"] = inventory( + report["database_tables"] = inventory( report, "database tables", - lambda: store_tables(args.project, args.dataset, stamp), + lambda: database_tables(args.project, args.dataset, stamp), ) after = inventory( report, diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 6626e5865..5d73ab2b7 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1737,8 +1737,6 @@ def _prepare_run( if key not in excluded_hashes ] _refuse_shadowed_steps(runnable_nodes) - # Once preflight passes, stored row counts may change during the run. - self._last_run_finished = False # --- Build execution OrcaDAG from existing node objects (no cloning) --- exec_dag: OrcaDAG = OrcaDAG() @@ -1798,6 +1796,9 @@ def _prepare_run( owner=run_owner("/".join(self._name)), ) ) + # Once preflight passes and the leases are held, stored row counts may change + # during the run. A run refused its lease keeps the last run's save state. + self._last_run_finished = False # Every source first takes in any new data, moving its modified time, before # the state rule judges any node (ITL-1102). unchecked = check_sources(exec_dag.nodes()) @@ -2312,13 +2313,14 @@ def load( path: Path to the JSON file produced by ``save()``. database: Optional database override. When provided, takes precedence over any database configuration in the file. Required when the file's - database is a connector database. A SpiralDB database must be of the - saved kind (store or plain); any other database may be given. + database is a connector database. When the saved and the given databases + are both SpiralDB, their modes (writable or plain) must match; any + other database may be given. result_database: Optional override of the separate function-result database (ITL-1408), required when the file names a connector database. When provided, it is used whatever the file - says, except that a SpiralDB database must be of the saved kind - (store or plain). Otherwise the one the file names is rebuilt from its saved + says, except that when the saved and the given databases are both + SpiralDB, their modes (writable or plain) must match. Otherwise the one the file names is rebuilt from its saved configuration, as the job's database is; a file that names none keeps the results in the job's database (``/_result``). When the file names one that cannot be rebuilt, the function nodes get no diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index 23d47d96b..bb6668475 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -245,7 +245,7 @@ def run_sources(streams: Iterable[Any]) -> list[Any]: return found -def _source_side_databases(streams: Iterable[Any]) -> list[Any]: +def _source_side_databases(streams: Iterable[Any], *, load_only: bool) -> list[Any]: """The databases written by what feeds ``streams`` from outside the job's nodes, through bound sources, wrapped sources and streams. @@ -255,8 +255,10 @@ def _source_side_databases(streams: Iterable[Any]) -> list[Any]: slot computes, and writes its pod's caches, when the run reads it; ``_pod_result_databases``). Behind an ``ArrowTableStream`` no pod is read: the table holds its rows, whatever its ``upstreams`` name (ITL-1121), so only the - caches of the sources there are collected. Each stream is visited at most twice, - behind a table and not (linear in the size of the graph). + caches of the sources there are collected. A load-only run reads no function pod + stream (``refuse_unloadable_inputs`` refuses one), so it leases none of their + databases: the refusal is the error it gives, never a busy lease. Each stream is + visited at most twice, behind a table and not (linear in the size of the graph). """ from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources.cached_source import CachedSource @@ -276,7 +278,7 @@ def _source_side_databases(streams: Iterable[Any]) -> list[Any]: continue if isinstance(stream, CachedSource): found.append(stream._cache_database) # pyright: ignore[reportPrivateUsage] # the database a run must hold the lease of - if not behind_table and not _is_job_node(stream): + if not load_only and not behind_table and not _is_job_node(stream): # A job node's pods: ``write_scope_databases``. found.extend(db for db in _pod_result_databases(stream) if db is not None) behind = behind_table or isinstance(stream, ArrowTableStream) @@ -337,7 +339,7 @@ def write_scope_databases( written.extend( db for node in nodes for db in _pod_result_databases(node) if db is not None ) - written.extend(_source_side_databases(streams)) + written.extend(_source_side_databases(streams, load_only=load_only)) return written diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index a16513144..4d15ca79e 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -589,8 +589,8 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: writable=True)``, ITL-1844) is loaded with a writable connector, and one saved on a plain SpiralDB connector with a plain one: the two read different tables. The project and dataset are not compared (a job may be pointed at a copy). A saved - SpiralDB connector with a ``store`` key is refused whatever is given: it is not an - option of this version. + SpiralDB connector with a ``store`` key, or a ``writable`` that is not a boolean, is + refused whatever is given: ``store`` is not an option of this version. Args: config: The saved database configuration. @@ -612,13 +612,18 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) if "store" in saved: return STORE_KEY_REFUSAL + saved_writable = saved.get("writable", False) + if not isinstance(saved_writable, bool): + return ( + "the saved SpiralDB connector's 'writable' is " + f"{saved_writable!r}, not true or false" + ) given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over if not isinstance(connector, SpiralDBConnector): return None - saved_writable = saved.get("writable", False) is True given_writable = connector._writable # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a writable database if saved_writable == given_writable: return None diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index f837d0e9d..9338eb7f2 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -240,8 +240,9 @@ def test_every_table_kind_is_stored_as_on_delta( def test_a_separate_result_database_is_stored_as_on_delta( root: Path, entry: str, dataset: str ) -> None: - """Results in a separate result database, on another dataset (two leases) or on the same - dataset through another connector (one lease).""" + """Results in a separate result database, on another dataset (two leases) or on + the same dataset through another connector (one lease), table by table as on + Delta.""" spiral_db, results = _database(), _database("r" if dataset == "other" else "d") delta = DeltaTableDatabase(root / "delta") delta_results = DeltaTableDatabase(root / "delta_results") @@ -257,6 +258,16 @@ def test_a_separate_result_database_is_stored_as_on_delta( [*delta.list_table_paths(), *delta_results.list_table_paths()] ) assert sorted(spiral_db.list_table_paths()) == on_delta + on_results = set(delta_results.list_table_paths()) + for path in on_delta: + on_spiral = spiral_db.get_all_records(path) + expected = (delta_results if path in on_results else delta).get_all_records( + path + ) + assert on_spiral is not None and expected is not None, path + assert on_spiral.schema.names == expected.schema.names, path + assert _types(on_spiral) == _types(expected), path + assert _comparable(on_spiral) == _comparable(expected), path assert len(_lease_tables("d")) == LEASES[entry] @@ -368,6 +379,24 @@ def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( _ = PipelineJob.load(saved, database=given) +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("given_writable", [True, False]) +@pytest.mark.parametrize("saved_value", ["true", 1, None]) +def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( + root: Path, given_writable: bool, saved_value: object +) -> None: + """A saved ``writable`` of another type is not read as plain (review of + de39bbc4c).""" + saved = root / "job.json" + _job(_database()).save(saved) + data = json.loads(saved.read_text()) + data["bindings"]["database"]["connector"]["writable"] = saved_value + saved.write_text(json.dumps(data)) + given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + with pytest.raises(ValueError, match="'writable' is .*not true or false"): + _ = PipelineJob.load(saved, database=given) + + @pytest.mark.usefixtures("root") def test_a_spiraldb_connector_config_with_a_store_key_is_refused() -> None: config = SpiralDBConnector("p", "d", writable=True).to_config() @@ -1136,6 +1165,65 @@ def add(x: int, y: int) -> int: assert on_spiral.list_table_paths(("outside",)) != [] +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("entry", ["sync", "async orchestrator", "run_async"]) +def test_a_load_only_run_over_an_outside_function_pod_stream_is_refused_not_busy( + entry: str, +) -> None: + """A load-only run reads no function pod stream built outside the job, so it takes + no lease of that pod's database: on a busy dataset it gives the refusal that says + how to run the input, never ``LeaseBusyError`` (review of de39bbc4c).""" + on_spiral = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + + def add(x: int, y: int) -> int: + return x + y + + pod = function_pod(output_keys=("total",), result_database=on_spiral.at("outside"))( + add + ) + outside = pod.pod( + ArrowTableSource( + _rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ) + ) + job = PipelineJob(name=JOB, database=_database()) + with job: + SelectDataColumns(["total"])(outside, label="select") + release = _held_by_another_writer("f") + try: + with pytest.raises(ValueError, match="function pod") as refused: + _ = _run(job, entry, load_only=True) + assert not isinstance(refused.value, spiraldb_lease.LeaseBusyError) + finally: + release() + assert on_spiral.list_table_paths(("outside",)) == [] + + +@pytest.mark.usefixtures("root") +def test_a_run_refused_its_lease_keeps_the_last_runs_save_state(root: Path) -> None: + """A run refused with ``LeaseBusyError`` changes nothing: a save afterwards records + the last completed run's row counts as a save before it did (review of + de39bbc4c).""" + job = _job(_database()) + _ = job.run() + before, after = root / "before.json", root / "after.json" + job.save(before) + expected = json.loads(before.read_text())["run"]["expected_rows"] + assert expected + release = _held_by_another_writer() + try: + with pytest.raises(spiraldb_lease.LeaseBusyError): + _ = job.run() + finally: + release() + job.save(after) + assert json.loads(after.read_text())["run"].get("expected_rows") == expected + + # ------------------------------------------------- review of e1581afe9 (ITL-1844) diff --git a/tests/test_dev_scripts/test_itl_1844_database_evaluation.py b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py index a5e9c43d4..f489e132d 100644 --- a/tests/test_dev_scripts/test_itl_1844_database_evaluation.py +++ b/tests/test_dev_scripts/test_itl_1844_database_evaluation.py @@ -147,7 +147,7 @@ def failing(*args: object) -> None: raise ConnectionError("scenario failed") monkeypatch.setattr(script, "lease_tables", down) - monkeypatch.setattr(script, "store_tables", down) + monkeypatch.setattr(script, "database_tables", down) monkeypatch.setattr(script, "evaluate", failing) monkeypatch.setattr(sys, "argv", ["itl_1844_database_evaluation.py", "fake"]) assert script.main() == 1 From 637fc8551fdc0b0ce08878802431a2b019fc7659 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:58:53 -0800 Subject: [PATCH 49/50] fix(spiraldb): delta review of 047dbe290: earlier key is another format, load-only follows live inputs, saved config refused first (ITL-1844) - A table whose metadata holds the earlier draft's key (any value, beside the current key or not), or the earlier value under either key, is of the earlier draft's format: listed as another format, never read or appended to. - A load-only run refuses, before any lease or source check, a source whose live inputs (live_source_inputs) reach a function pod or side-effect pod built outside the job. - A saved SpiralDB connector with a "store" key or a non-bool "writable" is refused before a missing connector override is reported. - Text: a writable SpiralDBConnector can be a job's database; a plain one refuses writes; leftover "store" wording reworded. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1186.md | 2 +- docs/concepts/sources.md | 7 +- .../databases/connector_arrow_database.py | 4 +- .../databases/spiral_database_identity.py | 20 +++- src/orcapod/databases/spiraldb_connector.py | 21 ++-- src/orcapod/errors.py | 9 +- src/orcapod/pipeline/job.py | 19 ++- src/orcapod/pipeline/node_run.py | 102 ++++++++++++---- src/orcapod/pipeline/serialization.py | 51 +++++--- tests/test_databases/test_spiraldb_reading.py | 2 +- .../test_spiraldb_writable_mode.py | 56 ++++++++- .../test_spiraldb_writable_runs.py | 110 ++++++++++++++++-- 12 files changed, 323 insertions(+), 80 deletions(-) diff --git a/changelog.d/ITL-1186.md b/changelog.d/ITL-1186.md index 01dc142c2..d7c59cc94 100644 --- a/changelog.d/ITL-1186.md +++ b/changelog.d/ITL-1186.md @@ -1,7 +1,7 @@ ### Breaking changes and migration - SpiralDB is read through `spiral-sdk` (the `spiraldb` extra pins `spiral-sdk==0.16.74`), and `pyspiral` is gone. Both packages provide a module named `spiral`: install into an environment without `pyspiral`. -- Orcapod only reads SpiralDB for now. Every write of `SpiralDBConnector` (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. Writing is a follow-up of ITL-1186. +- A plain `SpiralDBConnector` only reads. Every write of a plain connector (`create_table_if_not_exists`, `upsert_records`, `delete_table`) and every job whose database is on one raises `SpiralDBWriteNotSupportedError`, before anything is buffered or run. A job keeps its tables in SpiralDB through a writable SpiralDB database, `SpiralDBConnector(..., writable=True)` (ITL-1844). - A table's non-nullable columns and Arrow metadata are read from its dataset's schema table, `__orcapod_schemas__`, not from the table's metadata. Datasets written by an earlier release must be migrated once with `scripts/migrate_spiral_schemas.py` (`RELEASING.md`); then schemas, hashes and source ids are as before. Until then their tables read with every column nullable, with `UnrecordedTableSchemaWarning`, and their hashes differ. - `read_nullability_record` and `write_nullability_record` are removed, and `NullabilityRecordError` is replaced by `TableSchemaError`. - Row counts are counted from the keys: `row_count_estimate` is exact and reads every key, the `max_rows` check reads at most `max_rows + 1` keys, and a preview of more than 100,000 rows shows no total. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 82926a1d4..39403ae94 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -553,9 +553,10 @@ again only when the version moved. A changed environment or saved login, or a cl whose calls failed, gives the next new source a new client. Closing a source affects no other; the client goes with the last source that uses it, and a forked process starts with none. -Orcapod only reads SpiralDB for now. Writing a SpiralDB table (`SpiralDBConnector`, or a job -whose database is on one) raises `SpiralDBWriteNotSupportedError`; store a job's results in -another database, such as `DeltaTableDatabase`. +A plain `SpiralDBConnector` only reads: a write through it (or a job whose database is on +one) raises `SpiralDBWriteNotSupportedError`. A job can keep its tables in SpiralDB through +a writable SpiralDB database, `SpiralDBConnector(..., writable=True)`: see +[SpiralDB as a Job's Database](spiraldb-database.md). To find the tables of a project and their key columns: diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 9866f7b71..db796bf55 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -495,7 +495,7 @@ def _get_committed_table( Raises: OrcapodDatabaseReadError: If the table cannot be found or read, on - every connector (finding it reads the store too): a lookup that + every connector (finding it reads the database too): a lookup that cannot read the stored table fails the run rather than one row (``job.run``'s contract for an unreadable stored table), as ``get_table_schema`` does. @@ -508,7 +508,7 @@ def _get_committed_table( # not be reported as a stored table that could not be read. self._require_table_name(table_name) try: - # Finding the table reads the store too (a SpiralDB table's metadata, a + # Finding the table reads the database too (a SpiralDB table's metadata, a # SQL catalog): a failure there is a read error, as in ``get_table_schema``. table = self._find_committed_table(table_name, full_path, schema=schema) if table is None: diff --git a/src/orcapod/databases/spiral_database_identity.py b/src/orcapod/databases/spiral_database_identity.py index 9cbb5639c..513246614 100644 --- a/src/orcapod/databases/spiral_database_identity.py +++ b/src/orcapod/databases/spiral_database_identity.py @@ -76,17 +76,25 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: DATA_CONTEXT_KEY = "orcapod.data_context" _RECORD_KEYS = (FORMAT_KEY, PATH_KEY, LAYOUT_KEY, DATA_CONTEXT_KEY) EARLIER_DRAFT_FORMAT_KEY = "orcapod.store" -"""The key an earlier draft of the format recorded its format under (before 0.4.0). +"""The key an earlier draft of the format recorded its format under (before 0.4.0).""" -A table that records its format there is of another table format: a listing reports it -as one, and it is never read or written.""" +EARLIER_DRAFT_FORMAT = "orcapod.spiral_store.draft" +"""The format value an earlier draft recorded (before 0.4.0).""" def _with_format_entry(metadata: Mapping[str, bytes]) -> Mapping[str, bytes]: - """The metadata, with an earlier draft's format entry under ``FORMAT_KEY``.""" - if FORMAT_KEY in metadata or EARLIER_DRAFT_FORMAT_KEY not in metadata: + """The metadata, with the format of an earlier draft's table under ``FORMAT_KEY``. + + A table whose metadata holds ``EARLIER_DRAFT_FORMAT_KEY`` (with any value, beside + ``FORMAT_KEY`` or not), or ``EARLIER_DRAFT_FORMAT`` under ``FORMAT_KEY``, is of the + earlier draft's format, whatever else it records: a listing reports it as that + format, and it is never read or written. No value of the old key is taken as this + format. + """ + earlier = EARLIER_DRAFT_FORMAT.encode() + if EARLIER_DRAFT_FORMAT_KEY not in metadata and metadata.get(FORMAT_KEY) != earlier: return metadata - return {**metadata, FORMAT_KEY: metadata[EARLIER_DRAFT_FORMAT_KEY]} + return {**metadata, FORMAT_KEY: earlier} def spiral_table_name(path: Sequence[str]) -> str: diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 8fc964488..ac7b5cb0f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -83,9 +83,9 @@ _SCAN_BATCH_ROWS = 8_192 _LIST_TIMEOUT_S = 60 _NO_WRITES = ( - "Orcapod does not write SpiralDB tables through spiral-sdk yet; it reads them. Writing " - "is a follow-up of ITL-1186. Nothing was written. Store a job's results in another " - "database, for example DeltaTableDatabase." + "a plain SpiralDBConnector only reads SpiralDB tables; nothing was written. A job " + "keeps its tables in SpiralDB through a writable SpiralDB database: " + "ConnectorArrowDatabase(SpiralDBConnector(..., writable=True))" ) # Tables a warning was issued for in this process (``UnrecordedTableSchemaWarning``). _warned_unrecorded: set[tuple[str, str]] = set() @@ -1463,7 +1463,7 @@ def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> in return self.lookup_table(table_name).row_count_estimate(asof=asof) def delete_table(self, table_name: str) -> None: - """Refuse to drop a table: Orcapod does not write SpiralDB yet. + """Refuse to drop a table: this connector writes nothing directly. Raises: SpiralDBWriteNotSupportedError: Always (ITL-1186). @@ -1477,7 +1477,7 @@ def create_table_if_not_exists( columns: list[ColumnInfo], pk_column: str, ) -> None: - """Refuse to create a table: Orcapod does not write SpiralDB yet. + """Refuse to create a table: this connector writes nothing directly. Raises: ValueError: If the name is reserved for an internal table. @@ -1501,7 +1501,7 @@ def upsert_records( id_column: str, skip_existing: bool = False, ) -> None: - """Refuse to write rows: Orcapod does not write SpiralDB yet. + """Refuse to write rows: this connector writes nothing directly. Raises: SpiralDBWriteNotSupportedError: Always (ITL-1186). @@ -1519,8 +1519,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. + """Refuse every column: a plain connector writes nothing. A job whose database is + on a plain connector is refused when the database is attached, before it runs (a + writable SpiralDB database checks its columns itself). Args: name: The column's name. @@ -1546,8 +1547,8 @@ 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. + """Refuse the rows: a plain connector writes nothing. Called before a database on + a plain connector buffers them. Args: records: The rows. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 14a42d9f3..c4ee3e373 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -730,11 +730,12 @@ def __init__(self, reason: str, *, table: str | None = None) -> None: class SpiralDBWriteNotSupportedError(NotImplementedError): - """Orcapod does not write SpiralDB through spiral-sdk yet (ITL-1186): it reads it. + """A plain SpiralDB connector was asked to write: it only reads (ITL-1186). - Raised by every write of ``SpiralDBConnector`` (creating or deleting a table, storing - rows), so also by a job whose database is a ``ConnectorArrowDatabase`` on one. Nothing - is written. Writing is a follow-up of ITL-1186. + Raised by every write of a plain ``SpiralDBConnector`` (creating or deleting a table, + storing rows), so also by a job whose database is a ``ConnectorArrowDatabase`` on one. + Nothing is written. A job keeps its tables in SpiralDB through a writable SpiralDB + database, ``SpiralDBConnector(..., writable=True)`` (ITL-1844). """ diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 5d73ab2b7..ab08c137d 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2352,7 +2352,8 @@ def load( (ITL-1844). Only a SpiralDB database of the other kind is refused: a database that is not a SpiralDB one may stand for a saved SpiralDB database. A saved SpiralDB connector with a ``store`` key - is refused whatever database is given. + or a ``writable`` that is not a boolean is refused whatever + database is given, also when none is (checked first). """ import json as _json import os @@ -2371,6 +2372,7 @@ def load( saved_connector_kind, saved_database_kind, saved_source_kind, + spiraldb_saved_config_refusal, spiraldb_writable_mismatch, warn_saved_tags_as_data, ) @@ -2388,6 +2390,21 @@ def load( exc.add_note(f"Loading the job file {path}") raise + # A saved SpiralDB connector configuration this version does not read (a + # ``store`` key, a ``writable`` that is not a boolean) is refused first, given + # a connector or not, so an old file is told about writable=True (ITL-1844). + unreadable = [ + f"bindings.{slot_name}: {reason}" + for slot_name in ("database", "result_database") + if ( + reason := spiraldb_saved_config_refusal( + data.get("bindings", {}).get(slot_name) + ) + ) + is not None + ] + if unreadable: + raise ValueError(f"{path}: " + "; ".join(unreadable) + ".") # A connector is supplied by the user, never rebuilt from the file (ITL-1391): # refused before anything is rebuilt. Nothing of the saved configuration is # shown. diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py index bb6668475..f6e5a0680 100644 --- a/src/orcapod/pipeline/node_run.py +++ b/src/orcapod/pipeline/node_run.py @@ -61,20 +61,28 @@ def _streams_read_by(node: Any) -> Iterator[Any]: """Yield the streams outside a job that a run of ``node`` reads. The node's inputs, the stream bound to a source slot among them, and, through every - stream outside a job, that stream's own inputs. A job node other than a source slot - is not entered: the run reads the rows the node holds (none if it has not run in - this process). Nor is an ``ArrowTableStream``: reading it reads only the table it - holds, whatever its ``upstreams`` name (ITL-1121). + stream outside a job, that stream's own inputs and the inputs a source reads live + (``live_source_inputs``, a wrapper's such as a ``CachedSource``'s). A job node + other than a source slot is not entered: the run reads the rows the node holds + (none if it has not run in this process). Nor are the ``upstreams`` of an + ``ArrowTableStream``: reading it reads only the table it holds, whatever they name + (ITL-1121). Args: node: A job node; for a source slot, its bound stream is what it reads. """ from orcapod.core.nodes.source_node import SourceJobNode + + start = [node.bound_source] if isinstance(node, SourceJobNode) else node.upstreams + yield from _streams_reached(start) + + +def _streams_reached(start: Iterable[Any]) -> Iterator[Any]: + """Yield the streams outside a job read through ``start`` (``_streams_read_by``).""" + from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.streams.arrow_table_stream import ArrowTableStream - pending: list[Any] = ( - [node.bound_source] if isinstance(node, SourceJobNode) else list(node.upstreams) - ) + pending: list[Any] = list(start) seen: list[Any] = [] while pending: stream = pending.pop() @@ -87,10 +95,60 @@ def _streams_read_by(node: Any) -> Iterator[Any]: if _is_job_node(stream): continue yield stream + pending.extend(getattr(stream, "live_source_inputs", None) or ()) if not isinstance(stream, ArrowTableStream): pending.extend(getattr(stream, "upstreams", ())) +def _unloadable(stream: Any) -> str | None: + """What a stream outside a job does when read that a load-only run cannot, or + ``None`` when a load-only run can read it.""" + from orcapod.core.function_pod import FunctionPodStream + from orcapod.side_effects import SideEffectNode, SideEffectPodStream + + # A SideEffectJobNode is a job node: the walks never yield one. + if isinstance(stream, (SideEffectPodStream, SideEffectNode)): + return ( + "a side-effect pod's stream outside a job, which delivers its side " + "effects when it is read, and a load-only run delivers nothing" + ) + if isinstance(stream, FunctionPodStream): + return ( + "a function pod's stream outside a job, which computes when it is " + "read, and a load-only run computes nothing" + ) + return None + + +def refuse_unloadable_source_checks(streams: Iterable[Any]) -> None: + """Refuse a load-only run whose source check would read an input which computes or + delivers when it is read. + + A run checks every source feeding it (``check_sources``) before it plans, and a + source that reads another stream live (``live_source_inputs``: a ``CachedSource`` + over a source that reads a function pod's stream) reads that input when checked. + So a load-only run is refused, as ``refuse_unloadable_inputs`` refuses a node, + before any lease is taken, any source checked or anything written. + + Args: + streams: The nodes of the run, or the node whose ``run()`` it is. + + Raises: + ValueError: If a source the run checks would read such a stream. + """ + for source in run_sources(streams): + for upstream in _streams_reached( + getattr(source, "live_source_inputs", None) or () + ): + what = _unloadable(upstream) + if what is not None: + raise ValueError( + f"A load-only run cannot check source {source_name(source)!r}: " + f"its input {upstream.label!r} is {what}. Build the pod inside " + "the job, or run without load_only." + ) + + def refuse_unloadable_inputs(node: Any) -> None: """Refuse a load-only run of ``node`` that would read an input which computes or delivers when it is read. @@ -103,7 +161,7 @@ def refuse_unloadable_inputs(node: Any) -> None: (``SideEffectNode``, the blueprint a ``Pipeline`` records) delivers its side effects. Such a stream is refused before anything is read, whether it is an input of ``node``, bound to a source slot, or read through another stream outside a job (an - operator's stream over it). + operator's stream over it, a source reading it live). Args: node: A job node a load-only run would run or read. @@ -111,22 +169,9 @@ def refuse_unloadable_inputs(node: Any) -> None: Raises: ValueError: If a run of ``node`` would read such a stream. """ - from orcapod.core.function_pod import FunctionPodStream - from orcapod.side_effects import SideEffectNode, SideEffectPodStream - for upstream in _streams_read_by(node): - # A SideEffectJobNode is a job node: _streams_read_by never yields one. - if isinstance(upstream, (SideEffectPodStream, SideEffectNode)): - what = ( - "a side-effect pod's stream outside a job, which delivers its side " - "effects when it is read, and a load-only run delivers nothing" - ) - elif isinstance(upstream, FunctionPodStream): - what = ( - "a function pod's stream outside a job, which computes when it is " - "read, and a load-only run computes nothing" - ) - else: + what = _unloadable(upstream) + if what is None: continue raise ValueError( f"A load-only run cannot run node {node.label!r}: its input " @@ -354,7 +399,9 @@ def database_write_scope( (ITL-1844). The run may write the databases ``write_scope_databases`` lists. Entered before the - run checks its sources (``spiraldb_write_scope.database_writes``). When no writable + run checks its sources (``spiraldb_write_scope.database_writes``). A load-only run + whose source check would read an input that computes or delivers is refused first + (``refuse_unloadable_source_checks``). When no writable SpiralDB connector exists in the process, no run can write one: nothing is walked and the scope holds nothing. @@ -367,9 +414,16 @@ def database_write_scope( Returns: The context manager that holds the leases. + + Raises: + ValueError: As ``refuse_unloadable_source_checks``, for a load-only run. """ from orcapod.databases.spiraldb_writable_registry import any_writable_connector + if load_only: + # Before any lease is taken or source checked: a load-only run never reads an + # input that computes or delivers, also through a source's live inputs. + refuse_unloadable_source_checks(streams) if not any_writable_connector(): return contextlib.nullcontext() from orcapod.databases.spiraldb_write_scope import database_writes diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 4d15ca79e..8773c0e3b 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -582,6 +582,37 @@ def saved_connector_kind(config: Any) -> str | None: return "unknown connector kind" +def spiraldb_saved_config_refusal(config: Any) -> str | None: + """Why a saved SpiralDB connector configuration is not read, or ``None``. + + A saved SpiralDB connector with a ``store`` key (not an option of this version: + ``writable`` is), or a ``writable`` that is not a boolean, is refused whatever + database is given, also when none is: ``PipelineJob.load`` checks it before it + asks for a missing connector, so an old file is told about ``writable=True``. + + Args: + config: The saved database configuration. + + Returns: + The reason, or ``None`` when the configuration is not a SpiralDB connector's or + is one this version reads. + """ + from orcapod.databases.spiraldb_connector import STORE_KEY_REFUSAL + + if saved_connector_kind(config) != "spiraldb": + return None + saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) + if "store" in saved: + return STORE_KEY_REFUSAL + writable = saved.get("writable", False) + if not isinstance(writable, bool): + return ( + f"the saved SpiralDB connector's 'writable' is {writable!r}, not true or " + "false" + ) + return None + + def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """Why a database given at load cannot stand for a saved SpiralDB one, or ``None``. @@ -589,8 +620,8 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: writable=True)``, ITL-1844) is loaded with a writable connector, and one saved on a plain SpiralDB connector with a plain one: the two read different tables. The project and dataset are not compared (a job may be pointed at a copy). A saved - SpiralDB connector with a ``store`` key, or a ``writable`` that is not a boolean, is - refused whatever is given: ``store`` is not an option of this version. + configuration this version does not read (``spiraldb_saved_config_refusal``) is + refused whatever is given. Args: config: The saved database configuration. @@ -602,28 +633,20 @@ def spiraldb_writable_mismatch(config: Any, given: Any) -> str | None: """ from orcapod.databases.connector_arrow_database import ConnectorArrowDatabase from orcapod.databases.extension_aware_database import unwrap_database_views - from orcapod.databases.spiraldb_connector import ( - STORE_KEY_REFUSAL, - SpiralDBConnector, - ) + from orcapod.databases.spiraldb_connector import SpiralDBConnector + if (refusal := spiraldb_saved_config_refusal(config)) is not None: + return refusal if saved_connector_kind(config) != "spiraldb": return None saved = cast("dict[str, Any]", cast("dict[str, Any]", config)["connector"]) - if "store" in saved: - return STORE_KEY_REFUSAL - saved_writable = saved.get("writable", False) - if not isinstance(saved_writable, bool): - return ( - "the saved SpiralDB connector's 'writable' is " - f"{saved_writable!r}, not true or false" - ) given = unwrap_database_views(given) # a library view over the connector database if not isinstance(given, ConnectorArrowDatabase): return None connector = given._connector # pyright: ignore[reportPrivateUsage] # which connector the given database is over if not isinstance(connector, SpiralDBConnector): return None + saved_writable = saved.get("writable", False) is True given_writable = connector._writable # pyright: ignore[reportPrivateUsage] # whether it opens the dataset as a writable database if saved_writable == given_writable: return None diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 60f44e226..453c57dd4 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -676,7 +676,7 @@ def test_every_write_is_refused_and_writes_nothing(project: Any) -> None: lambda: connector.validate_records(_rows()), lambda: connector.unstorable_column_reason("v", pa.int64(), primary_key=False), ): - with pytest.raises(SpiralDBWriteNotSupportedError, match="ITL-1186"): + with pytest.raises(SpiralDBWriteNotSupportedError, match=r"writable=True"): write() assert connector.get_table_names() == ["swapped", "units"] assert connector.get_row_count_estimate("units") == 3 diff --git a/tests/test_databases/test_spiraldb_writable_mode.py b/tests/test_databases/test_spiraldb_writable_mode.py index bfdec8dd0..aa02a2d07 100644 --- a/tests/test_databases/test_spiraldb_writable_mode.py +++ b/tests/test_databases/test_spiraldb_writable_mode.py @@ -163,10 +163,10 @@ def test_rows_round_trip() -> None: @pytest.mark.usefixtures("root") def test_the_table_is_named_from_its_full_path_and_records_it() -> None: - db = ConnectorArrowDatabase(writable_connector()).at("team", "store") + db = ConnectorArrowDatabase(writable_connector()).at("team", "results") db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") db.flush() - full = ("team", "store", *RESULT) + full = ("team", "results", *RESULT) table = _table(identity.spiral_table_name(full)) metadata = table.get_metadata() record = identity.read_table_identity_metadata(metadata) @@ -903,6 +903,58 @@ def test_a_table_of_an_earlier_draft_is_another_format_never_read_or_written( assert _table(name).scan(["__record_id", "v"]).to_table().equals(before) +def _current_table_with_the_earlier_key(*, both_keys: bool) -> str: + """A current table (manifest, one encoded row) given the earlier draft's key. + + Written by a writable database on another dataset, then copied to this one with its + metadata changed: the earlier key holding the current value in place of the current + key, or (``both_keys``) the earlier key holding the earlier value beside the current + key holding the current value. Returns the table's name. + """ + ConnectorArrowDatabase(writable_connector(dataset="src")).add_records( + OTHER, rows(["r0"]), record_id_column="__record_id", flush=True + ) + name = identity.spiral_table_name(OTHER) + written = _client().keyed_table("p", "src", name) + metadata = dict(written.get_metadata()) + data = written.scan().to_table() + if both_keys: + metadata[identity.EARLIER_DRAFT_FORMAT_KEY] = EARLIER_DRAFT_FORMAT.encode() + else: + metadata[identity.EARLIER_DRAFT_FORMAT_KEY] = metadata.pop(identity.FORMAT_KEY) + key = pa.schema([data.schema.field(codec.KEY_COLUMN)]) + copy = _client().project("p").create_keyed_table("d", name, key) + copy.set_metadata(metadata) + _ = copy.append(data) + return name + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "both_keys", [False, True], ids=["old key, new value", "both keys"] +) +def test_a_current_table_with_the_earlier_key_is_another_format_and_never_grows( + both_keys: bool, +) -> None: + """The earlier draft's key, with any value and beside the current key or not, + makes a table of the earlier draft's format: listed as such, never listed as + current, read or appended to (delta review of 047dbe290).""" + name = _current_table_with_the_earlier_key(both_keys=both_keys) + assert _table(name).scan().to_table().num_rows == 1 + db = ConnectorArrowDatabase(writable_connector()) + listed = (*OTHER[:-1], f"rdb_v1/{EARLIER_DRAFT_FORMAT}") + assert db.list_table_paths(("my_fn",)) == [listed] + assert db.list_table_paths() == [listed] + refusal = f"its format is b'{EARLIER_DRAFT_FORMAT}'" + with pytest.raises(SpiralTableCollisionError, match=refusal): + _ = db.table_exists(OTHER) + with pytest.raises(SpiralTableCollisionError, match=refusal): + _ = db.get_all_records(OTHER) + with pytest.raises(SpiralTableCollisionError, match=refusal): + db.add_records(OTHER, rows(["r1"]), record_id_column="__record_id", flush=True) + assert _table(name).scan().to_table().num_rows == 1 + + @pytest.mark.usefixtures("root") @pytest.mark.parametrize( "metadata", diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 9338eb7f2..582bad66b 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -1,10 +1,10 @@ -"""Job runs on a writable SpiralDB database: every table kind, the writer lease, save and load -(ITL-1844). +"""Job runs on a writable SpiralDB database: every table kind, the writer lease, save +and load (ITL-1844). -On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a store -(``SpiralDBConnector(..., writable=True)``) and on Delta, and every stored table is -compared: same paths, same rows, apart from the columns a run fills with its own time -or a random id. +On the fake (``fake_spiral_sdk``); no live SpiralDB. Each job is run on a writable +SpiralDB database (``SpiralDBConnector(..., writable=True)``) and on Delta, and every +stored table is compared: same paths, same rows, apart from the columns a run fills +with its own time or a random id. """ from __future__ import annotations @@ -362,9 +362,9 @@ def test_load_refuses_a_spiraldb_connector_of_the_other_kind( @pytest.mark.usefixtures("root") -@pytest.mark.parametrize("given_writable", [True, False]) +@pytest.mark.parametrize("given_writable", [True, False, None]) def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( - root: Path, given_writable: bool + root: Path, given_writable: bool | None ) -> None: """``store`` is not an option of this version: ``writable`` is.""" saved = root / "job.json" @@ -374,13 +374,21 @@ def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( del connector["writable"] connector["store"] = True saved.write_text(json.dumps(data)) - given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + # None: no override given; the refusal still names the saved value, never only + # the missing connector (delta review of 047dbe290). + given = ( + None + if given_writable is None + else ConnectorArrowDatabase( + SpiralDBConnector("p", "d", writable=given_writable) + ) + ) with pytest.raises(ValueError, match=r"'store' key.*writable=True"): _ = PipelineJob.load(saved, database=given) @pytest.mark.usefixtures("root") -@pytest.mark.parametrize("given_writable", [True, False]) +@pytest.mark.parametrize("given_writable", [True, False, None]) @pytest.mark.parametrize("saved_value", ["true", 1, None]) def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( root: Path, given_writable: bool, saved_value: object @@ -392,7 +400,15 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( data = json.loads(saved.read_text()) data["bindings"]["database"]["connector"]["writable"] = saved_value saved.write_text(json.dumps(data)) - given = ConnectorArrowDatabase(SpiralDBConnector("p", "d", writable=given_writable)) + # None: no override given; the refusal still names the saved value, never only + # the missing connector (delta review of 047dbe290). + given = ( + None + if given_writable is None + else ConnectorArrowDatabase( + SpiralDBConnector("p", "d", writable=given_writable) + ) + ) with pytest.raises(ValueError, match="'writable' is .*not true or false"): _ = PipelineJob.load(saved, database=given) @@ -764,7 +780,7 @@ def test_the_lease_key_keeps_the_service_address_of_construction() -> None: def test_connectors_reaching_one_service_share_one_lease(given: str) -> None: """A writable connector with no address and one given the default address (also with a final slash) reach one service: a run over both takes one lease, held by both - stores; another service keeps its own lease.""" + databases; another service keeps its own lease.""" plain = SpiralDBConnector("p", "d", writable=True) addressed = SpiralDBConnector("p", "d", {"server.url": given}, writable=True) other = SpiralDBConnector( @@ -1203,6 +1219,76 @@ def add(x: int, y: int) -> int: assert on_spiral.list_table_paths(("outside",)) == [] +class _LiveReader(ArrowTableSource): + """A source that reads another stream live when read (``live_source_inputs``, the + extension point of a source over another stream).""" + + def __init__(self, live: Any, table: pa.Table) -> None: + super().__init__( + table, + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="live_reader", + record_id_columns=["unit", "trial"], + ) + self._live = live + + @property + def live_source_inputs(self) -> tuple[Any, ...]: # pyright: ignore[reportIncompatibleVariableOverride] # a narrower return than the base declares + return (self._live,) + + def as_table(self, *args: Any, **kwargs: Any) -> pa.Table: # pyright: ignore[reportIncompatibleMethodOverride] # passes everything through + _ = self._live.as_table() + return super().as_table(*args, **kwargs) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "entry", ["sync", "async orchestrator", "run_async", "node run"] +) +def test_a_load_only_run_reading_an_outside_pod_through_a_live_wrapper_is_refused( + entry: str, +) -> None: + """A load-only run whose cached source reads an outside function pod's stream live + (through a source's ``live_source_inputs``) is refused, as for a direct input, + before any lease is taken, any source checked or anything written (delta review of + 047dbe290: it reached an unleased write of the pod's results).""" + on_pod = ConnectorArrowDatabase(SpiralDBConnector("p", "f", writable=True)) + cache = ConnectorArrowDatabase(SpiralDBConnector("p", "c", writable=True)) + + computed: list[int] = [] + + def add(x: int, y: int) -> int: + computed.append(x) + return x + y + + pod = function_pod(output_keys=("total",), result_database=on_pod.at("outside"))( + add + ) + outside = pod.pod( + ArrowTableSource( + _rows(), + tag_columns=["unit", "trial"], + tag_only_columns=True, + source_id="trials", + record_id_columns=["unit", "trial"], + ) + ) + source = CachedSource(_LiveReader(outside, _rows()), cache_database=cache) + job = PipelineJob(name=JOB, database=_database()) + with job: + SelectDataColumns(["x"])(source, label="select") + with pytest.raises(ValueError, match="load-only run cannot check source"): + if entry == "node run": + _ = job.nodes["select"].run(load_only=True) + else: + _ = _run(job, entry, load_only=True) + assert computed == [] + for dataset in ("d", "f", "c"): + assert _database_tables(dataset) == [], dataset + assert _lease_tables(dataset) == [], dataset + + @pytest.mark.usefixtures("root") def test_a_run_refused_its_lease_keeps_the_last_runs_save_state(root: Path) -> None: """A run refused with ``LeaseBusyError`` changes nothing: a save afterwards records From 55f7c71b0dc413fdc928fb3be5745c0c98c1b69d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 15:18:09 -0800 Subject: [PATCH 50/50] fix(spiraldb): delta review 2 of 637fc8551: non-bool writable message names writable=True, typed test helper (ITL-1844) - A saved SpiralDB connector whose 'writable' is not a boolean is refused with a message saying it must be true or false and that writable=True makes a writable SpiralDB database, in either binding. - The live-wrapper test source overrides the base signatures exactly, with no pyright ignore. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/serialization.py | 5 ++- .../test_spiraldb_writable_runs.py | 40 +++++++++++++------ 2 files changed, 31 insertions(+), 14 deletions(-) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 8773c0e3b..7054094c3 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -607,8 +607,9 @@ def spiraldb_saved_config_refusal(config: Any) -> str | None: writable = saved.get("writable", False) if not isinstance(writable, bool): return ( - f"the saved SpiralDB connector's 'writable' is {writable!r}, not true or " - "false" + f"the saved SpiralDB connector's 'writable' is {writable!r}; it must be " + "true or false (writable=True makes a writable SpiralDB database: " + "SpiralDBConnector(..., writable=True), saved as 'writable': true)" ) return None diff --git a/tests/test_databases/test_spiraldb_writable_runs.py b/tests/test_databases/test_spiraldb_writable_runs.py index 582bad66b..77cd3f4a4 100644 --- a/tests/test_databases/test_spiraldb_writable_runs.py +++ b/tests/test_databases/test_spiraldb_writable_runs.py @@ -17,6 +17,8 @@ from pathlib import Path from typing import Any +from typing_extensions import override + import pyarrow as pa import pytest @@ -45,7 +47,8 @@ from orcapod.semantic_types.universal_converter import UniversalTypeConverter from orcapod.side_effects import SideEffectPod, sink_pod from orcapod.sources import ArrowTableSource -from orcapod.types import CacheMode +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.types import CacheMode, ColumnConfig from tests.test_databases import fake_spiral_sdk as fake pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") @@ -390,15 +393,17 @@ def test_load_refuses_a_saved_spiraldb_connector_with_a_store_key( @pytest.mark.usefixtures("root") @pytest.mark.parametrize("given_writable", [True, False, None]) @pytest.mark.parametrize("saved_value", ["true", 1, None]) +@pytest.mark.parametrize("binding", ["database", "result_database"]) def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( - root: Path, given_writable: bool, saved_value: object + root: Path, given_writable: bool | None, saved_value: object, binding: str ) -> None: """A saved ``writable`` of another type is not read as plain (review of - de39bbc4c).""" + de39bbc4c): the refusal says it must be true or false and names + ``writable=True`` (delta review of 637fc8551).""" saved = root / "job.json" - _job(_database()).save(saved) + _job(_database(), result_database=_database("r")).save(saved) data = json.loads(saved.read_text()) - data["bindings"]["database"]["connector"]["writable"] = saved_value + data["bindings"][binding]["connector"]["writable"] = saved_value saved.write_text(json.dumps(data)) # None: no override given; the refusal still names the saved value, never only # the missing connector (delta review of 047dbe290). @@ -409,8 +414,12 @@ def test_load_refuses_a_saved_writable_value_that_is_not_a_boolean( SpiralDBConnector("p", "d", writable=given_writable) ) ) - with pytest.raises(ValueError, match="'writable' is .*not true or false"): - _ = PipelineJob.load(saved, database=given) + with pytest.raises( + ValueError, + match=r"'writable' is .*must be true or false.*writable=True makes a writable " + r"SpiralDB database", + ): + _ = PipelineJob.load(saved, database=given, result_database=given) @pytest.mark.usefixtures("root") @@ -1223,7 +1232,7 @@ class _LiveReader(ArrowTableSource): """A source that reads another stream live when read (``live_source_inputs``, the extension point of a source over another stream).""" - def __init__(self, live: Any, table: pa.Table) -> None: + def __init__(self, live: StreamProtocol, table: pa.Table) -> None: super().__init__( table, tag_columns=["unit", "trial"], @@ -1231,15 +1240,22 @@ def __init__(self, live: Any, table: pa.Table) -> None: source_id="live_reader", record_id_columns=["unit", "trial"], ) - self._live = live + self._live: StreamProtocol = live @property - def live_source_inputs(self) -> tuple[Any, ...]: # pyright: ignore[reportIncompatibleVariableOverride] # a narrower return than the base declares + @override + def live_source_inputs(self) -> tuple[StreamProtocol, ...]: return (self._live,) - def as_table(self, *args: Any, **kwargs: Any) -> pa.Table: # pyright: ignore[reportIncompatibleMethodOverride] # passes everything through + @override + def as_table( + self, + *, + columns: ColumnConfig | dict[str, object] | None = None, + all_info: bool = False, + ) -> pa.Table: _ = self._live.as_table() - return super().as_table(*args, **kwargs) + return super().as_table(columns=columns, all_info=all_info) @pytest.mark.usefixtures("root")