Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
eb19792
feat(spiraldb): add generation-table writer leases (ITL-1838)
eywalker Dec 1, 2026
60bf0af
test(spiraldb): type the fake client boundary
eywalker Dec 1, 2026
76ac9fe
fix(spiraldb): type leases without the optional SDK
eywalker Dec 1, 2026
faa21c3
fix(spiraldb): reserve numbered lease generations consistently
eywalker Dec 1, 2026
2745f9a
fix(spiraldb): preserve tables with colliding lease names
eywalker Dec 1, 2026
d3ed38e
fix: recover writer lease claims and skip reserved names
eywalker Dec 1, 2026
a02aeaa
fix: reconcile interrupted lease creation and align migration listings
eywalker Dec 1, 2026
215b9ce
Test lease name recognition parity
eywalker Dec 1, 2026
8334616
Merge remote-tracking branch 'origin/main' into eywalker/itl-1838-spi…
eywalker Dec 1, 2026
123d900
Merge origin/main into the stage C lease branch
eywalker Dec 2, 2026
8c10bd5
fix(spiraldb_lease): keep acquisition errors and wrap failed reopens
eywalker Dec 2, 2026
dc4accf
fix(spiraldb_lease): clear only the newest generation; dry run refuse…
eywalker Dec 2, 2026
f8399f7
docs(changelog): limit the ITL-1838 known limitation to tables with a…
eywalker Dec 2, 2026
fcf67d5
fix(spiraldb_lease): guard token verification; name both clear prereq…
eywalker Dec 2, 2026
5514407
fix(spiraldb_lease): reconcile every exit of a claim before it is ret…
eywalker Dec 2, 2026
c318d2c
Merge origin/main (store stage B, #692; #694) into the stage C lease …
eywalker Dec 2, 2026
387156f
docs(spiraldb_lease): say which acquire errors propagate; name both c…
eywalker Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions changelog.d/ITL-1838.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### Breaking changes and migration

- SpiralDB table names of the form `orcapod_lease_v1_g<N>` (`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.
51 changes: 51 additions & 0 deletions docs/dev/plans/itl-1838-spiraldb-lease.md
Original file line number Diff line number Diff line change
@@ -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.
66 changes: 64 additions & 2 deletions scripts/migrate_spiral_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,17 @@
import importlib
import json
import os
import re
import sys
import warnings
from datetime import datetime, timezone
from pathlib import Path
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"
Expand Down Expand Up @@ -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]:
Expand Down Expand Up @@ -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))
Expand All @@ -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})")
Expand Down
65 changes: 46 additions & 19 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand All @@ -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(
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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)),
Expand All @@ -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()
Expand Down Expand Up @@ -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(
Expand Down
Loading
Loading