From eb197924d9916a77d1be37ab6454030a760f85a1 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:31:24 -0800 Subject: [PATCH 01/14] 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 02/14] 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 76ac9fe695b198665c21a906f033d8650d2b39e8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 09:40:29 -0800 Subject: [PATCH 03/14] 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 04/14] 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 05/14] 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 d3ed38e0409638cb6df6b8304881c1a313b0d5bb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 11:54:32 -0800 Subject: [PATCH 06/14] 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 a02aeaa716225c525f2dede2c3c14e7dba56e800 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 12:02:33 -0800 Subject: [PATCH 07/14] 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 08/14] 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 8c10bd571e4daa92b658531c678d42a33b534809 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:19:48 -0800 Subject: [PATCH 09/14] 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 dc4accfe838f6cea2c4c2c4fa799451205cb8109 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:23:06 -0800 Subject: [PATCH 10/14] 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 f8399f75b0c72536c863bbe8df4d39f3e65111f6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 22:43:54 -0800 Subject: [PATCH 11/14] 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 fcf67d5ee2a2a282eb35195fa2a59203bc9a731e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 23:57:07 -0800 Subject: [PATCH 12/14] 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 13/14] 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 14/14] 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)