From 16729fc4e3ae2eb653203f2386e07bc27977e2cd Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 10:48:04 -0800 Subject: [PATCH 1/2] fix(spiraldb): enforce verified pyspiral write refusals (ITL-1446) --- changelog.d/ITL-1446.md | 3 + docs/dev/design_issues/ITL-1162-CA3.md | 3 + .../plans/2026-11-24-itl-1446-strict-fake.md | 21 ++++ docs/reference/database-types.md | 12 +- src/orcapod/databases/spiraldb_connector.py | 99 ++++++++++++---- .../data_tags/test_database_capability.py | 19 ++- .../test_spiraldb_table_source_fake.py | 6 +- .../test_spiraldb_table_source_where.py | 17 ++- tests/test_databases/fake_pyspiral.py | 75 ++++++++++-- .../test_spiraldb_connector_fake.py | 111 ++++++++++++++++++ .../test_databases/test_unstorable_columns.py | 22 ++-- 11 files changed, 321 insertions(+), 67 deletions(-) create mode 100644 changelog.d/ITL-1446.md create mode 100644 docs/dev/plans/2026-11-24-itl-1446-strict-fake.md diff --git a/changelog.d/ITL-1446.md b/changelog.d/ITL-1446.md new file mode 100644 index 000000000..561026af8 --- /dev/null +++ b/changelog.d/ITL-1446.md @@ -0,0 +1,3 @@ +### Fixed + +- SpiralDB reports unsupported table names and rejects fixed-size binary, duration, and untyped null columns before writing rows. diff --git a/docs/dev/design_issues/ITL-1162-CA3.md b/docs/dev/design_issues/ITL-1162-CA3.md index 73e1c1ee6..d5690c0ed 100644 --- a/docs/dev/design_issues/ITL-1162-CA3.md +++ b/docs/dev/design_issues/ITL-1162-CA3.md @@ -35,6 +35,9 @@ ruling, November 16, 2026). `PostgreSQLConnector` also states which table names (`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now raises. +ITL-1446 extends SpiralDB's refusal to table names outside pyspiral's `TableName` +type and to fixed-size binary, duration, and untyped null columns. + **Open (the real fix, a later release):** store list and struct columns (for example as JSON text read back as the same Arrow type) and timestamps on SQLite, and rename SpiralDB's reserved column names on write and recover them on read, and restore a timestamp's time diff --git a/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md b/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md new file mode 100644 index 000000000..44e1191e7 --- /dev/null +++ b/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md @@ -0,0 +1,21 @@ +# ITL-1446 PR 1: pyspiral refusals + +- Verify the restrictions in sections 0, 3.2 and 3.4 of PR 542 against pyspiral 0.16.33 without a service. +- Cover the fake's refusals directly. Make the connector report unsupported Arrow types and table names before writes, and check its errors through the connector and database APIs. +- Update test input that relied on an unsupported write. Regenerate the database type matrix and run the targeted suites, lint, types and golden checks. + +The installed client's `spiral.api.types.TableName` declares 128 characters and the ASCII pattern +`^[a-zA-Z_][a-zA-Z0-9_-]*$`. An offline Pydantic `TypeAdapter` check confirmed the endpoints +and rejects a final newline. Offline `spiral.core.table.spec.Schema.from_arrow` rejects fixed-size +binary, duration, union and interval. Fixed-size binary and duration also fail inside lists, +structs, maps and dictionary or run-end encoded values. + +The installed native library carries the write diagnostics for a value name starting with +`$`, a write array with only key columns, and duplicate keys in an input batch. It also +says a key schema cannot contain a Null type field. + +The scope of duplicate detection across Arrow batches is unverified. The native null column-group +diagnostic does not establish refusal of an Arrow `null` value column, which `Schema.from_arrow` +accepts. The connector explicitly refuses such columns as required by PR 1. The schema converter +preserves struct field order, so the fake does not infer nested ordering from the client. ITL-1367 +recorded nested sorting on the service. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index c7dd0063e..e1df982a7 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -181,7 +181,7 @@ fields is not covered: a struct whose fields are in another order is another typ | Type | in-memory | Delta | SQLite | PostgreSQL | SpiralDB | |---|---|---|---|---|---| -| `null` | kept | refused | refused | refused | kept | +| `null` | kept | refused | refused | refused | refused | ## Temporal @@ -205,10 +205,10 @@ fields is not covered: a struct whose fields are in another order is another typ | `timestamp[ms, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | | `timestamp[us, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | | `timestamp[ns, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `duration[s]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ms]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[us]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ns]` | kept | kept (recorded type) | refused | refused | kept | +| `duration[s]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[ms]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[us]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[ns]` | kept | kept (recorded type) | refused | refused | refused | ## String and binary @@ -218,7 +218,7 @@ fields is not covered: a struct whose fields are in another order is another typ | `large_string` | kept | kept | kept | kept (by rule) | kept | | `binary` | kept | kept | kept | kept (by rule) | kept | | `large_binary` | kept | kept | kept | kept (by rule) | kept | -| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | kept | +| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | refused | ## List diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index be80d8919..95426bb92 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -44,6 +44,8 @@ NullabilityRecordError, NullabilityRecordMismatchError, NullInNonNullableColumnError, + UnstorableColumnError, + UnstorableTableNameError, UnsupportedValueError, ) from orcapod.types import ColumnInfo @@ -59,6 +61,9 @@ logger = logging.getLogger(__name__) _ARROW_METADATA_KEY = "__arrow_metadata__" +# pyspiral 0.16.33, spiral.api.types.TableName. +_TABLE_NAME_MAX_LENGTH = 128 +_TABLE_NAME_PATTERN = re.compile(r"[a-zA-Z_][a-zA-Z0-9_-]*") def _serialize_field_meta_tree(field: pa.Field) -> dict | None: @@ -379,6 +384,27 @@ def _about_table(table: str) -> Iterator[None]: # --------------------------------------------------------------------------- +def _unsupported_physical_type_reason(arrow_type: pa.DataType) -> str | None: + """Explain a physical Arrow type refused before it reaches the writer.""" + if pa.types.is_null(arrow_type): + return "the SpiralDB connector requires a concrete Arrow type for a column of nulls" + return _fixed_binary_or_duration_reason(arrow_type) + + +def _fixed_binary_or_duration_reason(arrow_type: pa.DataType) -> str | None: + """Find a fixed-size binary or duration type refused by pyspiral's schema converter.""" + # Both fail in pyspiral 0.16.33's Schema.from_arrow, including inside containers. + if pa.types.is_fixed_size_binary(arrow_type) or pa.types.is_duration(arrow_type): + return f"pyspiral does not support the Arrow type {arrow_type}" + if pa.types.is_dictionary(arrow_type): + return _fixed_binary_or_duration_reason(arrow_type.value_type) + for index in range(arrow_type.num_fields): + reason = _fixed_binary_or_duration_reason(arrow_type.field(index).type) + if reason is not None: + return reason + return None + + def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: """Whether ``arrow_type`` is or nests a timestamp with a time zone (ITL-1162). @@ -575,8 +601,26 @@ def share_client(self) -> SpiralDBConnector: def _table_id(self, table_name: str) -> str: """Return the dataset-qualified table identifier for a plain table name.""" + reason = self.unstorable_table_name_reason(table_name) + if reason is not None: + raise UnstorableTableNameError( + database_kind=type(self).__name__, table_name=table_name, reason=reason + ) return f"{self._dataset}.{table_name}" + def _require_supported_physical_type( + self, column: str, arrow_type: pa.DataType + ) -> None: + """Reject a physical type the connector cannot write.""" + reason = _unsupported_physical_type_reason(arrow_type) + if reason is not None: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=column, + arrow_type=arrow_type, + reason=reason, + ) + def _qualified(self, table_name: str) -> str: """Return ``"//"``, the table as errors name it.""" return f"{self._project_id}/{self._dataset}/{table_name}" @@ -605,7 +649,6 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: The table: its id and key columns, and its schema and version when asked. """ self._require_open() - identifier = self._table_id(table_name) if ( not self._dataset or not table_name @@ -614,8 +657,9 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: ): # The SDK omits empty filters and treats dots as identifier separators. raise SpiralDBTableNotFoundError( - f"Table not found: {self._project_id}.{identifier}" + f"Table not found: {self._project_id}.{self._dataset}.{table_name}" ) + identifier = self._table_id(table_name) try: table = self._project.table(identifier) except ValueError as exc: @@ -912,8 +956,9 @@ def delete_table(self, table_name: str) -> None: if the table does not exist. """ self._require_open() + identifier = self._table_id(table_name) if table_name in self.get_table_names(): - self._project.drop_table(self._table_id(table_name)) + self._project.drop_table(identifier) def create_table_if_not_exists( self, @@ -924,9 +969,9 @@ def create_table_if_not_exists( """Create a SpiralDB table with a single-column key schema, idempotently. Only the primary-key column's type is registered with Spiral at creation - time (via ``key_schema``). Non-PK columns in ``columns`` are ignored — - Spiral infers value column schemas from the first write. A second call - with the same table name is a no-op (``exist_ok=True``). + time (via ``key_schema``). The connector checks the other columns for + unsupported physical types. Spiral infers their schemas from the first + write. A second call with the same table name is a no-op (``exist_ok=True``). Only single-column primary keys are supported via this method. Tables with composite primary keys must be created outside this connector but @@ -934,8 +979,7 @@ def create_table_if_not_exists( Args: table_name: Plain table name (no dataset prefix). - columns: Full column list; must include ``pk_column``. Non-PK entries - are accepted but not used at creation time. + columns: Full column list; must include ``pk_column``. pk_column: Name of the single primary-key column. Raises: @@ -943,14 +987,17 @@ def create_table_if_not_exists( when ``columns`` is empty). """ self._require_open() + identifier = self._table_id(table_name) col_names = [c.name for c in columns] if pk_column not in col_names: raise ValueError( f"pk_column {pk_column!r} not found in columns: {col_names}" ) pk_arrow_type = next(c.arrow_type for c in columns if c.name == pk_column) + for column in columns: + self._require_supported_physical_type(column.name, column.arrow_type) self._project.create_table( - self._table_id(table_name), + identifier, key_schema=[(pk_column, pk_arrow_type)], exist_ok=True, ) @@ -1004,12 +1051,6 @@ def upsert_records( ``write_nullability_record`` after checking the data holds no null in the non-nullable columns. - Limitation: "no value columns yet" stands for "no rows yet", which saves a scan - on every first write. A table whose columns are all key columns, holding rows - and no record, is recorded by the next write; if that write adds value columns - declared non-nullable, the earlier rows hold nulls there and every read raises - ``NullInNonNullableColumnError`` (a null is never hidden). - Raises: ValueError: If ``id_column`` is not in the table key schema (including empty key schema), or if any key-schema column is absent from @@ -1043,6 +1084,8 @@ def upsert_records( f"records is missing key column(s) {missing} required by the " f"table key schema {pk_cols}." ) + for field in records.schema: + self._require_supported_physical_type(field.name, field.type) # Nullability (ITL-936). SpiralDB keeps no non-null flag except on list items, and # stores a null written to a non-null struct field as the type's zero, so every @@ -1066,8 +1109,7 @@ def upsert_records( [render_path(p) for p in sorted(paths - recorded)], table=qualified, ) - # A table with no value columns yet holds no rows Orcapod did not record (but see - # the limitation in the docstring: a table whose columns are all keys may). + # A table with no value columns yet holds no rows: pyspiral refuses key-only writes. record_first = recorded is None and set(tbl.schema().to_arrow().names) <= set( pk_cols ) @@ -1173,7 +1215,9 @@ def unstorable_column_reason( class, ``set[int]``, a NumPy array) would read back as its storage type and is refused (ITL-1334; keeping it is a follow-up). A map whose key or item field has another name than ``key`` / ``value`` reads back with those names, - and is refused too. + and is refused too. The pyspiral schema converter refuses fixed-size + binary and duration, including inside containers. The connector also + requires a concrete type for an entirely untyped null column. Args: name: The column's name. @@ -1202,6 +1246,9 @@ def unstorable_column_reason( "SpiralDB drops Arrow field metadata, so a logical (extension) type " "reads back as its storage type" ) + physical_reason = _unsupported_physical_type_reason(arrow_type) + if physical_reason is not None: + return physical_reason if arrow_utils.holds_renamed_map(arrow_type): return ( "SpiralDB gives a map's key and item fields back as 'key' and 'value'" @@ -1214,16 +1261,24 @@ def unstorable_column_reason( return None def unstorable_table_name_reason(self, table_name: str) -> str | None: - """Say why SpiralDB cannot hold a table of this name: it holds every name. - - The database's table names are letters, digits and ``_``. + """Say why the name fails pyspiral's ``TableName`` constraints. Args: table_name: The table name. Returns: - Always ``None``. + A short reason, or ``None`` when the name is valid. """ + if len(table_name) > _TABLE_NAME_MAX_LENGTH: + return ( + f"SpiralDB allows at most {_TABLE_NAME_MAX_LENGTH} characters in a " + f"table name, and this name has {len(table_name)}" + ) + if _TABLE_NAME_PATTERN.fullmatch(table_name) is None: + return ( + "SpiralDB table names must start with an ASCII letter or '_' and " + "contain only ASCII letters, digits, '_' or '-'" + ) return None def validate_records(self, records: pa.Table) -> None: diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index e33adaf88..52ed6b16e 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -395,21 +395,14 @@ def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: def test_spiraldb_failed_write_keeps_the_metadata_of_stored_rows( spiral: None, monkeypatch: pytest.MonkeyPatch ) -> None: - """A failed write restores the metadata entry the stored rows had, even key-only.""" + """A failed write restores the metadata entry the stored rows had.""" connector = SpiralDBConnector("p") connector.create_table_if_not_exists( "k", [ColumnInfo("rid", pa.large_binary())], pk_column="rid" ) - def key_only(ids: list[int]) -> pa.Table: - return mark_data_tags( - pa.table( - {"rid": pa.array([str(i).encode() for i in ids], pa.large_binary())} - ), - ["rid"], - ) - - connector.upsert_records("k", key_only([1]), id_column="rid") + # SpiralDB requires a value column alongside the key. + connector.upsert_records("k", _rows([1]), id_column="rid") real_write = fake_pyspiral.FakeTable.write def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: @@ -417,12 +410,14 @@ def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: monkeypatch.setattr(fake_pyspiral.FakeTable, "write", failing_write) with pytest.raises(RuntimeError, match="write failed"): - connector.upsert_records("k", key_only([2]), id_column="rid") + connector.upsert_records( + "k", mark_data_tags(_rows([2]), ["rid"]), id_column="rid" + ) monkeypatch.setattr(fake_pyspiral.FakeTable, "write", real_write) table = pa.Table.from_batches(list(connector.iter_batches('SELECT * FROM "k"'))) assert table.column("rid").to_pylist() == [b"1"] - assert stored_data_tags(table.schema) == ("rid",) + assert stored_data_tags(table.schema) == ("unit",) def test_spiraldb_failed_metadata_read_leaves_no_nullability_record( diff --git a/tests/test_core/sources/test_spiraldb_table_source_fake.py b/tests/test_core/sources/test_spiraldb_table_source_fake.py index 8f46a99c8..66d798b2f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_fake.py +++ b/tests/test_core/sources/test_spiraldb_table_source_fake.py @@ -373,9 +373,13 @@ def test_unreadable_record_raises_its_own_type(self, tmp_path: Path): project = fake_pyspiral.FakeSpiral().project(_PROJECT) keys = pa.schema([pa.field("subject_id", pa.string(), False)]) project.create_table("default.subject", key_schema=keys) + # SpiralDB requires a value column alongside the key. + rows = pa.table({"subject_id": ["m1"]}, schema=keys).append_column( + "value", pa.array([1]) + ) SpiralDBConnector(_PROJECT).upsert_records( "subject", - pa.table({"subject_id": ["m1"]}, schema=keys), + rows, id_column="subject_id", ) table = project.table("default.subject") diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index f1d08143f..cb1bf02a3 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -539,7 +539,6 @@ def _typed_rows() -> pa.Table: { "d64": pa.array([one, two, one], pa.date64()), "bin": pa.array([b"a", b"b", b"a"], pa.binary()), - "fbin": pa.array([b"aa", b"bb", b"aa"], pa.binary(2)), "i8": pa.array([-1, 2, -1], pa.int8()), "u8": pa.array([255, 2, 255], pa.uint8()), "i32": pa.array([1, 2, 1], pa.int32()), @@ -549,7 +548,6 @@ def _typed_rows() -> pa.Table: "t32": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time32("s")), "t64": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time64("us")), "dec": pa.array([Decimal("1.50")] * 3, pa.decimal128(5, 2)), - "dur": pa.array([dt.timedelta(1)] * 3, pa.duration("us")), } ) return pa.table(columns) @@ -640,7 +638,6 @@ def test_two_zoned_units_and_a_key_together(self, typed): [ ("d64", dt.date(2026, 1, 1), [0, 2]), ("bin", b"a", [0, 2]), - ("fbin", b"aa", [0, 2]), ("i8", -1, [0, 2]), ("u8", 255, [0, 2]), ("i32", 2, [1]), @@ -656,24 +653,32 @@ def test_each_other_type_can_be_matched(self, typed, column, value, expected): @pytest.mark.parametrize( "column, value, match", [ - ("fbin", b"a", "cannot hold"), ("i8", 128, "cannot hold"), ("u8", -1, "cannot hold"), ("u32", 2**32, "cannot hold"), ("t32", 1, "does not support"), ("t64", 1, "does not support"), ("dec", 1.5, "does not support"), - ("dur", 1, "does not support"), ], ) def test_a_value_the_column_cannot_take_is_refused( self, typed, column, value, match ): - """Time of day, decimal and duration columns take no condition: a condition + """Time of day and decimal columns take no condition: a condition holds only a bool, int, float, str, bytes, datetime or date.""" with pytest.raises(TypeError, match=match): typed.where({column: value}) + def test_predicate_types_that_pyspiral_cannot_write(self): + """The predicate checker can be tested without writing an unsupported schema.""" + fixed_binary = pa.schema([pa.field("fbin", pa.binary(2))]) + assert _checked_conditions({"fbin": b"aa"}, fixed_binary) == {"fbin": b"aa"} + with pytest.raises(TypeError, match="cannot hold"): + _checked_conditions({"fbin": b"a"}, fixed_binary) + duration = pa.schema([pa.field("dur", pa.duration("us"))]) + with pytest.raises(TypeError, match="does not support"): + _checked_conditions({"dur": 1}, duration) + @pytest.mark.parametrize( "value", [dt.time(1), Decimal("1.50"), dt.timedelta(1)], ids=repr ) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 9bc7a0fb1..d7abcc64d 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -51,6 +51,7 @@ import json import os +import re import types import uuid from collections.abc import Iterator @@ -99,6 +100,21 @@ class StorageBehaviour: reject_struct_nulls: bool = True +def _check_arrow_type(arrow_type: pa.DataType) -> None: + """Mirror the unsupported inputs to pyspiral 0.16.33's Schema.from_arrow.""" + if ( + pa.types.is_fixed_size_binary(arrow_type) + or pa.types.is_duration(arrow_type) + or pa.types.is_union(arrow_type) + or pa.types.is_interval(arrow_type) + ): + raise ValueError(f"Arrow data type not supported: {arrow_type}") + if pa.types.is_dictionary(arrow_type): + _check_arrow_type(arrow_type.value_type) + for index in range(arrow_type.num_fields): + _check_arrow_type(arrow_type.field(index).type) + + def _stored_type(t: pa.DataType, b: StorageBehaviour) -> pa.DataType: """Return the Arrow type SpiralDB hands back for a column written as ``t``. @@ -557,9 +573,9 @@ def write( **kwargs: Accepted for signature compatibility; unused. Raises: - ValueError: If a key column is missing, a column name is one SpiralDB - reserves (a ``.`` anywhere, or a ``__`` prefix on a value column), a - struct value is null without ``push_down_nulls``, or the column set + ValueError: If key columns are missing, the write has no value columns + or a batch repeats a key, a column uses an unsupported name or type, + a struct value is null without ``push_down_nulls``, or the column set differs from the stored table (live SpiralDB adds a new column: the fake does not model it). """ @@ -568,6 +584,18 @@ def write( missing = [k for k in keys.names if k not in table.column_names] if missing: raise ValueError(f"write is missing key columns {missing}") + values = sorted(name for name in table.column_names if name not in keys.names) + if not values: + # pyspiral 0.16.33 native writer diagnostic. + raise ValueError( + "Write array contains only key columns, no data columns to write" + ) + if keys.names: + for batch in table.select(keys.names).to_batches(): + # pyspiral 0.16.33 native writer diagnostic names the input batch. + batch_keys = set(zip(*batch.columns)) + if len(batch_keys) != batch.num_rows: + raise ValueError("Duplicate keys found in input batch") for name in table.column_names: # SpiralDB's own refusals, with its messages as observed live (ITL-1164). if "." in name: @@ -577,6 +605,13 @@ def write( f"Column name '{name}' has reserved prefix: column group columns " "must not start with '__'" ) + if name.startswith("$") and name not in keys.names: + # pyspiral 0.16.33 native writer diagnostic in writer/extract.rs. + raise ValueError( + f"Field name {name!r} starts with '$', which is reserved for key columns." + ) + for field in table.schema: + _check_arrow_type(field.type) if b.reject_struct_nulls and not push_down_nulls: for name in table.column_names: if _has_struct_nulls(table.column(name)): @@ -613,7 +648,6 @@ def write( # then the value columns sorted by name, by code point (observed live, # ITL-1367). Struct children are sorted live too; the fake keeps them as # written (struct field order: ITL-1368). - values = sorted(n for n in incoming.column_names if n not in keys.names) incoming = incoming.select([*keys.names, *values]) existing = self._store.read(self._project_id, self._identifier) if existing is not None: @@ -751,13 +785,13 @@ def create_table( root_uri: Any = None, exist_ok: bool = False, ) -> FakeTable: - """Create the table ``".
"`` with ``key_schema`` and open it. + """Create a table with ``key_schema`` and open it. Key columns are stored the way SpiralDB stores them, nullable under ``server_nullability`` however they were declared. Args: - identifier: ``".
"``. + identifier: ``".
"`` or a name in the default dataset. key_schema: An Arrow schema, or ``(name, type)`` pairs as pyspiral accepts. root_uri: Accepted for signature compatibility; unused. exist_ok: Open an existing table instead of raising. @@ -766,16 +800,35 @@ def create_table( The new table, or with ``exist_ok`` the existing one. Raises: - ValueError: If the table exists and ``exist_ok`` is false. + ValueError: If the name or key schema is invalid, or the table exists + and ``exist_ok`` is false. """ - if self._store.exists(self._project_id, identifier): - if not exist_ok: - raise ValueError(f"Table already exists: {identifier}") - return self.table(identifier) + parts = identifier.split(".") + if len(parts) == 1: + identifier = f"default.{identifier}" + # The pyspiral 0.16.33 spiral.api.types.TableName annotation on create_table. + name = parts[-1] + if ( + len(parts) > 2 + or len(name) > 128 + or re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_-]*", name) is None + ): + raise ValueError(f"Invalid table name: {identifier!r}") if isinstance(key_schema, pa.Schema): schema = key_schema else: schema = pa.schema([pa.field(n, t, True) for n, t in key_schema]) + for field in schema: + _check_arrow_type(field.type) + if pa.types.is_null(field.type): + # pyspiral 0.16.33 native key schema diagnostic. + raise ValueError( + f"Key schema cannot contain Null type field: {field.name}" + ) + if self._store.exists(self._project_id, identifier): + if not exist_ok: + raise ValueError(f"Table already exists: {identifier}") + return self.table(identifier) b = self._store.behaviour # SpiralDB reports key columns nullable however they were declared (ITL-936). schema = pa.schema( diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index 6d78530da..071508a47 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -24,6 +24,8 @@ NullabilityRecordError, NullabilityRecordMismatchError, NullInNonNullableColumnError, + UnstorableColumnError, + UnstorableTableNameError, UnsupportedValueError, ) from orcapod.utils import arrow_utils @@ -31,6 +33,115 @@ from tests.test_databases import fake_pyspiral from tests.test_databases.type_matrix import map_of_fields + +@pytest.mark.parametrize("name", ["", "1table", "a.b", "a b", "é", "a\n", "a" * 129]) +def test_invalid_table_name(tmp_path, name): + with fake_pyspiral.install(tmp_path): + connector = SpiralDBConnector("p") + assert connector.unstorable_table_name_reason(name) + with pytest.raises(UnstorableTableNameError, match="table name"): + connector.create_table_if_not_exists(name, [], "id") + assert connector.get_table_names() == [] + + +@pytest.mark.parametrize("name", ["_", "_T-9", "T" * 128]) +def test_valid_table_name(tmp_path, name): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + connector = SpiralDBConnector("p") + assert connector.unstorable_table_name_reason(name) is None + project.create_table(f"default.{name}", key_schema=[("id", pa.int64())]) + assert connector.get_table_names() == [name] + + +@pytest.mark.parametrize("name", ["", "1table", "a b", "é", "a\n", "a" * 129]) +def test_fake_refuses_table_names_outside_client_type(tmp_path, name): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises(ValueError, match="table name"): + project.create_table(f"default.{name}", key_schema=[("id", pa.int64())]) + assert project.list_tables() == [] + + +@pytest.mark.parametrize( + ("arrow_type", "reason"), + [ + (pa.binary(16), "fixed_size_binary"), + (pa.duration("us"), "duration"), + (pa.list_(pa.struct([("value", pa.binary(4))])), "fixed_size_binary"), + (pa.map_(pa.int64(), pa.duration("ns")), "duration"), + (pa.month_day_nano_interval(), "month_day_nano_interval"), + (pa.sparse_union([pa.field("value", pa.int64())]), "sparse_union"), + ], +) +def test_fake_refuses_types_rejected_by_schema_from_arrow(tmp_path, arrow_type, reason): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises(ValueError, match=reason): + project.create_table("default.bad", key_schema=[("id", arrow_type)]) + table = project.create_table("default.t", key_schema=[("id", pa.int64())]) + rows = pa.table({"id": [0], "v": pa.nulls(1, type=arrow_type)}) + with pytest.raises(ValueError, match=reason): + table.write(rows) + assert table.schema().to_arrow().names == ["id"] + + +@pytest.mark.parametrize( + ("rows", "message"), + [ + ({"id": [1], "part": [2]}, "Write array contains only key columns"), + ({"id": [1, 1], "part": [2, 2], "v": [3, 4]}, "Duplicate keys found"), + ({"id": [1], "part": [2], "$value": [3]}, "reserved for key columns"), + ], +) +def test_fake_refuses_invalid_write_batch(tmp_path, rows, message): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + table = project.create_table( + "default.t", key_schema=[("id", pa.int64()), ("part", pa.int64())] + ) + with pytest.raises(ValueError, match=message): + table.write(pa.table(rows)) + # A repeated component is valid, and a later write may upsert a complete key. + table.write(pa.table({"id": [1, 1], "part": [2, 3], "a$b": [3, 4]})) + table.write(pa.table({"id": [1], "part": [2], "a$b": [5]})) + assert table.schema().to_arrow().names == ["id", "part", "a$b"] + assert list(SpiralDBConnector("p").scan_batches("t"))[0].to_pylist() == [ + {"id": 1, "part": 2, "a$b": 5}, + {"id": 1, "part": 3, "a$b": 4}, + ] + + +def test_fake_refuses_null_key_type(tmp_path): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises( + ValueError, match="Key schema cannot contain Null type field" + ): + project.create_table("t", key_schema=[("id", pa.null())]) + + +@pytest.mark.parametrize( + ("arrow_type", "reason"), + [ + (pa.binary(16), "fixed_size_binary"), + (pa.duration("us"), "duration"), + (pa.null(), "null"), + ], +) +def test_connector_refuses_unstorable_arrow_columns(tmp_path, arrow_type, reason): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + table = project.create_table("default.t", key_schema=[("id", pa.int64())]) + connector = SpiralDBConnector("p") + rows = pa.table({"id": [0], "v": pa.nulls(1, type=arrow_type)}) + with pytest.raises(UnstorableColumnError, match=reason) as exc_info: + connector.upsert_records("t", rows, id_column="id") + assert exc_info.value.column == "v" + assert table.get_metadata() == {} + assert table.schema().to_arrow().names == ["id"] + + _NESTED = pa.schema( [ pa.field("id", pa.int64(), nullable=False), diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py index 4619b9de8..d940756ff 100644 --- a/tests/test_databases/test_unstorable_columns.py +++ b/tests/test_databases/test_unstorable_columns.py @@ -622,15 +622,19 @@ def test_extension_type_refused_as_unstorable_column(self, tmp_path: pathlib.Pat assert exc_info.value.column == "u" - def test_null_column_is_not_a_large_string_column(self, spiral_database): - """The schema comparison keeps ``null``: a later ``large_string`` is a change.""" - null_table = pa.table({"v": pa.array([None], type=pa.null())}) - text_table = pa.table({"v": pa.array(["a"], type=pa.large_string())}) - spiral_database.add_record(("t",), b"1", null_table, flush=True) - - spiral_database.add_record(("t",), b"2", text_table) - with pytest.raises(ValueError, match="Schema mismatch"): - spiral_database.flush() + def test_untyped_null_column_is_refused_before_buffering(self, spiral_database): + """A null value needs a concrete column type.""" + with pytest.raises(UnstorableColumnError, match="concrete Arrow type"): + spiral_database.add_record(("t",), b"1", pa.table({"v": pa.nulls(1)})) + spiral_database.flush() + assert spiral_database.list_table_paths() == [] + + typed = pa.table({"v": pa.array([None], type=pa.large_string())}) + spiral_database.add_record(("t",), b"1", typed, flush=True) + stored = spiral_database.get_all_records(("t",)) + assert stored is not None + assert stored.schema.field("v").type == pa.large_string() + assert stored["v"].to_pylist() == [None] def test_buffered_text_reads_with_committed_text(self, tmp_path: pathlib.Path): """Buffered ``string`` rows read together with committed ``large_string`` rows.""" From 324d01ab0d0d5a4e4ae74846efdad0e6bf7ff543 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 24 Nov 2026 11:35:39 -0800 Subject: [PATCH 2/2] feat(databases): the one-writer lease and write sessions of a SpiralDB store (ITL-1452) Co-Authored-By: Claude Opus 5.5 --- src/orcapod/databases/_spiral_lease.py | 821 ++++++++++++ tests/test_databases/fake_pyspiral.py | 101 +- tests/test_databases/test_spiral_lease.py | 1472 +++++++++++++++++++++ 3 files changed, 2375 insertions(+), 19 deletions(-) create mode 100644 src/orcapod/databases/_spiral_lease.py create mode 100644 tests/test_databases/test_spiral_lease.py diff --git a/src/orcapod/databases/_spiral_lease.py b/src/orcapod/databases/_spiral_lease.py new file mode 100644 index 000000000..651133c20 --- /dev/null +++ b/src/orcapod/databases/_spiral_lease.py @@ -0,0 +1,821 @@ +"""The one-writer lease of a SpiralDB store, and the write session that holds it. + +Private, and used by no job yet (ITL-1452, part of ITL-1446). The design is sections 4 and 8 +of the ITL-1446 specification. + +SpiralDB has no data-commit conflict: of two writers of one key the last commit wins, silently. +So a run holds a **lease** on each dataset it may write: the table ``orcapod_lease_v1``, created +exclusively. The owner is the name of that table's one key column, so it is part of the atomic +create, and SpiralDB's own id of the table is the lease. + +* Nothing makes a lease expire: no age, process id or host. A lease left behind is cleared by a + person, with ``clear_lease`` and the table id the refusal names. +* Leases are dropped by table id, never by name, so a late or repeated drop cannot touch a + newer lease. Only SpiralDB's answer about that id (done, or 404) says it is gone. +* The check before a commit is detection, not fencing: if a live holder's lease is cleared, a + commit already past its check still lands. + +A **session** (``write_session``, ``async_write_session``) is one run's lease of one dataset. +What may write is an explicit ``WriteCapability``, checked at every admission for its process, +its session's state, the lease it was made for, and the dataset. The run has one, and each piece +of work registered with ``submit`` or ``create_task`` has its own, revoked when the work ends. +A context variable only *locates* the caller's capability (``current_capability``); it is taken +away around user code (``without_capability``). + +Held back until decided (second review of the design): leases of several datasets in one run, +one dataset reached under two addresses, any automatic clearing, and any claim that a timeout +proves a request can no longer land. A second address of a leased dataset is simply refused. +""" + +from __future__ import annotations + +import asyncio +import os +import re +import threading +import time +from collections.abc import AsyncIterator, Callable, Coroutine, Iterator +from concurrent.futures import Executor, Future +from contextlib import asynccontextmanager, contextmanager +from contextvars import ContextVar, copy_context +from datetime import UTC, datetime +from enum import Enum +from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar + +import pyarrow as pa + +from orcapod.databases.spiraldb_connector import SpiralDBTableNotFoundError + +if TYPE_CHECKING: + from orcapod.databases.spiraldb_connector import SpiralDBConnector + +T = TypeVar("T") + +LEASE_TABLE_NAME = "orcapod_lease_v1" +# How often one release sends its drop before it gives up. A repeated drop of one id is safe. +_DROP_ATTEMPTS = 3 +_JOB_LABEL_LENGTH = 40 + + +class SpiralLeaseError(RuntimeError): + """Base of the errors about a SpiralDB store's lease.""" + + +class LeaseHeldError(SpiralLeaseError): + """The dataset's lease belongs to another run. + + Attributes: + table_id: The holder's lease table id, or ``None`` if it was gone when looked up. + """ + + def __init__(self, dataset: str, owner: str | None, table_id: str | None) -> None: + self.table_id = table_id + if table_id is None: + detail = "it was held when this run started and released since. Run again." + else: + detail = f"held by {owner!r}, lease table id {table_id!r}. {_how_to_clear(table_id)}" + super().__init__( + f"SpiralDB dataset {dataset} is in use by another run: {detail}" + ) + + +class LeaseUncertainError(SpiralLeaseError): + """Whether this run holds the lease could not be found out, so it does not.""" + + def __init__(self, dataset: str, owner: str) -> None: + super().__init__( + f"The lease of SpiralDB dataset {dataset} could not be taken: the reply to the " + "request was lost and the lease table could not be read back as this run's. If " + f"a later run is refused by the owner {owner!r}, the request landed late: clear " + "that lease with its table id." + ) + + +class LeaseLostError(SpiralLeaseError): + """The lease table is no longer the one this run created.""" + + def __init__(self, dataset: str, table_id: str) -> None: + super().__init__( + f"This run's lease of SpiralDB dataset {dataset} (table id {table_id!r}) is " + "gone: it was cleared while the run was alive. Nothing more is written. A " + "commit of this run that was already being sent may have landed." + ) + + +class LeaseLeftError(SpiralLeaseError): + """A lease may have been left behind; a person clears it. + + Attributes: + table_id: The id of the lease table. + """ + + def __init__(self, dataset: str, table_id: str, reason: str) -> None: + self.table_id = table_id + super().__init__( + f"The lease of SpiralDB dataset {dataset} may be left behind: {reason}. " + + _how_to_clear(table_id) + ) + + +class NoWriteSessionError(SpiralLeaseError): + """A write was attempted without the authority of an open write session.""" + + +class NestedWriteSessionError(SpiralLeaseError): + """A write session was opened inside another one.""" + + +def _how_to_clear(table_id: str) -> str: + """Return the instruction for clearing the lease ``table_id``.""" + return ( + f"If that run is gone, clear its lease with clear_lease({table_id!r}), after making " + "sure that its process has ended and that no request of it can still reach " + "SpiralDB. A timeout in the client does not show that." + ) + + +def _dataset_label(connector: SpiralDBConnector) -> str: + """Return the dataset as errors name it (never the endpoint: it can hold secrets).""" + return f"{connector._project_id}/{connector._dataset}" # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + + +def _dataset_key(connector: SpiralDBConnector) -> tuple[str, str, str]: + """Return ``(endpoint, project, dataset)``.""" + overrides = connector._overrides or {} # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + return ( + overrides.get("server.url", ""), + connector._project_id, # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + connector._dataset, # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + ) + + +# --------------------------------------------------------------------------- the lease + + +def _new_token() -> str: + """Return a new UUIDv7 as 32 hex digits, different in a forked copy of this process. + + The random bits come from the operating system for every token: a generator held in + process memory would give a parent and its fork the same token. + """ + raw = bytearray((time.time_ns() // 1_000_000).to_bytes(6, "big") + os.urandom(10)) + raw[6] = 0x70 | (raw[6] & 0x0F) + raw[8] = 0x80 | (raw[8] & 0x3F) + return raw.hex() + + +def _owner_text(job: str) -> str: + """Return a new owner text: ``own----``.""" + label = re.sub(r"[^a-z0-9_]+", "_", job.lower())[:_JOB_LABEL_LENGTH] + started = datetime.now(UTC).strftime("%Y%m%dT%H%M%SZ") + return f"own-{_new_token()}-{started}-{os.getpid()}-{label}" + + +class _Holder(NamedTuple): + """The lease table found under the name: its owner text and its table id.""" + + owner: str + table_id: str + + +def _current_holder(connector: SpiralDBConnector) -> _Holder | None: + """Look the lease table up by name. + + Returns: + Its owner and id, or ``None`` if there is no such table. Any other failure is + raised: it is never read as "absent". + """ + try: + table = connector.lookup_table(LEASE_TABLE_NAME) + except SpiralDBTableNotFoundError: + return None + return _Holder(",".join(table.key_columns), table.table_id) + + +class Lease: + """The lease of one dataset, held by this run.""" + + def __init__(self, connector: SpiralDBConnector, owner: str, table_id: str) -> None: + """Hold the lease table ``table_id`` of ``connector``'s dataset.""" + self.connector = connector + self.owner = owner + self.table_id = table_id + + @property + def dataset(self) -> str: + """The dataset as errors name it.""" + return _dataset_label(self.connector) + + def check(self) -> None: + """Raise ``LeaseLostError`` unless the lease table is still this run's.""" + holder = _current_holder(self.connector) + if holder is None or holder.table_id != self.table_id: + raise LeaseLostError(self.dataset, self.table_id) + + def release(self) -> None: + """Drop the lease table, or raise ``LeaseLeftError``.""" + _drop_lease_table(self.connector, self.table_id) + + +def take_lease(connector: SpiralDBConnector, job: str) -> Lease: + """Take the lease of ``connector``'s dataset: one claim, refused at once or held. + + One claim has one token. However often the client's transport delivers its create, the + replies are settled against that token (``_settle_create``). + + Args: + connector: The dataset to lease. + job: A name shown to a run that is refused. + + Returns: + The lease. + + Raises: + LeaseHeldError: If another run holds it. + LeaseUncertainError: If the reply was lost and the lease cannot be shown to be + this run's. + """ + owner = _owner_text(job) + try: + table = connector._project.create_table( # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + f"{connector._dataset}.{LEASE_TABLE_NAME}", # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + key_schema=pa.schema([(owner, pa.int64())]), + exist_ok=False, + ) + return Lease(connector, owner, str(table.table_id)) + except Exception as exc: + return _settle_create(connector, owner, exc) + except BaseException as interrupt: + _undo_interrupted_create(connector, owner, interrupt) + raise + + +def _settle_create(connector: SpiralDBConnector, owner: str, error: Exception) -> Lease: + """Find out, by one look at the name, what a failed create did. + + A 409 and a lost reply are settled the same way, because the client's own retry turns + a lost reply into a 409. + """ + dataset = _dataset_label(connector) + refused = _has_status(error, 409) + try: + holder = _current_holder(connector) + except Exception as lookup_error: + lookup_error.add_note(f"The create had failed with: {error!r}") + raise LeaseUncertainError(dataset, owner) from lookup_error + if holder is None: + if refused: + raise LeaseHeldError(dataset, None, None) from error + raise LeaseUncertainError(dataset, owner) from error + if holder.owner == owner: + return Lease(connector, owner, holder.table_id) + raise LeaseHeldError(dataset, holder.owner, holder.table_id) from error + + +def _undo_interrupted_create( + connector: SpiralDBConnector, owner: str, interrupt: BaseException +) -> None: + """Drop the lease an interrupted create may have made; note it if that fails.""" + try: + holder = _current_holder(connector) + if holder is not None and holder.owner == owner: + _drop_lease_table(connector, holder.table_id) + except Exception as exc: + interrupt.add_note( + f"A lease of SpiralDB dataset {_dataset_label(connector)} with the owner " + f"{owner!r} may be left behind ({exc!r})." + ) + + +def _drop_lease_table(connector: SpiralDBConnector, table_id: str) -> None: + """Drop the lease table with exactly this id; already gone is success. + + Raises: + LeaseLeftError: If it could not be settled whether the table is gone. + """ + error: Exception | None = None + for _ in range(_DROP_ATTEMPTS): + try: + connector._spiral.core.drop_table(table_id=table_id) # pyright: ignore[reportPrivateUsage] # the lease is the connector's own + return + except Exception as exc: + if _has_status(exc, 404): + return + error = exc + raise LeaseLeftError( + _dataset_label(connector), table_id, f"dropping it failed ({error!r})" + ) from error + + +def clear_lease(connector: SpiralDBConnector, table_id: str) -> bool: + """Drop a lease a run left behind. Called by a person, never by Orcapod. + + The caller has made sure that the holder's process has ended and that no request of it + is in flight; clearing a live holder's lease lets a second run write. + + Args: + connector: The dataset whose lease is cleared. + table_id: The lease table id the refusal named. + + Returns: + Whether the dataset's lease had that id. If not, nothing is dropped. + + Raises: + LeaseLeftError: If it could not be settled whether the table is gone. + """ + holder = _current_holder(connector) + if holder is None or holder.table_id != table_id: + return False + _drop_lease_table(connector, table_id) + return True + + +def _has_status(error: Exception, status: int) -> bool: + """Whether ``error`` is SpiralDB's reply ``status``. + + pyspiral 0.16.33 raises a plain ``Exception`` whose text starts with the status from its + native calls (seen live: ``409 Conflict: ...``, ``404 Not Found: ...``) and + ``SpiralHTTPError`` with a ``code`` from its Python calls. + """ + return getattr(error, "code", None) == status or str(error).startswith(f"{status} ") + + +# ------------------------------------------------------------------------- the session + + +class _State(Enum): + """What a session still admits.""" + + OPEN = "open" # every live capability + DRAINING = "draining" # registered work that is still running, only + FLUSHING = "flushing" # the final flush, only + CLOSED = "closed" # nothing + + +class _Role(Enum): + """Whose capability it is.""" + + RUN = "run" + WORK = "work" + FLUSH = "flush" + + +_ADMITTED = { + _State.OPEN: {_Role.RUN, _Role.WORK}, + _State.DRAINING: {_Role.WORK}, + _State.FLUSHING: {_Role.FLUSH}, + _State.CLOSED: set[_Role](), +} + + +class Commit: + """One commit to a store table, made under a checked lease.""" + + def __init__(self) -> None: + """Start with an unknown outcome.""" + self._settled = False + + def settle(self) -> None: + """Say that no request of this commit can still reach SpiralDB. + + Called for a commit that failed, by a writer that knows: it was never sent, or + SpiralDB answered it with a refusal. + """ + self._settled = True + + @property + def settled(self) -> bool: + """Whether no request of this commit can still reach SpiralDB.""" + return self._settled + + +class _Session: + """One run's lease of one dataset, and what is running under it.""" + + def __init__(self, connector: SpiralDBConnector, job: str, is_async: bool) -> None: + """Describe the session; nothing is leased yet.""" + self.connector = connector + self.is_async = is_async + self.dataset_key = _dataset_key(connector) + self.pid = os.getpid() + self.final_flushes: list[Callable[[], None]] = [] + self._job = job + self._changed = threading.Condition() + self._state = _State.OPEN + self._running = 0 + self._commits: list[Commit] = [] + self._lease: Lease | None = None + self._lost: LeaseLostError | None = None + + @property + def lease(self) -> Lease: + """The lease; only of an opened session.""" + assert self._lease is not None + return self._lease + + # ---- admission + + def admit(self, capability: WriteCapability, *, work: bool) -> None: + """Check ``capability``, and in the same step count new running work. + + Args: + capability: What the caller acts with. + work: Whether something starts running that ends with ``end``. + + Raises: + NoWriteSessionError: If the capability does not allow it now. + """ + # The process first: after a fork a lock may be held by a thread that is gone. + if os.getpid() != self.pid: + raise NoWriteSessionError( + "A forked process cannot write with its parent's write session." + ) + with self._changed: + if self._state is _State.CLOSED: + raise NoWriteSessionError( + "The write session is closed: the run it belongs to has ended." + ) + if ( + capability.revoked + or capability.role not in _ADMITTED[self._state] + or capability.generation != self.lease.table_id + ): + raise NoWriteSessionError( + "The write session no longer admits this work: what it belongs to " + "has ended." + ) + if work: + self._running += 1 + + def end(self, revoke: WriteCapability | None = None) -> None: + """Count one piece of running work less, and revoke its capability.""" + with self._changed: + if revoke is not None: + revoke.revoked = True + self._running -= 1 + self._changed.notify_all() + + def start_commit(self) -> Commit: + """Check the lease and return a commit of unknown outcome.""" + if self._lost is not None: + raise self._lost + try: + self.lease.check() + except LeaseLostError as exc: + self._lost = exc + raise + commit = Commit() + with self._changed: + self._commits.append(commit) + return commit + + # ---- open and close + + def open(self) -> None: + """Take the lease.""" + self._lease = take_lease(self.connector, self._job) + + def close(self, error: BaseException | None) -> None: + """Close admission, wait for the run's work, flush, and release. + + Args: + error: What the run raised. Failures here become notes on it; without one, + the first failure is raised. + """ + if os.getpid() != self.pid: + return # a forked child ends its copy of the run: the lease is the parent's + failures: list[Exception] = [] + try: + with self._changed: + self._state = _State.DRAINING + self._drain() + failures += self._flush() + with self._changed: + self._state = _State.CLOSED + self._release() + except LeaseLeftError as exc: + failures.append(exc) + except BaseException as interrupt: + with self._changed: + self._state = _State.CLOSED + interrupt.add_note(str(self._left("closing the write session failed"))) + raise + if self._lost is not None and self._lost is not error: + failures = [f for f in failures if f is not self._lost] + failures.insert(0, self._lost) + if error is not None: + for failure in failures: + error.add_note(f"Closing the write session: {failure}") + elif failures: + first, *rest = failures + for failure in rest: + first.add_note(f"Closing the write session: {failure}") + raise first + + def _drain(self) -> None: + """Wait until nothing is running; admit nothing but the final flush from then on.""" + with self._changed: + self._changed.wait_for(lambda: self._running == 0) + self._state = _State.FLUSHING + + def _flush(self) -> list[Exception]: + """Run every final flush, with a capability of its own; return what failed.""" + failures: list[Exception] = [] + capability = WriteCapability(self, _Role.FLUSH) + token = _located.set(capability) + try: + for flush in self.final_flushes: + try: + flush() + except Exception as exc: + failures.append(exc) + finally: + _located.reset(token) + with self._changed: + capability.revoked = True + # a commit a flush handed to another thread + self._changed.wait_for(lambda: self._running == 0) + return failures + + def _release(self) -> None: + """Drop the lease table, unless a request of this run may still land.""" + if not all(commit.settled for commit in self._commits): + raise self._left( + "a commit failed and its request may still reach the service" + ) + self.lease.release() + + def _left(self, reason: str) -> LeaseLeftError: + """Return the error that the lease stays, for ``reason``.""" + return LeaseLeftError(self.lease.dataset, self.lease.table_id, reason) + + +class WriteCapability: + """The right to write to one leased dataset: a run's, or one piece of its work's. + + Attributes: + generation: The table id of the lease it was made for. + role: Whose it is. + revoked: Whether what it belonged to has ended. + """ + + def __init__(self, session: _Session, role: _Role) -> None: + """Make a capability of ``session``'s current lease.""" + self._session = session + self.generation = session.lease.table_id + self.role = role + self.revoked = False + + def require(self, connector: SpiralDBConnector) -> None: + """Raise unless the holder may write to ``connector``'s dataset now.""" + self._require_dataset(connector) + self._session.admit(self, work=False) + + @contextmanager + def commit(self, connector: SpiralDBConnector) -> Iterator[Commit]: + """Run one commit: check the lease, then let the caller send it. + + The session does not close before the body has ended. If the body raises, the + commit's request may still land: unless the caller settles it, the session leaves + its lease behind. + + Args: + connector: The dataset the commit goes to. + + Yields: + The commit. + + Raises: + NoWriteSessionError: If this capability does not allow it. + LeaseLostError: If the lease was cleared. Every later commit raises it too. + """ + self._require_dataset(connector) + self._session.admit(self, work=True) + try: + commit = self._session.start_commit() + yield commit + commit.settle() + finally: + self._session.end() + + def submit( + self, executor: Executor, function: Callable[..., T], /, *args: Any + ) -> Future[T]: + """Run Orcapod's own ``function`` on ``executor`` with a capability of its own. + + The session does not close before the function has ended, also if its future, or + a task awaiting it, is cancelled while it runs. + """ + self._session.admit(self, work=True) + capability = WriteCapability(self._session, self._work_role) + try: + context = copy_context() + context.run(_located.set, capability) + future = executor.submit(context.run, function, *args) + except BaseException: + self._session.end(revoke=capability) + raise + future.add_done_callback(lambda _: self._session.end(revoke=capability)) + return future + + def create_task(self, coroutine: Coroutine[Any, Any, T]) -> asyncio.Task[T]: + """Run Orcapod's own ``coroutine`` as a task with a capability of its own. + + The session does not close before the task has ended, also if it is cancelled. + """ + try: + if not self._session.is_async: + raise NoWriteSessionError( + "A synchronous write session cannot wait for an asyncio task." + ) + self._session.admit(self, work=True) + except BaseException: + coroutine.close() + raise + capability = WriteCapability(self._session, self._work_role) + try: + context = copy_context() + context.run(_located.set, capability) + task = asyncio.get_running_loop().create_task(coroutine, context=context) + except BaseException: + self._session.end(revoke=capability) + coroutine.close() + raise + task.add_done_callback(lambda _: self._session.end(revoke=capability)) + return task + + def add_final_flush(self, flush: Callable[[], None]) -> None: + """Call ``flush`` once everything else of the run has ended, before release.""" + self._session.admit(self, work=True) + try: + self._session.final_flushes.append(flush) + finally: + self._session.end() + + @property + def _work_role(self) -> _Role: + """The role of work this capability starts.""" + return _Role.FLUSH if self.role is _Role.FLUSH else _Role.WORK + + def _require_dataset(self, connector: SpiralDBConnector) -> None: + """Raise unless ``connector``'s dataset is the leased one.""" + if _dataset_key(connector) != self._session.dataset_key: + raise NoWriteSessionError( + "The write session holds no lease of SpiralDB dataset " + f"{_dataset_label(connector)} at that address." + ) + + +# Where the caller's capability is found. It authorizes nothing: ``_Session.admit`` does. +_located: ContextVar[WriteCapability | None] = ContextVar( + "orcapod_spiral_write_capability", default=None +) + + +def current_capability() -> WriteCapability: + """Return the caller's capability. + + Raises: + NoWriteSessionError: If it has none. + """ + capability = _located.get() + if capability is None: + raise NoWriteSessionError( + "A SpiralDB store is written only inside a run or store.writing()." + ) + return capability + + +@contextmanager +def without_capability() -> Iterator[None]: + """Run user code without the run's capability: each call, await and generator step. + + User code may then open a session of its own on another dataset. + """ + token = _located.set(None) + try: + yield + finally: + _located.reset(token) + + +def _new_session(connector: SpiralDBConnector, job: str, is_async: bool) -> _Session: + """Return a session to open, unless the caller has one already.""" + if _located.get() is not None: + raise NestedWriteSessionError( + "A write session cannot be opened inside another one." + ) + return _Session(connector, job, is_async) + + +@contextmanager +def write_session( + connector: SpiralDBConnector, *, job: str +) -> Iterator[WriteCapability]: + """Hold the lease of ``connector``'s dataset for the body: one run. + + Args: + connector: The dataset the run writes. + job: A name shown to a run that is refused. + + Yields: + The run's capability. + + Raises: + LeaseHeldError: If the dataset is in use. + LeaseUncertainError: If the lease could not be shown to be this run's. + NestedWriteSessionError: If the caller already has a capability. + """ + session = _new_session(connector, job, is_async=False) + session.open() + capability = WriteCapability(session, _Role.RUN) + token = _located.set(capability) + try: + try: + yield capability + except BaseException as exc: + session.close(exc) + raise + session.close(None) + finally: + _located.reset(token) + + +@asynccontextmanager +async def async_write_session( + connector: SpiralDBConnector, *, job: str +) -> AsyncIterator[WriteCapability]: + """``write_session`` for an asynchronous run. + + Cancelling the run does not interrupt taking, draining or releasing: a thread that is + committing goes on after its task is cancelled, so the lease is kept until it ends. + The cancellation is raised afterwards. + """ + session = _new_session(connector, job, is_async=True) + error, cancelled = await _uncancelled(session.open) + if error is not None: + if cancelled is not None: + raise cancelled from error + raise error + if cancelled is not None: + await _close_async(session, cancelled) + raise cancelled + capability = WriteCapability(session, _Role.RUN) + token = _located.set(capability) + try: + try: + yield capability + except BaseException as exc: + await _close_async(session, exc) + raise + await _close_async(session, None) + finally: + _located.reset(token) + + +async def _close_async(session: _Session, raised: BaseException | None) -> None: + """Close ``session`` without being interrupted by a cancellation.""" + if os.getpid() != session.pid: + return # a forked child: see ``_Session.close`` + error, cancelled = await _uncancelled(lambda: session.close(raised)) + if cancelled is not None and raised is None: + if error is not None: + cancelled.add_note(f"Closing the write session: {error}") + raise cancelled + if error is not None: + raise error + + +async def _uncancelled( + function: Callable[[], None], +) -> tuple[BaseException | None, asyncio.CancelledError | None]: + """Run ``function`` in a thread and wait for its end, whatever is cancelled. + + Returns: + What it raised, and the cancellation that arrived meanwhile. + """ + loop = asyncio.get_running_loop() + ended: asyncio.Future[BaseException | None] = loop.create_future() + context = copy_context() + + def run() -> None: + error: BaseException | None = None + try: + context.run(function) + except BaseException as exc: + error = exc + try: + loop.call_soon_threadsafe(ended.set_result, error) + except RuntimeError: + pass # the loop was closed: nobody waits any more + + # A daemon: if the loop is stopped, waiting for its tasks must not keep the process + # alive. The lease then stays, as after a crash. + threading.Thread(target=run, name="orcapod-spiral-session", daemon=True).start() + cancelled: asyncio.CancelledError | None = None + while not ended.done(): + try: + await asyncio.wait({ended}) + except asyncio.CancelledError as exc: + cancelled = exc + return ended.result(), cancelled diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index d7abcc64d..2e0ae65dd 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -13,7 +13,7 @@ (each call is recorded in ``scan_log``; batches are read on demand) * ``Project.list_tables()`` (``TableResource`` with ``.dataset`` / ``.table``), ``Project.table(id)``, ``Project.create_table(id, key_schema=..., exist_ok=...)``, - ``Project.drop_table(id)`` + ``Project.drop_table(id)``, ``Spiral.core.drop_table(table_id=...)`` * ``Table.key_schema``, ``Table.table_id``, ``Table.last_modified_at()``, ``Table[name] == v``, ``Table.core.get_snapshot()``, ``Table.schema().to_arrow()``, ``Table.select()``, ``Table.write(t)``, ``Table.get_metadata()``, ``Table.set_metadata(kv)``, ``Table.drop_metadata(keys)`` @@ -44,11 +44,18 @@ * ``reject_struct_nulls`` (documented by pyspiral ``Table.write``): a null struct value is refused unless written with ``push_down_nulls=True``, which turns it into a struct of null fields (observed live, ITL-936; top-level struct columns only in the fake). +* Creating a table name is atomic across processes and threads; with ``exist_ok=False`` a taken + name is a plain ``Exception`` starting ``409 Conflict`` (observed live, ITL-1446: 25 rounds + of 5 processes, one winner each). +* A table is dropped by its id; an unknown or already dropped id is a plain ``Exception`` + starting ``404 Not Found``, also when a newer table has the name (observed live, ITL-1446: 10 + takeover rounds). Dropping by name looks the id up first (pyspiral 0.16.33's source). * Rows come back sorted by key and writes upsert by key (SpiralDB is a key-sorted store). """ from __future__ import annotations +import fcntl import json import os import re @@ -266,6 +273,13 @@ def _path(self, project_id: str, identifier: str, suffix: str) -> Path: """Return the file holding ``identifier``'s part named by ``suffix``.""" return self.root / project_id / f"{identifier}{suffix}" + @contextmanager + def locked(self) -> Iterator[None]: + """Make the body one step of the service, for every process and thread.""" + with open(self.root / ".lock", "w") as lock: + fcntl.flock(lock, fcntl.LOCK_EX) + yield + def exists(self, project_id: str, identifier: str) -> bool: """Return whether table ``identifier`` exists in ``project_id``.""" return self._path(project_id, identifier, ".keys.json").exists() @@ -277,23 +291,52 @@ def identifiers(self, project_id: str) -> list[str]: return [] return sorted(p.name[: -len(".keys.json")] for p in pdir.glob("*.keys.json")) - def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> None: - """Create table ``identifier`` with ``key_schema`` and empty metadata.""" + def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> bool: + """Create table ``identifier`` with ``key_schema`` and empty metadata, atomically. + + Returns: + Whether the name was free. If not, nothing is changed. + """ + with self.locked(): + if self.exists(project_id, identifier): + return False + self._create(project_id, identifier, key_schema) + return True + + def _create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> None: + """Write the files of the new table ``identifier``.""" (self.root / project_id).mkdir(parents=True, exist_ok=True) sink = pa.BufferOutputStream() pa.ipc.new_stream(sink, key_schema).close() self._path(project_id, identifier, ".keys.arrow").write_bytes( sink.getvalue().to_pybytes() ) - self._path(project_id, identifier, ".keys.json").write_text( - json.dumps(key_schema.names) - ) self._path(project_id, identifier, ".kv.json").write_text("{}") # SpiralDB gives every table its own id; a recreated table gets a new one. self._path(project_id, identifier, ".id.txt").write_text( f"table_{uuid.uuid4().hex[:12]}" ) self._path(project_id, identifier, ".version.txt").write_text("0") + # Last: the table exists once this file does. + self._path(project_id, identifier, ".keys.json").write_text( + json.dumps(key_schema.names) + ) + + def drop_id(self, table_id: str) -> None: + """Remove the table with the id ``table_id``, whatever its name. + + Raises: + Exception: If no table has that id (a 404, as pyspiral raises it). + """ + with self.locked(): + for project in self.root.iterdir(): + for identifier in ( + self.identifiers(project.name) if project.is_dir() else () + ): + if self.table_id(project.name, identifier) == table_id: + self.drop(project.name, identifier) + return + raise Exception(f"404 Not Found: Resource `{table_id}` not found") def drop(self, project_id: str, identifier: str) -> None: """Remove every file of table ``identifier``.""" @@ -325,8 +368,10 @@ def read(self, project_id: str, identifier: str) -> pa.Table | None: def write(self, project_id: str, identifier: str, table: pa.Table) -> None: """Replace table ``identifier``'s rows with ``table`` and move its version on.""" p = self._path(project_id, identifier, ".data.arrow") - with pa.ipc.new_file(str(p), table.schema) as w: + part = p.with_name(f"{p.name}.{uuid.uuid4().hex}") + with pa.ipc.new_file(str(part), table.schema) as w: w.write_table(table) + os.replace(part, p) # a reader sees the old rows or the new ones self._path(project_id, identifier, ".version.txt").write_text( str(self.version(project_id, identifier) + 1) ) @@ -493,6 +538,7 @@ def __init__(self, store: _Store, project_id: str, identifier: str) -> None: self._store = store self._project_id = project_id self._identifier = identifier + self._table_id = store.table_id(project_id, identifier) @property def key_schema(self) -> pa.Schema: @@ -502,7 +548,7 @@ def key_schema(self) -> pa.Schema: @property def table_id(self) -> str: """The table's own id: kept on rename, new when the table is recreated.""" - return self._store.table_id(self._project_id, self._identifier) + return self._table_id @property def core(self) -> Any: @@ -649,6 +695,12 @@ def write( # ITL-1367). Struct children are sorted live too; the fake keeps them as # written (struct field order: ITL-1368). incoming = incoming.select([*keys.names, *values]) + with self._store.locked(): + self._commit(incoming) + + def _commit(self, incoming: pa.Table) -> None: + """Upsert ``incoming`` by key: one atomic step (observed live, ITL-1446).""" + keys = self.key_schema existing = self._store.read(self._project_id, self._identifier) if existing is not None: if existing.schema.names != incoming.schema.names: @@ -745,6 +797,11 @@ def _list_tables( self, dataset: str | None = None, table: str | None = None ) -> list[TableResource]: """Apply the SDK's project API filters, which omit empty values.""" + with self._store.locked(): + return self._listed(dataset, table) + + def _listed(self, dataset: str | None, table: str | None) -> list[TableResource]: + """Return the tables the filters leave.""" out = [] for ident in self._store.identifiers(self._project_id): found_dataset, _, found_table = ident.partition(".") @@ -800,8 +857,8 @@ def create_table( The new table, or with ``exist_ok`` the existing one. Raises: - ValueError: If the name or key schema is invalid, or the table exists - and ``exist_ok`` is false. + ValueError: If the name or key schema is invalid. + Exception: If the table exists and ``exist_ok`` is false (a 409). """ parts = identifier.split(".") if len(parts) == 1: @@ -825,10 +882,6 @@ def create_table( raise ValueError( f"Key schema cannot contain Null type field: {field.name}" ) - if self._store.exists(self._project_id, identifier): - if not exist_ok: - raise ValueError(f"Table already exists: {identifier}") - return self.table(identifier) b = self._store.behaviour # SpiralDB reports key columns nullable however they were declared (ITL-936). schema = pa.schema( @@ -841,12 +894,16 @@ def create_table( for f in schema ] ) - self._store.create(self._project_id, identifier, schema) + created = self._store.create(self._project_id, identifier, schema) + if not created and not exist_ok: + raise Exception( + f"409 Conflict: Table {self._project_id}.{identifier} already exists." + ) return self.table(identifier) def drop_table(self, identifier: str) -> None: - """Drop the table ``".
"`` if it exists.""" - self._store.drop(self._project_id, identifier) + """Look the table ``".
"`` up and drop its id.""" + self._store.drop_id(self.table(identifier).table_id) class FakeSpiral: @@ -899,9 +956,15 @@ def scan(self, *projections: Any, **kwargs: Any) -> FakeScan: @property def core(self) -> Any: - """The client's low-level handle; only ``manifest_stats`` is modelled.""" + """The client's low-level handle; ``manifest_stats`` and ``drop_table`` only.""" + + return types.SimpleNamespace( + manifest_stats=self.manifest_stats, drop_table=self.drop_table + ) - return types.SimpleNamespace(manifest_stats=self.manifest_stats) + def drop_table(self, table_id: str) -> None: + """Drop the table with exactly this id; a 404 if there is none.""" + self._store.drop_id(table_id) def manifest_stats(self, snapshot: FakeTable) -> Any: """Return stats whose ``key_space_stats.total_rows`` counts rows.""" diff --git a/tests/test_databases/test_spiral_lease.py b/tests/test_databases/test_spiral_lease.py new file mode 100644 index 000000000..109e9a663 --- /dev/null +++ b/tests/test_databases/test_spiral_lease.py @@ -0,0 +1,1472 @@ +"""The one-writer lease and write sessions of a SpiralDB store (ITL-1452), on the fake. + +Every request a client sends goes through a ``Wire``, so a test says exactly what happens at +each one: nothing is timed and nothing sleeps. Threads are handed on by events and by the +``Schedule`` of the interleaving test, never by waiting a while. +""" + +from __future__ import annotations + +import ast +import asyncio +import os +import threading +import uuid +from collections.abc import Callable, Iterator +from concurrent.futures import ThreadPoolExecutor +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +import orcapod +from orcapod.databases import _spiral_lease as lease_module +from orcapod.databases._spiral_lease import ( + LEASE_TABLE_NAME, + LeaseHeldError, + LeaseLeftError, + LeaseLostError, + LeaseUncertainError, + NestedWriteSessionError, + NoWriteSessionError, + async_write_session, + clear_lease, + current_capability, + take_lease, + without_capability, + write_session, +) +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from tests.test_databases import fake_pyspiral + +WAIT = 30 # seconds before a hung test fails; no test waits this long + + +class Killed(BaseException): + """The process died: raised by this and every later request of its client.""" + + +class Wire: + """Carries one client's requests; a test decides what happens to each. + + ``on(kind, ...)`` queues what happens to the next requests of that kind: a callable given + the request to send. With nothing queued a request is sent. + """ + + def __init__(self) -> None: + self.log: list[str] = [] + self.dead = False + self._plans: dict[str, list[Callable[[Callable[[], Any]], Any]]] = {} + + def on(self, kind: str, *plans: Callable[[Callable[[], Any]], Any]) -> None: + self._plans.setdefault(kind, []).extend(plans) + + def __call__(self, kind: str, request: Callable[[], Any]) -> Any: + if self.dead: + raise Killed + self.log.append(kind) + plans = self._plans.get(kind) + return plans.pop(0)(request) if plans else request() + + +def send(request: Callable[[], Any]) -> Any: + return request() + + +def lost_reply(request: Callable[[], Any]) -> Any: + """The service does it (or refuses it); the client sees a timeout.""" + try: + request() + except Exception: + pass + raise TimeoutError("reply lost") + + +def lost_request(request: Callable[[], Any]) -> Any: + raise TimeoutError("request lost") + + +def retried_by_client(request: Callable[[], Any]) -> Any: + """The client repeats a request whose reply was lost, and sees the second reply.""" + request() + return request() + + +class WiredProject: + def __init__(self, project: Any, wire: Wire) -> None: + self._project, self._wire = project, wire + + def create_table(self, *args: Any, **kwargs: Any) -> Any: + return self._wire("create", lambda: self._project.create_table(*args, **kwargs)) + + def list_tables(self) -> Any: + return self._project.list_tables() + + def table(self, identifier: str) -> Any: + return self._wire("lookup", lambda: self._project.table(identifier)) + + +class WiredSpiral: + def __init__(self, spiral: Any, wire: Wire) -> None: + self._spiral, self._wire = spiral, wire + + @property + def core(self) -> Any: + return self + + def drop_table(self, table_id: str) -> None: + self._wire("drop", lambda: self._spiral.core.drop_table(table_id=table_id)) + + +class Client(SpiralDBConnector): + """A connector whose lease requests go through its ``wire``.""" + + def __init__( + self, + dataset: str = "store", + wire: Wire | None = None, + project: str = "p", + endpoint: str | None = None, + ) -> None: + overrides = None if endpoint is None else {"server.url": endpoint} + super().__init__(project, dataset, overrides) + self.wire = wire or Wire() + self.real_project = self._project + self.real_spiral = self._spiral + self._project: Any = WiredProject(self._project, self.wire) + self._spiral: Any = WiredSpiral(self._spiral, self.wire) + + def holder(self) -> Any: + """The lease table as another client sees it, or ``None``.""" + try: + return self.real_project.table(f"{self._dataset}.{LEASE_TABLE_NAME}") + except ValueError: + return None + + def put(self, key: int, value: str) -> None: + """Send one row of data, as a commit of a store does.""" + table = self.real_project.create_table( + f"{self._dataset}.data", key_schema=[("k", pa.int64())], exist_ok=True + ) + rows = pa.table({"k": [key], "v": [value]}) + self.wire("write", lambda: table.write(rows)) + + def rows(self) -> dict[int, str]: + table = self.real_project.table(f"{self._dataset}.data") + stored = self.real_spiral.scan(table.select()).to_table().to_pydict() + return dict(zip(stored["k"], stored["v"])) if "v" in stored else {} + + +@pytest.fixture(autouse=True) +def service(tmp_path: Path) -> Iterator[None]: + with fake_pyspiral.install(tmp_path): + yield + + +def commit(client: Client, key: int, value: str) -> None: + with current_capability().commit(client): + client.put(key, value) + + +def kill(client: Client) -> None: + client.wire.dead = True + + +def test_nothing_uses_the_module_yet() -> None: + """Inert until PR 8: no module of the library imports it.""" + root = Path(orcapod.__file__).parent + users = [ + path.name + for path in root.rglob("*.py") + for node in ast.walk(ast.parse(path.read_text())) + if isinstance(node, (ast.Import, ast.ImportFrom)) + and "_spiral_lease" in ast.unparse(node) + ] + assert users == [] + + +# ------------------------------------------------------------------- the fake's own rules + + +def test_fake_exclusive_create_and_drop_by_id_as_measured() -> None: + client = Client() + project, core = client.real_project, client.real_spiral.core + first = project.create_table("store.t", key_schema=[("a", pa.int64())]) + with pytest.raises(Exception, match=r"^409 Conflict: Table p\.store\.t already"): + project.create_table("store.t", key_schema=[("b", pa.int64())]) + core.drop_table(table_id=first.table_id) + second = project.create_table("store.t", key_schema=[("b", pa.int64())]) + assert first.table_id != second.table_id + with pytest.raises(Exception, match="^404 Not Found: Resource"): + core.drop_table(table_id=first.table_id) + assert project.table("store.t").table_id == second.table_id + with pytest.raises(ValueError, match="Table not found"): + project.drop_table("store.absent") + + +def test_fake_create_has_one_winner_among_threads() -> None: + start = threading.Barrier(5) + + def create(index: int) -> bool: + project = Client().real_project + start.wait(WAIT) + try: + project.create_table("store.t", key_schema=[(f"k{index}", pa.int64())]) + except Exception as exc: + assert str(exc).startswith("409 ") + return False + return True + + with ThreadPoolExecutor(5) as pool: + assert sorted(pool.map(create, range(5))) == [False] * 4 + [True] + + +# ------------------------------------------------------------------------------ the lease + + +def test_take_check_and_release() -> None: + client = Client() + lease = take_lease(client, "My Job/№ 7." + "x" * 60) + assert client.holder().table_id == lease.table_id + (owner,) = client.holder().key_schema.names + kind, token, started, pid, job = owner.split("-") + assert (kind, int(pid), len(job)) == ("own", os.getpid(), 40) + assert uuid.UUID(token).version == 7 + assert started.endswith("Z") + assert job.startswith("my_job_7_xxx") + lease.check() + lease.release() + assert client.holder() is None + assert client.wire.log == ["create", "lookup", "drop"] + + +def test_tokens_are_never_reused() -> None: + owners = set() + for _ in range(3): + lease = take_lease(Client(), "j") + owners.add(lease.owner.split("-")[1]) + lease.release() + assert len(owners) == 3 + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +@pytest.mark.filterwarnings("ignore:.*fork.*:DeprecationWarning") +def test_a_fork_makes_its_own_tokens() -> None: + read, write = os.pipe() + child = os.fork() + if child == 0: + os.write(write, lease_module._new_token().encode()) + os._exit(0) + os.close(write) + os.waitpid(child, 0) + mine = lease_module._new_token() + assert os.read(read, 100).decode()[12:] != mine[12:] + os.close(read) + + +def test_a_second_run_is_refused_at_once_with_the_owner_and_the_id() -> None: + first = take_lease(Client(), "first job") + second = Client() + with pytest.raises(LeaseHeldError) as refused: + take_lease(second, "second job") + assert refused.value.table_id == first.table_id + assert first.owner in str(refused.value) + assert first.table_id in str(refused.value) + assert "does not show that" in str(refused.value) + assert second.wire.log.count("create") == 1 + + +def test_a_refusal_whose_holder_left_meanwhile_is_not_retried() -> None: + lease = take_lease(Client(), "first") + second = Client() + + def refused_then_released(request: Callable[[], Any]) -> Any: + try: + return request() + finally: + lease.release() + + second.wire.on("create", refused_then_released) + with pytest.raises(LeaseHeldError, match="Run again"): + take_lease(second, "second") + assert second.holder() is None + + +def test_every_run_after_a_crash_is_refused_whatever_its_owner_text_says() -> None: + """No age, process id or form of the owner text makes a lease expire.""" + client = Client() + for owner in ( + "own-" + "0" * 32 + "-20200101T000000Z-999999-old", + f"own-{'1' * 32}-20200101T000000Z-{os.getpid()}-this_pid", + "not an owner text", + ): + table = client.real_project.create_table( + f"store.{LEASE_TABLE_NAME}", key_schema=[(owner, pa.int64())] + ) + for _ in range(3): + with pytest.raises(LeaseHeldError) as refused: + take_lease(Client(), "next") + assert owner in str(refused.value) + assert clear_lease(client, table.table_id) + + +@pytest.mark.parametrize("reply", [lost_reply, retried_by_client]) +def test_a_create_that_landed_without_its_reply_is_recognised( + reply: Callable[..., Any], +) -> None: + client = Client() + client.wire.on("create", reply) + lease = take_lease(client, "j") + assert client.holder().table_id == lease.table_id + assert client.holder().key_schema.names == [lease.owner] + lease.release() + assert client.holder() is None + + +def test_a_lost_refusal_is_a_refusal() -> None: + first = take_lease(Client(), "first") + client = Client() + client.wire.on("create", lost_reply) + with pytest.raises(LeaseHeldError) as refused: + take_lease(client, "j") + assert refused.value.table_id == first.table_id + + +@pytest.mark.parametrize("create", [lost_request, lost_reply]) +def test_a_lookup_that_fails_never_grants_the_lease(create: Callable[..., Any]) -> None: + client = Client() + client.wire.on("create", create) + client.wire.on("lookup", lost_request) + with pytest.raises(LeaseUncertainError, match="own-"): + take_lease(client, "j") + assert client.wire.log == ["create", "lookup"] + + +def test_a_late_create_is_a_lease_left_behind_never_a_second_holder() -> None: + client = Client() + late: list[Callable[[], Any]] = [] + + def sent_late(request: Callable[[], Any]) -> Any: + late.append(request) + raise TimeoutError + + client.wire.on("create", sent_late) + with pytest.raises(LeaseUncertainError) as uncertain: + take_lease(client, "j") + # It lands while another run holds the lease: refused by the service. + other = take_lease(Client(), "other") + with pytest.raises(Exception, match="^409"): + late[0]() + other.check() + other.release() + # It lands on a free name: every run is refused, until a person clears it. + ghost = late[0]() + (owner,) = client.holder().key_schema.names + assert owner in str(uncertain.value) + with pytest.raises(LeaseHeldError) as refused: + take_lease(Client(), "next") + assert refused.value.table_id == ghost.table_id + assert clear_lease(Client(), ghost.table_id) + take_lease(Client(), "next").release() + + +def test_an_interrupted_create_is_undone() -> None: + client = Client() + + def interrupted(request: Callable[[], Any]) -> Any: + request() + raise KeyboardInterrupt + + client.wire.on("create", interrupted) + with pytest.raises(KeyboardInterrupt): + take_lease(client, "j") + assert client.holder() is None + + +def test_an_interrupted_create_that_cannot_be_undone_says_so() -> None: + client = Client() + + def interrupted(request: Callable[[], Any]) -> Any: + request() + raise KeyboardInterrupt + + client.wire.on("create", interrupted) + client.wire.on("lookup", lost_request) + with pytest.raises(KeyboardInterrupt) as raised: + take_lease(client, "j") + assert client.holder().key_schema.names[0] in raised.value.__notes__[0] + + +def test_drops_go_by_id_and_a_repeated_drop_spares_a_newer_lease() -> None: + first = take_lease(Client(), "first") + first.release() + newer = take_lease(Client(), "newer") + first.release() # 404: success, and nothing is dropped + newer.check() + + +@pytest.mark.parametrize("plans", [[lost_reply], [lost_request, lost_reply]]) +def test_a_drop_without_a_clear_reply_is_settled_by_its_id_alone( + plans: list[Any], +) -> None: + client = Client() + lease = take_lease(client, "j") + client.wire.on("drop", *plans) + lease.release() + assert client.holder() is None + # The drop is sent again until the id itself is answered; no look at the name decides. + assert client.wire.log == ["create", *["drop"] * (len(plans) + 1)] + + +def test_a_name_that_looks_free_does_not_prove_the_lease_is_gone() -> None: + client = Client() + lease = take_lease(client, "j") + client.wire.on("drop", *[lost_reply] * 3) + with pytest.raises(LeaseLeftError): + lease.release() + assert client.holder() is None + + +def test_a_lost_drop_reply_after_which_a_new_lease_was_taken() -> None: + client = Client() + lease = take_lease(client, "j") + newer = [] + + def dropped_then_taken(request: Callable[[], Any]) -> Any: + request() + newer.append(take_lease(Client(), "newer")) + raise TimeoutError + + client.wire.on("drop", dropped_then_taken) + lease.release() + newer[0].check() + + +def test_a_drop_that_cannot_be_settled_names_the_id() -> None: + client = Client() + lease = take_lease(client, "j") + client.wire.on("drop", *[lost_request] * 3) + with pytest.raises(LeaseLeftError) as left: + lease.release() + assert left.value.table_id == lease.table_id + assert lease.table_id in str(left.value) + + +def test_clear_drops_exactly_the_id_it_is_given() -> None: + client = Client() + table = client.real_project.create_table( + "store.data", key_schema=[("k", pa.int64())] + ) + assert not clear_lease(client, table.table_id) # no lease: never another table + first = take_lease(Client(), "first") + assert not clear_lease(client, table.table_id) + assert client.real_project.table("store.data").table_id == table.table_id + assert clear_lease(client, first.table_id) + assert not clear_lease(client, first.table_id) + second = take_lease(Client(), "second") + assert not clear_lease(client, first.table_id) + second.check() + + +# ------------------------------------------------------- every interleaving, with crashes + + +class Schedule: + """Runs writers one request at a time, in the order a list of choices gives. + + A step is ``(writer, fault)``. Choices beyond the given ones take the first option, and + the options of every step are recorded, so a caller can visit them all. + """ + + def __init__(self, choices: list[int], faults: int) -> None: + self.choices, self.faults = choices, faults + self.options: list[int] = [] + self.holding: set[int] = set() + self.late: list[Callable[[], Any]] = [] + self._turn = threading.Condition() + self._waiting: dict[int, tuple[str, Callable[[], Any]] | None] = {} + self._replies: dict[int, Callable[[], Any]] = {} + self._ended: set[int] = set() + + def run(self, bodies: list[Callable[[Wire], None]]) -> None: + errors: list[BaseException] = [] + + def writer(index: int) -> None: + wire = Wire() + wire.__class__ = type( + "Scheduled", + (Wire,), + {"__call__": lambda _, kind, request: self._ask(index, kind, request)}, + ) + try: + bodies[index](wire) + except (Killed, LeaseHeldError, LeaseUncertainError, LeaseLeftError): + pass + except BaseException as exc: + errors.append(exc) + finally: + with self._turn: + self._ended.add(index) + self._turn.notify_all() + + threads = [ + threading.Thread(target=writer, args=(i,)) for i in range(len(bodies)) + ] + for thread in threads: + thread.start() + while self._step(len(bodies)): + pass + for thread in threads: + thread.join(WAIT) + assert not thread.is_alive() + if errors: + raise errors[0] + + def _ask(self, index: int, kind: str, request: Callable[[], Any]) -> Any: + with self._turn: + if self._replies.get(index) is _die: + raise Killed + self._waiting[index] = (kind, request) + self._turn.notify_all() + assert self._turn.wait_for(lambda: index in self._replies, WAIT) + reply = self._replies[index] + if reply is not _die: + del self._replies[index] + return reply() + + def _step(self, count: int) -> bool: + with self._turn: + assert self._turn.wait_for( + lambda: len(self._ended) + len(self._waiting) == count, WAIT + ) + if not self._waiting: + for request in self.late: # what is still in flight lands now + _quietly(request) + return False + options: list[tuple[int, str]] = [] + for index, waiting in sorted(self._waiting.items()): + assert waiting is not None + options.append((index, "send")) + if self.faults: + options += [(index, "kill"), (index, "kill after")] + if waiting[0] in ("create", "drop"): + options += [(index, "lose reply"), (index, "late")] + if self.late: + options.append((-1, "land")) + taken = ( + self.choices[len(self.options)] + if len(self.options) < len(self.choices) + else 0 + ) + self.options.append(len(options)) + index, fault = options[taken] + if fault == "land": + _quietly(self.late.pop(0)) + return True + waiting = self._waiting.pop(index) + assert waiting is not None + kind, request = waiting + if fault != "send": + self.faults -= 1 + if fault in ("kill", "kill after"): + if fault == "kill after": + _quietly(request) + self.holding.discard(index) + self._replies[index] = _die + elif fault == "lose reply": + _quietly(request) + self._replies[index] = _time_out + elif fault == "late": + self.late.append(request) + self._replies[index] = _time_out + else: + # Sent here, in the scheduler's thread: one request at a time. + self._replies[index] = _outcome(request) + self._turn.notify_all() + return True + + +def _die() -> Any: + raise Killed + + +def _time_out() -> Any: + raise TimeoutError + + +def _quietly(request: Callable[[], Any]) -> None: + try: + request() + except Exception: + pass + + +def _outcome(request: Callable[[], Any]) -> Callable[[], Any]: + try: + value = request() + except Exception as exc: + error = exc + + def fail() -> Any: + raise error + + return fail + return lambda: value + + +def scheduled_writer( + schedule: Schedule, dataset: str, index: int +) -> Callable[[Wire], None]: + """Take the lease, commit once, release; never beside another holder.""" + + def write(wire: Wire) -> None: + client = Client(dataset, wire) + with write_session(client, job=f"w{index}") as capability: + try: + schedule.holding.add(index) + assert schedule.holding == {index}, "two holders" + + def data() -> None: + mine = capability._session.lease + assert client.holder().table_id == mine.table_id + + with capability.commit(client): + client.wire("write", data) + assert schedule.holding == {index}, "two holders" + finally: + schedule.holding.discard(index) + + return write + + +@pytest.mark.parametrize( + ("writers", "faults", "fewest"), [(2, 0, 20), (3, 0, 200), (2, 1, 500)] +) +def test_never_two_holders_in_any_interleaving( + writers: int, faults: int, fewest: int, tmp_path: Path +) -> None: + """Every order of the requests; with ``faults``, one fault at every possible place. + + A fault is a crash before or after a request, a lost reply, or a create or drop that + lands at any later point. Each writer takes the lease, commits once and releases. + """ + choices: list[int] = [] + runs = 0 + while True: + runs += 1 + dataset = f"run{runs}" + schedule = Schedule(choices, faults) + + schedule.run([scheduled_writer(schedule, dataset, i) for i in range(writers)]) + # the next unvisited branch + taken = choices + [0] * (len(schedule.options) - len(choices)) + while taken and taken[-1] + 1 == schedule.options[len(taken) - 1]: + taken.pop() + if not taken: + break + choices = [*taken[:-1], taken[-1] + 1] + assert runs >= fewest + + +# --------------------------------------------------------------- crashes between two steps + +STEPS = ["create", "lookup", "write", "drop"] + + +@pytest.mark.parametrize("step", STEPS) +@pytest.mark.parametrize("when", ["before", "after"]) +def test_a_crash_at_each_step_leaves_the_lease_or_nothing(step: str, when: str) -> None: + """A run is take, check, commit, release; its process dies before or after each.""" + client = Client() + + def die(request: Callable[[], Any]) -> Any: + if when == "after": + request() + kill(client) + raise Killed + + client.wire.on(step, die) + with pytest.raises(Killed): + with write_session(client, job="crash") as capability: + with capability.commit(client): + client.put(1, "a") + held = (step, when) not in (("create", "before"), ("drop", "after")) + other = Client() + assert (other.holder() is not None) is held + if held: + for _ in range(2): # it never expires + with pytest.raises(LeaseHeldError) as refused: + with write_session(other, job="next"): + raise AssertionError + assert refused.value.table_id == other.holder().table_id + assert clear_lease(other, other.holder().table_id) + with write_session(other, job="next"): + commit(other, 2, "b") + expected = {2: "b"} + if step == "drop" or (step, when) == ("write", "after"): + expected[1] = "a" + assert other.rows() == expected + + +# ------------------------------------------------------------------- sessions (section 4.5) + + +def test_a_session_takes_writes_and_releases() -> None: + client = Client() + with write_session(client, job="j") as capability: + assert current_capability() is capability + capability.require(client) + commit(client, 1, "a") + assert client.rows() == {1: "a"} + assert client.holder() is None + assert client.wire.log == ["create", "lookup", "write", "drop"] + with pytest.raises(NoWriteSessionError): + current_capability() + + +def test_an_unchanged_rerun_takes_the_lease_too() -> None: + client = Client() + with write_session(client, job="j"): + pass + assert client.wire.log == ["create", "drop"] + + +def test_a_run_that_fails_releases() -> None: + client = Client() + with pytest.raises(ZeroDivisionError): + with write_session(client, job="j"): + commit(client, 1, "a") + raise ZeroDivisionError + assert client.holder() is None + assert client.rows() == {1: "a"} + + +def test_a_write_by_hand_is_refused_before_anything_is_sent() -> None: + client = Client() + with write_session(client, job="j") as capability: + pass + with pytest.raises(NoWriteSessionError, match=r"store\.writing\(\)"): + current_capability() + for attempt in ( + lambda: capability.require(client), + lambda: capability.commit(client).__enter__(), + lambda: capability.add_final_flush(print), + ): + with pytest.raises(NoWriteSessionError): + attempt() + assert client.wire.log == ["create", "drop"] + + +def test_reads_need_no_session_and_are_never_refused() -> None: + client, reader = Client(), Client() + with write_session(client, job="j"): + commit(client, 1, "a") + with without_capability(): + assert reader.rows() == {1: "a"} + assert reader.get_table_names() == ["data", LEASE_TABLE_NAME] + assert reader.wire.log == [] + + +def test_a_dataset_the_session_did_not_lease_is_refused() -> None: + with write_session(Client("a"), job="j") as capability: + with pytest.raises(NoWriteSessionError, match="p/b"): + capability.require(Client("b")) + with pytest.raises(NoWriteSessionError, match="q/a"): + with capability.commit(Client("a", project="q")): + raise AssertionError + + +def test_a_nested_session_is_refused_before_any_request() -> None: + client, other = Client("a"), Client("b") + with write_session(client, job="j"): + for dataset in (client, other): + with pytest.raises(NestedWriteSessionError): + with write_session(dataset, job="nested"): + raise AssertionError + assert other.wire.log == [] + + +def test_user_code_has_no_authority_and_a_job_it_starts_on_the_dataset_is_refused() -> ( + None +): + client = Client() + with write_session(client, job="outer"): + with without_capability(): + with pytest.raises(NoWriteSessionError): + current_capability() + with pytest.raises(LeaseHeldError): + with write_session(client, job="nested"): + raise AssertionError + with write_session(Client("elsewhere"), job="nested"): + pass + commit(client, 1, "a") + assert client.rows() == {1: "a"} + + +def test_a_users_thread_has_no_authority() -> None: + outcome: list[object] = [] + + def users() -> None: + try: + current_capability() + except NoWriteSessionError as exc: + outcome.append(exc) + + with write_session(Client(), job="j"), without_capability(): + for target in (users, lambda: lease_module.copy_context().run(users)): + thread = threading.Thread(target=target) + thread.start() + thread.join(WAIT) + users() + assert len(outcome) == 3 + + +def test_a_users_generator_has_no_authority_at_any_step() -> None: + def users() -> Iterator[bool]: + while True: + yield lease_module._located.get() is None + + with write_session(Client(), job="j") as capability: + generator = users() + for _ in range(3): + with without_capability(): + assert next(generator) + assert current_capability() is capability + + +def test_the_locator_alone_authorizes_nothing() -> None: + """A capability is checked for its state, lease and dataset wherever it was found.""" + client = Client() + with write_session(client, job="j") as capability: + stale = lease_module.WriteCapability(capability._session, capability.role) + stale.generation = "table_of_an_earlier_lease" + token = lease_module._located.set(stale) + with pytest.raises(NoWriteSessionError): + commit(client, 1, "x") + stale.generation, stale.revoked = capability.generation, True + with pytest.raises(NoWriteSessionError): + commit(client, 1, "x") + lease_module._located.reset(token) + assert client.wire.log == ["create", "drop"] + + +def test_works_capability_ends_with_the_work() -> None: + """A thread or copied context the work left behind has no authority while the run goes on.""" + client = Client() + with ThreadPoolExecutor(1) as pool, write_session(client, job="j") as capability: + left = capability.submit(pool, lease_module.copy_context).result(WAIT) + pool.submit(lambda: None).result(WAIT) # the first future's callbacks have run + assert left.run(current_capability) is not capability + with pytest.raises(NoWriteSessionError, match="ended"): + left.run(commit, client, 1, "orphan") + commit(client, 2, "run") + assert client.rows() == {2: "run"} + + +def test_closing_admits_only_what_is_already_running() -> None: + client = Client() + running, closing = threading.Event(), threading.Event() + run: list[Any] = [] + + def work() -> None: + running.set() + assert closing.wait(WAIT) + for attempt in ( + lambda: run[0].require(client), + lambda: run[0].submit(pool, print), + lambda: run[0].commit(client).__enter__(), + lambda: run[0].add_final_flush(print), + ): + with pytest.raises(NoWriteSessionError): + attempt() + current_capability().submit(pool, commit, client, 1, "subwork") + commit(client, 2, "work") + + with ThreadPoolExecutor(2) as pool: + with write_session(client, job="j") as capability: + run.append(capability) + session = capability._session + drain = session._drain + + def noted() -> None: + closing.set() + drain() + + session._drain = noted + done = capability.submit(pool, work) + assert running.wait(WAIT) + done.result(0) + assert client.rows() == {1: "subwork", 2: "work"} + assert client.wire.log[-1] == "drop" + + +def test_a_lost_flush_capability_cannot_be_used_after_the_flush() -> None: + client, kept = Client(), [] + with write_session(client, job="j") as capability: + capability.add_final_flush(lambda: kept.append(current_capability())) + with pytest.raises(NoWriteSessionError): + kept[0].require(client) + + +def test_another_run_on_the_same_connector_object_is_refused() -> None: + client = Client() + refused: list[BaseException | None] = [] + + def second_run() -> None: + with write_session(client, job="second"): + raise AssertionError + + with write_session(client, job="first") as capability: + with ThreadPoolExecutor(1) as pool: + refused.append(pool.submit(second_run).exception(WAIT)) + refused.append(pool.submit(commit, client, 1, "x").exception(WAIT)) + capability.require(client) + commit(client, 2, "mine") + assert isinstance(refused[0], LeaseHeldError) + assert isinstance(refused[1], NoWriteSessionError) + assert client.rows() == {2: "mine"} + + +def test_orcapods_threads_write_with_the_session() -> None: + client = Client() + with ThreadPoolExecutor(4) as pool: + with write_session(client, job="j") as capability: + for key in range(8): + capability.submit(pool, commit, client, key, "t") + assert client.rows() == dict.fromkeys(range(8), "t") + assert client.wire.log[-1] == "drop" + + +def test_release_waits_for_a_thread_that_is_still_committing() -> None: + client = Client() + sending, go = threading.Event(), threading.Event() + + def slow(request: Callable[[], Any]) -> Any: + sending.set() + assert go.wait(WAIT) + return request() + + client.wire.on("write", slow) + with ThreadPoolExecutor(1) as pool, ThreadPoolExecutor(1) as runner: + + def run() -> None: + with write_session(client, job="j") as capability: + capability.submit(pool, commit, client, 1, "late") + assert sending.wait(WAIT) + + ended = runner.submit(run) + assert sending.wait(WAIT) + with pytest.raises(LeaseHeldError): + take_lease(Client(), "other") + assert not ended.done() + go.set() + ended.result(WAIT) + assert client.wire.log == ["create", "lookup", "write", "drop"] + + +def test_work_that_outlives_the_run_is_refused() -> None: + client = Client() + with ThreadPoolExecutor(1) as pool: + with write_session(client, job="j") as capability: + context = lease_module.copy_context() # a thread Orcapod did not register + for attempt in ( + lambda: capability.require(client), + lambda: commit(client, 1, "x"), + lambda: capability.submit(pool, print), + ): + with pytest.raises(NoWriteSessionError, match="closed"): + context.run(attempt) + assert client.wire.log == ["create", "drop"] + + +def test_the_final_flush_runs_after_the_drain_and_before_release() -> None: + client = Client() + client.wire.on("write", lambda request: request()) + with ThreadPoolExecutor(1) as pool: + with write_session(client, job="j") as capability: + refused: list[BaseException] = [] + + def flush() -> None: + assert client.rows() == {1: "thread"} + for attempt in ( + lambda: capability.require(client), + lambda: capability.submit(pool, print), + ): + with pytest.raises(NoWriteSessionError) as error: + attempt() + refused.append(error.value) + commit(client, 2, "flush") + + capability.add_final_flush(flush) + capability.submit(pool, commit, client, 1, "thread") + assert len(refused) == 2 + assert client.rows() == {1: "thread", 2: "flush"} + assert client.wire.log[-2:] == ["write", "drop"] + + +@pytest.mark.parametrize("run_fails", [False, True]) +def test_a_flush_that_fails_is_reported_and_the_others_run(run_fails: bool) -> None: + client, flushed = Client(), [] + + def refuse() -> None: + raise ValueError("3 rows dropped") + + with pytest.raises((ValueError, ZeroDivisionError)) as raised: + with write_session(client, job="j") as capability: + capability.add_final_flush(refuse) + capability.add_final_flush(lambda: flushed.append(1)) + if run_fails: + raise ZeroDivisionError + if run_fails: + assert "3 rows dropped" in raised.value.__notes__[0] + else: + assert str(raised.value) == "3 rows dropped" + assert flushed == [1] + assert client.holder() is None + + +def test_a_commit_that_failed_may_still_land_so_the_lease_stays() -> None: + client = Client() + landing: list[Callable[[], Any]] = [] + + def sent_late(request: Callable[[], Any]) -> Any: + landing.append(request) + raise TimeoutError + + client.wire.on("write", sent_late) + with pytest.raises(LeaseLeftError) as left: + with write_session(client, job="j"): + with pytest.raises(TimeoutError): + commit(client, 1, "late") + assert left.value.table_id == client.holder().table_id + landing[0]() # it does, and nobody else could write + assert client.rows() == {1: "late"} + + +def test_a_failed_commit_that_is_settled_does_not_keep_the_lease() -> None: + client = Client() + client.wire.on("write", lost_request) + with write_session(client, job="j") as capability: + failed: list[lease_module.Commit] = [] + with pytest.raises(TimeoutError): + with capability.commit(client) as sent: + failed.append(sent) + client.put(1, "a") + assert not failed[0].settled + commit(client, 1, "a") # a later success does not settle the earlier request + assert not failed[0].settled + failed[0].settle() + assert client.holder() is None + + +def test_a_check_that_fails_sends_nothing_and_may_be_repeated() -> None: + client = Client() + client.wire.on("lookup", lost_request) + with write_session(client, job="j"): + with pytest.raises(TimeoutError): + commit(client, 1, "a") + assert "write" not in client.wire.log + commit(client, 1, "a") + assert client.holder() is None + + +# ---------------------------------------------------------------- a cleared live lease (L2) + + +@pytest.mark.parametrize("second_run", [False, True]) +def test_a_cleared_live_lease_is_detected_at_the_next_commit(second_run: bool) -> None: + client, other = Client(), Client() + with pytest.raises(LeaseLostError): + with write_session(client, job="first"): + commit(client, 1, "first") + assert clear_lease(other, other.holder().table_id) + if second_run: + take_lease(other, "second") + with pytest.raises(LeaseLostError): + commit(client, 2, "never") + # Lost for good: no later commit looks again, nothing takes the lease back. + log = list(client.wire.log) + with pytest.raises(LeaseLostError): + commit(client, 3, "never") + assert client.wire.log == log + assert client.rows() == {1: "first"} + assert (other.holder() is not None) is second_run # the newer lease is untouched + + +def test_the_documented_window_a_commit_past_its_check_lands() -> None: + """4.3: the check is detection. There is no fencing, and this asserts that.""" + client, other = Client(), Client() + + def cleared_while_sending(request: Callable[[], Any]) -> Any: + assert clear_lease(other, other.holder().table_id) + with write_session(other, job="second"): + commit(other, 1, "second") + return request() + + client.wire.on("write", cleared_while_sending) + with pytest.raises(LeaseLostError): + with write_session(client, job="first"): + with current_capability().commit(client), without_capability(): + client.put(1, "first") + commit(client, 2, "never") + assert other.rows() == {1: "first"} # the old holder overwrote the new one's row + assert other.holder() is None + + +# --------------------------------------------------------- other datasets, other addresses + + +def test_one_dataset_through_two_connectors_is_one_lease() -> None: + first, second = Client(), Client() + with write_session(first, job="j"): + commit(first, 1, "a") + commit(second, 2, "b") + assert (first.wire.log + second.wire.log).count("create") == 1 + assert first.rows() == {1: "a", 2: "b"} + + +def test_one_service_under_two_addresses_is_refused() -> None: + """No alias is adopted: not between runs, and not within one.""" + first = Client(endpoint="https://one") + second = Client(endpoint="https://u:pw@two") + with write_session(first, job="j") as capability: + with pytest.raises(NoWriteSessionError) as inside: + capability.require(second) + with without_capability(), pytest.raises(LeaseHeldError) as between: + with write_session(second, job="j"): + raise AssertionError + for refused in (inside, between): + assert "pw" not in str(refused.value) # an endpoint can hold secrets + + +@pytest.mark.parametrize("order", [["a", "b"], ["b", "a"]]) +def test_two_datasets_are_two_sessions_that_never_wait(order: list[str]) -> None: + """A run holds one dataset; what user code opens on another is its own.""" + outer, inner = order + with write_session(Client(outer), job="outer"), without_capability(): + with write_session(Client(inner), job="inner"), without_capability(): + for name in order: + with pytest.raises(LeaseHeldError): + take_lease(Client(name), "third") + assert Client("a").holder() is None + assert Client("b").holder() is None + + +# ------------------------------------------------------------------- interrupted and forked + + +def test_an_interrupted_drain_keeps_the_lease(monkeypatch: pytest.MonkeyPatch) -> None: + client = Client() + with pytest.raises(KeyboardInterrupt) as raised: + with write_session(client, job="j") as capability: + + def interrupted(*_: Any) -> Any: + raise KeyboardInterrupt + + monkeypatch.setattr(capability._session, "_drain", interrupted) + assert client.holder().table_id in raised.value.__notes__[0] + assert "drop" not in client.wire.log + + +def test_an_interrupted_release_names_what_stays() -> None: + client = Client() + + def interrupted(request: Callable[[], Any]) -> Any: + raise KeyboardInterrupt + + client.wire.on("drop", interrupted) + with pytest.raises(KeyboardInterrupt) as raised: + with write_session(client, job="j"): + pass + assert client.holder().table_id in raised.value.__notes__[0] + + +@pytest.mark.skipif(not hasattr(os, "fork"), reason="needs fork") +@pytest.mark.filterwarnings("ignore:.*fork.*:DeprecationWarning") +@pytest.mark.parametrize("ends", ["normally", "raising"]) +def test_a_forked_child_cannot_write_and_never_releases(ends: str) -> None: + client = Client() + parent = os.getpid() + with ThreadPoolExecutor(1) as pool, write_session(client, job="j") as capability: + read, write = os.pipe() + child = os.fork() + if child == 0: + code = 1 + try: + refused = 0 + for attempt in ( + lambda: capability.require(client), + lambda: commit(client, 1, "child"), + lambda: capability.submit(pool, print), + lambda: capability.add_final_flush(print), + ): + try: + attempt() + except NoWriteSessionError: + refused += 1 + # leave the body, as a child that unwinds does + capability._session.close(None if ends == "normally" else SystemExit()) + code = 0 if refused == 4 else 2 + finally: + os._exit(code) + os.close(write) + os.close(read) + assert os.waitstatus_to_exitcode(os.waitpid(child, 0)[1]) == 0 + assert os.getpid() == parent + assert client.holder() is not None + commit(client, 2, "parent") + assert client.rows() == {2: "parent"} + assert client.holder() is None + + +# ------------------------------------------------------------------------------- async runs + + +def test_an_async_session_writes_from_tasks_and_threads() -> None: + client = Client() + + async def run() -> None: + with ThreadPoolExecutor(2) as pool: + async with async_write_session(client, job="j") as capability: + + async def work(key: int) -> None: + await asyncio.wrap_future( + current_capability().submit(pool, commit, client, key, "a") + ) + + for key in range(4): + capability.create_task(work(key)) + + asyncio.run(run()) + assert client.rows() == dict.fromkeys(range(4), "a") + assert client.holder() is None + assert client.wire.log[-1] == "drop" + + +def test_awaited_user_code_and_its_tasks_have_no_authority() -> None: + client = Client() + + async def user() -> None: + with pytest.raises(NoWriteSessionError): + current_capability() + + async def task() -> None: + current_capability() + + with pytest.raises(NoWriteSessionError): + await asyncio.create_task(task()) + + async def run() -> None: + async with async_write_session(client, job="j") as capability: + with without_capability(): + await user() + capability.require(client) + + asyncio.run(run()) + + +def test_a_second_async_run_in_the_same_loop_is_refused() -> None: + client = Client() + + async def second() -> None: + async with async_write_session(client, job="second"): + raise AssertionError + + async def run() -> None: + inside, done = asyncio.Event(), asyncio.Event() + + async def first() -> None: + async with async_write_session(client, job="first"): + inside.set() + await done.wait() + + running = asyncio.create_task(first()) + await inside.wait() + with pytest.raises(LeaseHeldError): + await second() + done.set() + await running + + asyncio.run(run()) + assert client.holder() is None + + +def test_a_cancelled_run_waits_for_the_commit_its_thread_is_sending() -> None: + client = Client() + sending, go = threading.Event(), threading.Event() + + def slow(request: Callable[[], Any]) -> Any: + sending.set() + assert go.wait(WAIT) + return request() + + client.wire.on("write", slow) + + async def run() -> None: + with ThreadPoolExecutor(1) as pool: + + async def job() -> None: + async with async_write_session(client, job="j") as capability: + await asyncio.wrap_future( + capability.submit(pool, commit, client, 1, "a") + ) + + running = asyncio.create_task(job()) + await asyncio.to_thread(sending.wait, WAIT) + for _ in range(3): # cancelled, and again while it drains + running.cancel() + await asyncio.sleep(0) + await asyncio.sleep(0) + assert not running.done() + with pytest.raises(LeaseHeldError): + take_lease(Client(), "other") + go.set() + with pytest.raises(asyncio.CancelledError): + await running + + asyncio.run(run()) + assert client.rows() == {1: "a"} + assert client.wire.log == ["create", "lookup", "write", "drop"] + + +def test_a_cancelled_task_is_waited_for() -> None: + client = Client() + + async def run() -> None: + async with async_write_session(client, job="j") as capability: + started, cleaned = asyncio.Event(), asyncio.Event() + + async def work() -> None: + started.set() + try: + await asyncio.Event().wait() + finally: + await cleaned.wait() + commit(client, 1, "cleanup") + + task = capability.create_task(work()) + await started.wait() + task.cancel() + asyncio.get_running_loop().call_soon(cleaned.set) + + asyncio.run(run()) + assert client.rows() == {1: "cleanup"} + assert client.holder() is None + + +@pytest.mark.parametrize("outcome", ["taken", "refused"]) +def test_a_run_cancelled_while_it_takes_the_lease(outcome: str) -> None: + client = Client() + blocker = take_lease(Client(), "other") if outcome == "refused" else None + asking, go = threading.Event(), threading.Event() + + def slow(request: Callable[[], Any]) -> Any: + asking.set() + assert go.wait(WAIT) + return request() + + client.wire.on("create", slow) + + async def run() -> None: + async def job() -> None: + async with async_write_session(client, job="j"): + raise AssertionError + + running = asyncio.create_task(job()) + await asyncio.to_thread(asking.wait, WAIT) + running.cancel() + await asyncio.sleep(0) + go.set() + with pytest.raises(asyncio.CancelledError): + await running + + asyncio.run(run()) + if blocker is not None: + blocker.check() + else: + assert client.holder() is None + + +def test_a_run_cancelled_while_it_releases() -> None: + client = Client() + dropping, go = threading.Event(), threading.Event() + + def slow(request: Callable[[], Any]) -> Any: + dropping.set() + assert go.wait(WAIT) + return request() + + client.wire.on("drop", slow) + + async def run() -> None: + async def job() -> None: + async with async_write_session(client, job="j"): + pass + + running = asyncio.create_task(job()) + await asyncio.to_thread(dropping.wait, WAIT) + running.cancel() + await asyncio.sleep(0) + go.set() + with pytest.raises(asyncio.CancelledError): + await running + + asyncio.run(run()) + assert client.holder() is None + + +def test_an_async_final_flush_and_a_lost_lease() -> None: + client, other = Client(), Client() + + async def run() -> None: + async with async_write_session(client, job="j") as capability: + capability.add_final_flush(lambda: commit(client, 1, "flush")) + clear_lease(other, other.holder().table_id) + + with pytest.raises(LeaseLostError): + asyncio.run(run()) + assert client.wire.log.count("write") == 0 + + +def test_a_nested_async_session_is_refused() -> None: + client = Client() + + async def run() -> None: + async with async_write_session(client, job="j"): + with pytest.raises(NestedWriteSessionError): + async with async_write_session(Client("b"), job="nested"): + raise AssertionError + + asyncio.run(run()) + + +def test_a_synchronous_session_refuses_a_task() -> None: + async def nothing() -> None: + pass + + with write_session(Client(), job="j") as capability: + with pytest.raises(NoWriteSessionError, match="asyncio"): + capability.create_task(nothing()) + with pytest.raises(NoWriteSessionError): + capability.create_task(nothing()) + + +def test_a_task_that_outlives_the_run_is_refused() -> None: + client = Client() + + async def run() -> None: + go = asyncio.Event() + + async def stray() -> None: + await go.wait() + with pytest.raises(NoWriteSessionError, match="closed"): + commit(client, 1, "late") + + async with async_write_session(client, job="j"): + task = asyncio.create_task(stray()) # not registered with the session + go.set() + await task + + asyncio.run(run()) + assert client.wire.log == ["create", "drop"]