diff --git a/changelog.d/ITL-1838.md b/changelog.d/ITL-1838.md new file mode 100644 index 000000000..9a52ae348 --- /dev/null +++ b/changelog.d/ITL-1838.md @@ -0,0 +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 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 of the newest generation by table ID. + +### Known limitations + +- 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. 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..0c2b7c5e0 --- /dev/null +++ b/docs/dev/plans/itl-1838-spiraldb-lease.md @@ -0,0 +1,51 @@ +# 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 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. 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 +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. +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. 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, 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 +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 e7557892e..6d15163b8 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,9 @@ from typing import Any SCHEMA_TABLE = "__orcapod_schemas__" +# 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" @@ -186,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]: @@ -233,24 +261,56 @@ 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 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: 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.setdefault(dataset, []).append(name) + if collisions: + 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, "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)) @@ -259,6 +319,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_connector.py b/src/orcapod/databases/spiraldb_connector.py index f0de7c74e..b5cbbd75f 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -50,6 +50,7 @@ ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.databases.store_table_names import is_spiral_lease_table_name from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -218,6 +219,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: @@ -229,14 +237,21 @@ def _open_keyed_table( return None -def _open_keyed_table_by_id(client: Any, table_id: str) -> Any: - """Return the latest snapshot of the keyed table with id ``table_id``. +def _open_keyed_table_by_id(client: Any, table_id: str, asof: int | None = None) -> Any: + """Open a keyed table by its id, at version ``asof`` or the latest. + + The one place Orcapod opens a keyed table by id, covered by the same filter as its + opens by name; the SDK's errors are raised as they are. - Opened here, so spiral-sdk's keyed-table deprecation is ignored for it as for every - other open Orcapod makes (``_ignore_keyed_table_deprecation``). + Args: + client: The spiral-sdk client. + table_id: The table's immutable id. + asof: The version to open, or ``None`` for the latest. """ _ignore_keyed_table_deprecation() - return client.keyed_table_by_id(table_id) + if asof is None: + return client.keyed_table_by_id(table_id) + return client.keyed_table_by_id(table_id, asof=asof) def _create_keyed_table( @@ -508,7 +523,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 @@ -535,9 +550,12 @@ 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 - ) + entries = cast("list[dict[str, str]]", page["items"]) + for entry in entries: + name = entry["table"] + 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 @@ -736,9 +754,10 @@ def _at(self, asof: int | None) -> Any: opened = self._versions.get(str(asof)) if opened is None: with self._connector._service_call("open a version of", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle - _ignore_keyed_table_deprecation() - opened = self._connector._client.keyed_table_by_id( # pyright: ignore[reportPrivateUsage] # owns the handle - self.table_id, asof=asof + opened = _open_keyed_table_by_id( + self._connector._client, # pyright: ignore[reportPrivateUsage] # owns the handle + self.table_id, + asof, ) self._versions[str(asof)] = opened return opened @@ -1060,18 +1079,20 @@ 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. - 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. @@ -1087,7 +1108,11 @@ 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)), @@ -1107,8 +1132,8 @@ 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, or this connector is in store - mode. + ValueError: If the table is an internal schema or lease table, or this + connector is in store mode. """ self._require_open() self._refuse_in_store_mode() @@ -1377,9 +1402,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 new file mode 100644 index 000000000..c174e0b23 --- /dev/null +++ b/src/orcapod/databases/spiraldb_lease.py @@ -0,0 +1,512 @@ +"""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 a stale +newest generation. +""" + +from __future__ import annotations + +import os +from dataclasses import dataclass +from datetime import datetime, timezone +from typing import Protocol, 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_KEY_PREFIX, + spiral_lease_key_column, + spiral_lease_table_name, +) +from orcapod.errors import OrcapodDatabaseError + +_CLAIM = "claim" +_RELEASED = "released" + + +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.""" + + +class LeaseBusyError(LeaseError): + """Another claim took the generation this writer needs. + + Attributes: + table_id: Immutable ID of the conflicting generation. + """ + + table_id: str + + def __init__( + 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. + 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, {project_id!r}, {dataset!r}, {table_id!r}, " + "confirm_writer_stopped=True)" + ) + conflict = f"SpiralDB dataset {dataset!r} has a conflicting writer lease" + recovery = ( + "The conflicting lease was released. Retry acquisition." + if released + 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}" + ) + + +@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( + 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.""" + key = spiral_lease_key_column(table.key_columns) + if key is None: + raise LeaseError( + f"SpiralDB table ID {table.resource_id!r} lacks the expected lease key" + ) + return key + + +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. + + 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: + claimed = cast( + "_KeyedTable", + sdk._create_keyed_table( + client, project_id, dataset, name, key_schema, exist_ok=False + ), + ) + except Exception as exc: + 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 found_key == key: + return found + state = _state(found, found_key) + raise LeaseBusyError( + project_id, dataset, found.resource_id, state.owner, released=state.released + ) from exc + if _key(claimed) != key: + 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 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. + """ + 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. + + 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. + 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. + """ + generation, latest = _newest(client, project_id, dataset) + if latest is not None: + state = _state(latest, _key(latest)) + if not state.released: + 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: _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) + 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 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: + _write_release(client, claimed, key) + except BaseException as cleanup_error: + exc.add_note( + f"Releasing the failed acquisition also failed (writer lease table ID " + f"{claimed.resource_id!r}): {cleanup_error!r}" + ) + raise + 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) + 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 + + +def check(client: _Client, lease: Lease) -> None: + """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: + 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 _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)) + except Exception as exc: + try: + latest = cast("_KeyedTable", sdk._open_keyed_table_by_id(client, 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 _mark_released(client: _Client, table: _KeyedTable, key: str) -> None: + """Write a release marker if this snapshot does not already show one.""" + 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) + + +def release(client: _Client, lease: Lease) -> None: + """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, + 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 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 and all its pending writes have " + "settled before clearing its lease" + ) + 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/src/orcapod/databases/store_table_names.py b/src/orcapod/databases/store_table_names.py index 79cec7cab..027e95db7 100644 --- a/src/orcapod/databases/store_table_names.py +++ b/src/orcapod/databases/store_table_names.py @@ -4,12 +4,34 @@ import hashlib import json +import re from collections.abc import Sequence SPIRAL_TABLE_NAME_LABEL = "spiral_table_name_v1" """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: + """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 is reserved for a numbered lease generation.""" + 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 require_store_path_domain(path: Sequence[str]) -> tuple[str, ...]: diff --git a/tests/test_databases/test_migrate_spiral_schemas.py b/tests/test_databases/test_migrate_spiral_schemas.py index 125f922d6..39f8137e3 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 @@ -12,7 +8,7 @@ import warnings 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 @@ -20,6 +16,13 @@ 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, +) from orcapod.errors import TableSchemaError from orcapod.sources import SpiralDBTableSource from tests.test_databases import fake_spiral_sdk as fake @@ -151,6 +154,174 @@ 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: + """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), + ("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) + 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 _legacy_listing( + tool: ModuleType, + 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. ``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. + """ + 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) + 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)) + listed.extend( + SimpleNamespace(dataset=dataset, table=st.SCHEMA_TABLE, id=f"schemas-{dataset}") + for dataset in schema_tables + ) + opened: list[str] = [] + + def key_columns_of(_connector: Any, name: str) -> list[str]: + opened.append(name) + return keys[name] + + 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], + ) + 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) + 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 "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 + 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: @@ -482,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 new file mode 100644 index 000000000..edf0cadb9 --- /dev/null +++ b/tests/test_databases/test_spiral_lease.py @@ -0,0 +1,918 @@ +"""Exercise generation leases against the local SDK fake.""" + +from __future__ import annotations + +import warnings +from collections.abc import Iterator, Sequence +from pathlib import Path + +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, + Lease, + LeaseError, + acquire, + check, + clear, + 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, +) +from tests.test_databases import fake_spiral_sdk as fake + +_PROJECT = "project" +_DATASET = "dataset" + + +@pytest.fixture +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.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) + 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_lease_operations_raise_no_keyed_table_deprecation( + client: fake.FakeClient, +) -> None: + """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(): + warnings.simplefilter("error", DeprecationWarning) + lease = acquire(client, _PROJECT, _DATASET, owner="checked run") + check(client, lease) + release(client, lease) + 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): + 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 ( + 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 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) + second = acquire(other, _PROJECT, _DATASET, owner="next run") + 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) + + +@pytest.mark.parametrize("winner_releases", [False, True]) +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] = [] + + 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.FakeClient() + 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") 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: + """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( + _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, _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] = [] + + def clear_before_append( + table: fake.FakeKeyedTable, rows: pa.Table + ) -> fake.FakeKeyedTable: + if not ids: + ids.append(table.resource_id) + 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) + + 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] + + +@pytest.mark.parametrize("reply", ["timeout", "conflict"]) +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( + 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) + 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) + holder = acquire(client, _PROJECT, _DATASET, owner="holder") + check(client, holder) + + +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}" + + 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: + """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") + + 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 +) -> 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( + 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", "scan_after_write_error"]) +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") + + def unavailable(*_args: object, **_kwargs: object) -> None: + 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) + if failed_call == "scan_after_write_error": + patch.setattr(fake.FakeKeyedTable, "append", lose_owner_reply) + 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")) + + +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") + + 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, _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") + + 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: + """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) + + 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: + """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") + + 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, _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 + + 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") + + +@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: + """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"] + 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 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: + 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, + _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) + with SpiralDBConnector(_PROJECT, dataset=_DATASET) as connector: + 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: + """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, _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 + 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_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"): + 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() == [] + 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): + 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 + + +@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: + """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) + _ = 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: + """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") + 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: + """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 + 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: 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]] = [] + + 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.FakeClient() + 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: 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 + 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: 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)") + + 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") + + +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) + + +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")) + + +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"))