diff --git a/changelog.d/ITL-1840.md b/changelog.d/ITL-1840.md new file mode 100644 index 000000000..ff7af217c --- /dev/null +++ b/changelog.d/ITL-1840.md @@ -0,0 +1,7 @@ +### Known limitations + +- Orcapod still cannot use SpiralDB as a job's database: a `SpiralDBConnector` refuses + every write. An internal store mode now writes and reads every stored table kind + through `ConnectorArrowDatabase` (one table per path, its identity and manifest in the + table's metadata), but nothing opens it publicly, it is not saved with a job, and its + format stays provisional, outside the 0.4.0 freeze. (ITL-1840) diff --git a/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md new file mode 100644 index 000000000..af817cf75 --- /dev/null +++ b/docs/dev/plans/2026-12-01-itl-1840-spiral-store-stage-b.md @@ -0,0 +1,168 @@ +# ITL-1840: SpiralDB store, stage B (store mode under ConnectorArrowDatabase) + +Stage B of using SpiralDB as a job's pipeline and result database (ITL-1446), on top of +stage A (ITL-1837: the spiral-sdk pin, the identity record, the codec). It carries PR 595's +store mode (ITL-1498) onto current `main`. PR 595 is not merged: its refactor of the +connector protocol (`table_name`, `has_table`, `table_paths`, `validate_records(table_name=)`) +collides with `main`'s SQL store catalog (`_sql_store.py`, ITL-1552) and is not carried. +Its `spiraldb_store_tables.py` and its tests are. + +Nothing is public. The store mode is a private constructor argument, +`SpiralDBConnector(project, dataset, _store=True)`, read and written only through +`ConnectorArrowDatabase`. A plain `SpiralDBConnector` behaves as on `main`: it reads and +refuses every write (`SpiralDBWriteNotSupportedError`). + +## Structure + +- `databases/spiraldb_store_tables.py` (`StoreTables`): the tables of one dataset in store + mode. Names come from the full path (`spiral_store_identity.spiral_store_table_name`, after + `store_table_names.require_store_path_domain`, the one path domain the identity record and + the manifest apply). Each table's metadata holds its identity record and manifest, written + in one upsert before its first rows. Rows go through the codec (`spiral_store`). +- `SpiralDBConnector` builds a `StoreTables` when `_store=True`, hands it out through the + private `_store_tables()`, and in store mode refuses raw access (`lookup_table`, + `iter_batches`, `get_table_names` and every read built on them) with a `ValueError`. Its + protocol write methods still raise `SpiralDBWriteNotSupportedError`. `to_config` refuses + a store-mode connector, so a job on one is not saved. `close` releases the store's tables. +- `ConnectorArrowDatabase` gets an internal store branch beside `_sql_store`: naming, + finding, reading, the stored-id check, listing, column info, the stored schema, the + storable-column check, validation and the write go to `StoreTables` when the connector + is a store-mode `SpiralDBConnector`. `DBConnectorProtocol` is unchanged. + +The branch is taken only for a store-mode connector. For every other connector, the +plain `SpiralDBConnector` included, the code paths are `main`'s, with one exception: a +lookup of committed rows (`get_record_by_id`, `get_all_records` and the reads built on +them) now raises `OrcapodDatabaseReadError` on every connector when finding or reading +the stored table fails, as `get_table_schema` already did. For example, a SQLite +`iter_batches` failure, or a failing catalog query, reaches the caller as +`OrcapodDatabaseReadError` (its cause the driver's error), no longer as +`sqlite3.OperationalError`; a table refused as another path's keeps its own error. + +## Rules carried over + +- A table under the computed name that is not this path's store table is refused + (`SpiralStoreTableCollisionError`): another path or format in its record, a key other + than `__record_id` binary, or rows without a manifest. A table with no rows is new to any + first writer (a creation that stopped before its first rows). +- A first write re-reads the table just before recording it and never records over what + that read shows: an equivalent manifest (compared by name and decoded, never by bytes or + order) is appended beside; anything else is refused. Without a compare-and-set and a lease + (ITL-1452) two writers can still race in between. +- Rows hold one `__data_context`, a key this Orcapod resolves, and the one the table records. + Checked when rows are added (before they are buffered) and again at flush (the table may + have been made since). +- A logical type given in storage form is made live before it is compared and buffered + (store mode only), so one column has one form in the manifest. +- Listing (`list_table_paths`, hence the stale-layout check of ITL-954): one listing of the + dataset narrowed by the name prefix, then each candidate's recorded path, cached by table + id; a listed table whose record is of a path with another name is refused, and so is a + partial or unreadable record. A table whose complete record names another store format + is listed under its recorded path with the last component `/`, + which no path can hold (a component never contains `/`): the stale-layout check reports + it (a side-effect node refuses, any other node reports and runs), and opening that path + raises a `ValueError` saying what it is. No protocol method is added (D4). + +## The write rules of ITL-1386 + +- A stored or pending id raises unless `skip_duplicates`, as for every connector + (`ConnectorArrowDatabase.add_records`). +- `existing_record_ids` is answered by one scan of the key column alone, with no filter, + intersected here with the ids asked. No other column is read. It never reads a range of + ids: how the service orders binary values is not measured, and a range taken in another + order than the service's would hide a stored id (review round 1). spiral-sdk 0.16.78 has + no membership expression; one equality per id would be a request per id, or an `or_` + chain as long as the ids, whose cost on the service is not measured either. The key + column alone is the cheapest order-independent read available. +- The stage E candidate for a keyed lookup (review round 2, not adopted here): spiral-sdk + 0.16.78's `KeyedTable.scan(key_ranges=...)` takes several `KeyRange`s with inclusive + `KeyBound`s, so a range whose start and end are both the same key, one per id, would be + a batched point lookup with no ordering assumed in Python. The fake does not model key + ranges and nothing here ran against a live SpiralDB: binary key literals, correctness + (every stored id found, under the service's own order) and the work on the service are + to be validated live before it replaces the key-column read. +- A flush reads the keys again, also for ids its add found absent (review round 2 + considered skipping it): until the one-writer lease (ITL-1838, wired into every job run + by stage D, ITL-1844), another writer, in this process or another, may store one of + those ids between the add and the flush, and an append would then replace its row. Once the lease makes this writer the only + one, the flush can rely on the add's check (ITL-1841). +- A flush never overwrites a row its key scan sees. A SpiralDB append replaces a row of the + same key, so the store writes only the keys the table does not hold in the snapshot the + flush reads its keys from (the same key-column read): a key another writer stored after + this one's add, and before that scan, keeps its first commit, as with every other + connector. A key another writer commits between that scan and the append is not seen, + and the pending row then replaces it: SpiralDB has no insert-if-absent. Nothing in this + stage closes that window; the one-writer lease (ITL-1838) and stage D, which takes it in + every job run and refuses store writes outside one (ITL-1844), do. +- Storage metadata must match on append: the stored schema (the manifest's, logical types + live) is held as for any connector that keeps field metadata (`_refuse_changed_columns`), + and the store compares the rows with the manifest again when it writes. +- An append is refused when the table's manifest records other stored names than the + codec's rule gives the rows (at any depth): the reader reads the names the manifest + records, so columns written under other names could not be read back. Only a manifest + this writer did not make (another writer, or a later naming rule) records other names. +- Rows of another data context than those pending for the same table are refused when + they are added, never buffered, as the write refuses a batch of two contexts. + +## Finding a table, and what is kept + +- Every keyed table the store opens (by name or by id) or creates is opened or created by + `spiraldb_connector` (`_open_keyed_table`, `_open_keyed_table_by_id`, + `_create_keyed_table`), handed to `StoreTables` as callables: spiral-sdk 0.16.79 and later + warn on every keyed-table call, attributed to the calling module, and Orcapod ignores that + warning for that module's own calls only (stage A, `_ignore_keyed_table_deprecation`). + +- A table's name is opened once per public operation of `ConnectorArrowDatabase` (an add, + a flush, a read, a schema or listing call; `StoreTables.operation`), and that handle + reused within it until the store writes to the table (review round 2). A flush of a table + that holds rows opens the name twice: the caller's schema check reads through the + operation's handle, and the write then looks the name up again and reads the keys from + that new snapshot. The second lookup is needed because the check is the caller's code + (run outside the operation): it, or another writer meanwhile, can rename or replace the + table or commit a key, and a write through the earlier handle would then append to the + wrong table or replace that key's row. The next + operation opens it again: a table can be renamed and another made under its name, so + nothing is read or written through an earlier operation's answer. What a table that + holds rows records (key, identity record, manifest) is kept by its table id. +- What a name was judged (no table; a table with no rows, with what it recorded; a table + with rows) is kept in the thread's operation only. No other call can change it: a table + judged empty reads as no rows for the rest of the operation, and a first write compares + the table with what its own judgment saw. +- What a first write records is kept only once its append succeeded. A failed append + (also one the service stored before the error reached the client) forgets it, and the + next call judges the table again. +- A logical type's identifier bytes are compared as given, before a storage-form column is + made live, against the pending batch and the manifest as recorded (ITL-1371). +- One declaration rule, `spiraldb_store_tables.declared_keeping_identifier`, gives the + rows buffered and flushed, the schema a table reports and the schema its rows are + decoded under: a column is made live, under the data context of the rows or of the + table, only when the live type states exactly the identifier bytes recorded; one the + type reads under other bytes (an older identifier) stays in its storage form (review + round 2). A table first written with an older identifier reads back, reports its + schema and appends with those bytes. +- `get_table_schema` of a stored table is the manifest's schema, field and schema metadata + included, as a read gives it. + +## Tests + +`tests/test_databases/test_spiraldb_store_mode.py`, on the fake only: + +- each table kind (`pdb_v2`, `rdb_v1`, `odb_v3`, `sdb_v2`, `tdb_v2`) written by a job (a + function node, a logged operator node, a sink) and a `CachedSource`, listed and read back + by a fresh connector, and a second run that calls and delivers nothing; sync and async; +- a new input adds rows to every table and leaves the stored rows unchanged, sync and + async; `job.run()` and `job.run_async()` with an observer, and a rerun that holds rows; +- the ITL-1386 rules, the key-column read (several ids, in both orders, under a service + that orders binary values otherwise), failed appends, renamed and replaced tables, + identifier bytes on both sides, refusals of + foreign tables, the data-context checks, the path domain, listing, concurrent first + writers, and that a plain connector still writes nothing. + +## What is left (later stages of ITL-1446) + +The one-writer lease (ITL-1452), the public switch-on with save and load, the live run, +and fewer service calls per run (keyed reads, one existence answer per run). + +Known limit (stage E, ITL-1841): each strict existence check, and each flush, reads the +table's whole key column, so its cost grows with the table's history; +successive batches into a growing table cost quadratically many keys in all. Reads of +stored rows read the whole table the same way. diff --git a/src/orcapod/databases/connector_arrow_database.py b/src/orcapod/databases/connector_arrow_database.py index 87d259f7d..94a20a9ce 100644 --- a/src/orcapod/databases/connector_arrow_database.py +++ b/src/orcapod/databases/connector_arrow_database.py @@ -22,8 +22,9 @@ from collections import defaultdict from collections.abc import Callable, Collection, Mapping from contextlib import AbstractContextManager, nullcontext +from functools import wraps from threading import Lock -from typing import Any, cast +from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar, cast from weakref import WeakKeyDictionary, WeakValueDictionary import pyarrow as pa @@ -42,8 +43,19 @@ stored_path, ) from orcapod.databases.postgresql_connector import PostgreSQLConnector +from orcapod.databases.spiraldb_connector import SpiralDBConnector +from orcapod.databases.spiral_store_identity import ( + SpiralStoreTableCollisionError, + refuse_other_format_path, +) +from orcapod.databases.spiraldb_store_tables import ( + StoreTables, + declared_keeping_identifier, +) +from orcapod.logical_types.canonical_form import storage_form_schema from orcapod.databases.store_table_names import ( STORE_TABLE_NAME_PREFIX, + require_store_path_domain, store_table_name, store_table_path_json, table_name_hint, @@ -69,6 +81,11 @@ normalize_to_large_types, ) +if TYPE_CHECKING: + from orcapod.logical_types.protocols import ( + TypeConverterProtocol as LogicalTypeConverterProtocol, + ) + #: The ``type`` of a connector database's saved configuration. CONNECTOR_DATABASE_TYPE = "connector_arrow_database" @@ -107,6 +124,72 @@ def _arrow_schema_to_column_infos(schema: pa.Schema) -> list[ColumnInfo]: ] +def _with_live_logical_types( + records: pa.Table, converter: "LogicalTypeConverterProtocol" +) -> pa.Table: + """Return ``records`` with each column given in a logical type's storage form live, + when that changes nothing about its identifier. + + For a SpiralDB store only (ITL-1840): rows are buffered and recorded in one form, so + a column given in storage form (its identifier as ``ARROW:extension:*`` field + metadata) is wrapped as the live type the rows' data context resolves for it, the + one rule a read and a table's schema apply too (``declared_keeping_identifier``: a + registered type, or one a factory rebuilds from the identifier). A column is + wrapped only when the live type states + exactly the identifier bytes given: one the reader also reads under other bytes (an + older identifier) is kept as given, so the bytes are never replaced + (ITL-1371). Any other column, an identifier nothing resolves included, is kept + exactly as given. + + Args: + records: The rows, in their large variants. + converter: The type converter of the rows' data context. + + Returns: + The rows, with the columns wrapped. + + Raises: + LogicalTypeIdentifierError: If a column names a known logical type with + metadata or storage that type does not read, naming the column. + """ + for position, field in enumerate(records.schema): + if isinstance(field.type, pa.BaseExtensionType): + continue + declared = declared_keeping_identifier(field, converter) + live = declared.type + if not isinstance(live, pa.ExtensionType) or live.storage_type != field.type: + continue # kept as given: no logical type, or another identifier's bytes + column = live.wrap_array(records.column(position)) + records = records.set_column(position, declared, column) + return records + + +_P = ParamSpec("_P") +_R = TypeVar("_R") + + +def _one_store_operation( + method: "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]", +) -> "Callable[Concatenate[ConnectorArrowDatabase, _P], _R]": + """Run a public method as one operation of a SpiralDB store (``StoreTables.operation``): + each table name is opened once inside it and its handle reused. Any other + connector calls the method as it is. + """ + + @wraps(method) + def wrapped( + self: ConnectorArrowDatabase, *args: _P.args, **kwargs: _P.kwargs + ) -> _R: + if self._spiral_connector is None: # pyright: ignore[reportPrivateUsage] + return method(self, *args, **kwargs) + store = self._spiral # pyright: ignore[reportPrivateUsage] + assert store is not None + with store.operation(): + return method(self, *args, **kwargs) + + return wrapped + + def _alike(parts: list[pa.Table]) -> list[pa.Table]: """Stored and queued rows under one schema when they differ only in a column's nullability: a store may read a column back ``NOT NULL`` (PostgreSQL's primary @@ -144,6 +227,11 @@ class ConnectorArrowDatabase: on ``flush()``. SQLite and PostgreSQL table names use a readable path hint and a digest of the full path. A catalog records the original path. + A ``SpiralDBConnector`` opened in store mode (private, ITL-1840) is read and + written through its store tables (``spiraldb_store_tables``): names computed from + the full path, identity and manifest in each table's metadata, rows through the + store codec. A plain ``SpiralDBConnector`` refuses every write, as before. + Args: connector: A ``DBConnectorProtocol`` implementation providing the underlying DB access (connection, type mapping, queries, writes). @@ -174,6 +262,13 @@ def __init__( self._sql_store: SQLStoreConnector | None = ( connector if isinstance(connector, SQLStoreConnector) else None ) + # A SpiralDB connector in store mode; ``None`` for any other (ITL-1840). + self._spiral_connector: SpiralDBConnector | None = ( + connector + if isinstance(connector, SpiralDBConnector) + and connector._store_tables() is not None # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + else None + ) self.max_hierarchy_depth = max_hierarchy_depth self._path_prefix = _path_prefix self._root = _root @@ -225,6 +320,17 @@ def __init__( connector, self._pending_commits ) + @property + def _spiral(self) -> StoreTables | None: + """The SpiralDB store's tables, or ``None`` for any other connector. + + Raises: + RuntimeError: If the store's connector has been closed. + """ + if self._spiral_connector is None: + return None + return self._spiral_connector._store_tables() # pyright: ignore[reportPrivateUsage] # the store's one reader and writer + def _discard_pending_state(self, key: str) -> None: """Forget indexes when an entire queued batch is discarded.""" self._pending_skip_existing.pop(key, None) @@ -237,6 +343,12 @@ def _discard_pending_state(self, key: str) -> None: def _get_record_key(self, record_path: tuple[str, ...]) -> str: full_path = self._plain_path(self._path_prefix + record_path) if self._sql_store is None: + if self._spiral_connector is not None: + # A path list_table_paths gives a table of another store format, + # then the one path domain of a SpiralDB store (its identity record + # and manifest apply it too). + refuse_other_format_path(full_path) + _ = require_store_path_domain(full_path) return "/".join(full_path) self._validate_path_components(full_path) return f"{self._sql_store.get_current_store_schema()}\0{'/'.join(full_path)}" @@ -261,6 +373,8 @@ def _schema_from_record_key(self, record_key: str) -> str | None: def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: """Map a full record path to a name the connector can store.""" + if (store := self._spiral) is not None: + return store.table_name(self._plain_path(record_path)) if self._sql_store is not None and record_path: return store_table_name( self._plain_path(record_path), @@ -276,6 +390,8 @@ def _path_to_table_name(self, record_path: tuple[str, ...]) -> str: def _validate_record_path(self, record_path: tuple[str, ...]) -> None: if not record_path: raise ValueError("record_path cannot be empty") + if self._spiral_connector is not None: + refuse_other_format_path(record_path) if len(self._path_prefix) + len(record_path) > self.max_hierarchy_depth: raise ValueError( f"record_path depth {len(record_path)} exceeds maximum " @@ -351,6 +467,8 @@ def _find_committed_table( self, table_name: str, full_path: tuple[str, ...], *, schema: str | None ) -> tuple[str | None, str] | None: """Return the verified schema and name of a committed table.""" + if (store := self._spiral) is not None: + return (None, table_name) if store.has_table(table_name) else None if self._sql_store is None: if table_name in self._connector.get_table_names(): return None, table_name @@ -369,22 +487,43 @@ def _find_committed_table( def _get_committed_table( self, record_path: tuple[str, ...], *, schema: str | None ) -> pa.Table | None: - """Fetch all committed records for a path from the connector.""" + """Fetch all committed records for a path from the connector. + + Raises: + OrcapodDatabaseReadError: If the table cannot be found or read, on + every connector (finding it reads the store too): a lookup that + cannot read the stored table fails the run rather than one row + (``job.run``'s contract for an unreadable stored table), as + ``get_table_schema`` does. + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. + """ full_path = self._path_prefix + record_path table_name = self._path_to_table_name(full_path) + # Outside the ``try``: an invalid path is no table, so its refusal must + # not be reported as a stored table that could not be read. self._require_table_name(table_name) - table = self._find_committed_table(table_name, full_path, schema=schema) - if table is None: - return None - schema, name = table - batches = list( - self._connector.iter_batches( - f"SELECT * FROM {sql_table_identifier(name, schema)}" - ) - ) - if not batches: - return None - return pa.Table.from_batches(batches) + try: + # Finding the table reads the store too (a SpiralDB table's metadata, a + # SQL catalog): a failure there is a read error, as in ``get_table_schema``. + table = self._find_committed_table(table_name, full_path, schema=schema) + if table is None: + return None + schema, name = table + if (store := self._spiral) is not None: + batches = list(store.scan(name)) + else: + batches = list( + self._connector.iter_batches( + f"SELECT * FROM {sql_table_identifier(name, schema)}" + ) + ) + except (OrcapodDatabaseError, SpiralStoreTableCollisionError): + # A table that is not this path's is refused as such, never as unreadable. + raise + except Exception as exc: + raise OrcapodDatabaseReadError(table_name, full_path) from exc + return pa.Table.from_batches(batches) if batches else None def _stored_conflicts( self, table: tuple[str | None, str], input_ids: set[bytes] @@ -392,6 +531,8 @@ def _stored_conflicts( """Return input IDs found in the committed table.""" schema, name = table column = self.RECORD_ID_COLUMN + if (store := self._spiral) is not None: + return store.existing_record_ids(name, input_ids) if self._sql_store is not None: assert schema is not None return self._sql_store.existing_record_ids( @@ -399,6 +540,7 @@ def _stored_conflicts( ) return self._connector.existing_record_ids(name, column, input_ids) + @_one_store_operation def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...]]: """List the paths of the tables stored under ``prefix``. @@ -406,6 +548,15 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] catalog and pending batches. Other connectors list by sanitized names. No record table is read. + A SpiralDB store lists its tables by the paths their identity records hold. + A table whose record names another store format is listed with the last + component ``"/"``, which no layout and no store path + can equal (a component never holds ``/``): stale-layout detection reports it + as a table of another layout, and opening that path raises ``ValueError`` + saying what it is. A partial or unreadable record, or a record of a path + whose table has another name, refuses the whole listing + (``SpiralStoreTableCollisionError``). + Args: prefix: Leading path components, relative to ``self.base_path``. @@ -413,6 +564,15 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] The table paths, relative to ``self.base_path``, sorted. """ full_prefix = self._path_prefix + prefix + if (store := self._spiral) is not None: + full_prefix = self._plain_path(full_prefix) + pending = [self._record_path_from_key(key) for key in self._pending_batches] + return sorted( + { + path[len(self._path_prefix) :] + for path in store.table_paths(full_prefix, pending) + } + ) if self._sql_store is not None: full_prefix = self._plain_path(full_prefix) stem = STORE_TABLE_NAME_PREFIX + table_name_hint( @@ -456,6 +616,7 @@ def list_table_paths(self, prefix: tuple[str, ...] = ()) -> list[tuple[str, ...] found.add(prefix + tuple(name[len(stem) + 2 :].split("__"))) return sorted(found) + @_one_store_operation def table_exists(self, record_path: tuple[str, ...]) -> bool: """Return ``True`` if a table exists at ``record_path``. @@ -482,6 +643,7 @@ def table_exists(self, record_path: tuple[str, ...]) -> bool: # ── Storable columns ────────────────────────────────────────────────────── + @_one_store_operation def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: """Read the committed or queued schema without fetching rows. @@ -505,6 +667,9 @@ def get_table_schema(self, record_path: tuple[str, ...]) -> pa.Schema | None: pending = self._pending_batches.get(record_key) return None if pending is None else pending.schema schema, name = table + if (store := self._spiral) is not None: + # As recorded: field and schema metadata included, as a read gives. + return store.arrow_schema(name) return pa.schema( pa.field(column.name, column.arrow_type, nullable=column.nullable) for column in self._column_info(name, schema) @@ -531,12 +696,17 @@ def require_storable(self, schema: pa.Schema) -> None: UnstorableColumnError: For the first column the connector cannot store, naming the connector, the column, its Arrow type and why. """ + store = self._spiral for field in schema: - reason = self._connector.unstorable_column_reason( - field.name, - field.type, - primary_key=field.name == self.RECORD_ID_COLUMN, - ) + primary_key = field.name == self.RECORD_ID_COLUMN + if store is not None: + reason = store.unstorable_column_reason( + field.name, field.type, primary_key + ) + else: + reason = self._connector.unstorable_column_reason( + field.name, field.type, primary_key=primary_key + ) if reason is not None: raise UnstorableColumnError( database_kind=type(self._connector).__name__, @@ -601,8 +771,12 @@ def validate_records(self, records: pa.Table) -> None: Args: records: The rows (any number, none included) to check. """ + if (store := self._spiral) is not None: + store.validate(records, None) + return self._connector.validate_records(records) + @_one_store_operation def add_records( self, record_path: tuple[str, ...], @@ -652,9 +826,44 @@ def add_records( table_name = self._path_to_table_name(full_path) self._require_table_name(table_name) records = normalize_table_to_large_types(records, keep_null=True) - self._connector.validate_records(records) + # The schemas a SpiralDB store holds for the table, as recorded. + recorded: list[pa.Schema] = [] + if (store := self._spiral) is not None: + from orcapod.contexts import resolve_context + + # The identifier bytes as given, against those held as recorded, before + # any form is converted (ITL-1371). + recorded = self._recorded_schemas(record_path) + self._refuse_changed_columns( + record_path, + storage_form_schema(records.schema), + recorded, + identity_only=True, + ) + # A logical type given in its storage form is the same column as one given + # live: buffered and stored in one form, resolved under the rows' own data + # context. That context is checked against the one the table records, + # before the rows are buffered. + converter = resolve_context(store.data_context(records)).type_converter + records = _with_live_logical_types( + records, + cast("LogicalTypeConverterProtocol", cast(object, converter)), + ) + store.validate(records, table_name) + else: + self._connector.validate_records(records) record_key = self._get_record_key(record_path) + if store is not None: + # One data context per store table, as its write requires: rows of another + # one than those pending for the table are refused here, never buffered. + pending = self._pending_batches.get(record_key) + if pending is not None: + from orcapod.contexts.stored import require_same_data_context + + require_same_data_context( + store.data_context(records), store.data_context(pending) + ) committed_table = None pending_owner_key: tuple[str, str] | None = None if self._sql_store is not None: @@ -675,10 +884,21 @@ def add_records( # A column of another logical type is refused first, on the raw identifier # bytes, before the reorder compares types (ITL-1371). # The held schemas are gathered once for both checks (one table listing). - held = self._held_schemas(record_path) - self._refuse_changed_columns(record_path, records, held, identity_only=True) - records = in_held_column_order(records, self._held_column_order(record_path)) - self._refuse_changed_columns(record_path, records, held) + if store is not None: + # Compared as recorded: every logical type in its storage form. + records = in_held_column_order( + records, self._held_column_order(record_path) + ) + self._refuse_changed_columns( + record_path, storage_form_schema(records.schema), recorded + ) + else: + held = self._held_schemas(record_path) + self._refuse_changed_columns(record_path, records, held, identity_only=True) + records = in_held_column_order( + records, self._held_column_order(record_path) + ) + self._refuse_changed_columns(record_path, records, held) records = self._deduplicate_within_table(records) input_ids = set(cast(list[bytes], records[self.RECORD_ID_COLUMN].to_pylist())) @@ -770,6 +990,8 @@ def _held_column_order( def _column_info(self, table_name: str, schema: str | None) -> list[ColumnInfo]: """Inspect the relation selected by the catalog when a schema was verified.""" + if (store := self._spiral) is not None: + return store.column_info(table_name) if self._sql_store is not None: return self._sql_store.get_column_info(table_name, schema=schema) return self._connector.get_column_info(table_name) @@ -815,10 +1037,34 @@ def _held_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema] | None: held.append(stored) return held + def _recorded_schemas(self, record_path: tuple[str, ...]) -> list[pa.Schema]: + """The schemas a SpiralDB store holds for a table, as recorded: the pending + batch's and the stored manifest's, every logical type in its storage form with + the identifier bytes it was given with (``_with_live_logical_types`` never + replaces them). For the identifier check, before any form is converted. + + Args: + record_path: The table's path, relative to ``base_path``. + + Returns: + The schemas, pending first. + """ + store = self._spiral + assert store is not None + held: list[pa.Schema] = [] + record_key = self._get_record_key(record_path) + pending = self._pending_batches.get(record_key) + if pending is not None: + held.append(storage_form_schema(pending.schema)) + table_name = self._path_to_table_name(self._path_prefix + record_path) + if store.has_table(table_name): + held.append(store.recorded_schema(table_name)) + return held + def _refuse_changed_columns( self, record_path: tuple[str, ...], - records: pa.Table, + records: pa.Table | pa.Schema, held: list[pa.Schema] | None, *, identity_only: bool = False, @@ -844,7 +1090,8 @@ def _refuse_changed_columns( # A column of another logical type would read back as the held one (ITL-1371). changed = first_logical_identity_change(held, records) if changed is None and not identity_only: - changed = first_changed_column(held, records.schema) + schema = records if isinstance(records, pa.Schema) else records.schema + changed = first_changed_column(held, schema) if changed is not None: raise InputValidationError( f"Cannot append to the table at {record_path!r}: column " @@ -859,6 +1106,8 @@ def _read_stored_schema( Read without rows from a connector that offers ``get_arrow_schema`` (``SpiralDBConnector``); from any other, the schema of its first batch. """ + if (store := self._spiral) is not None: + return store.arrow_schema(table_name) get_arrow_schema = getattr(self._connector, "get_arrow_schema", None) if callable(get_arrow_schema): return cast("pa.Schema", get_arrow_schema(table_name)) @@ -945,6 +1194,7 @@ def guard_table_schema( self._get_record_key(record_path), check ) + @_one_store_operation def flush(self) -> None: """Insert all ready batches into the connector.""" for record_key in list(self._pending_batches): @@ -959,6 +1209,7 @@ def flush_result_batch( """Commit a durable result table even if no pipeline records are stored.""" self.flush_batch(record_path) + @_one_store_operation def flush_batch(self, record_path: tuple[str, ...]) -> None: """Commit one table's ready records.""" self._flush_by_key(self._get_record_key(record_path)) @@ -983,7 +1234,9 @@ def _flush_by_key(self, record_key: str) -> None: record_path = self._record_path_from_key(record_key) table_name = self._path_to_table_name(record_path) self._require_table_name(table_name) - if self._sql_store is None: + if (store := self._spiral) is not None: + transaction = nullcontext((None, store.has_table(table_name))) + elif self._sql_store is None: transaction = nullcontext( (None, table_name in self._connector.get_table_names()) ) @@ -1033,14 +1286,40 @@ def _write_ready_batch( schema: str | None, ) -> None: """Check the current schema and write the ready rows.""" + store = self._spiral + if store is not None: + # The rows against the table as it is now: it may have been made since + # they were buffered, recording another data context or other identifiers + # (compared as recorded, before any form is converted: ITL-1371). + store.validate(pending, table_name) + if table_exists: + self._refuse_changed_columns( + self._record_path_from_key(record_key), + storage_form_schema(pending.schema), + [store.recorded_schema(table_name)], + ) columns = _arrow_schema_to_column_infos(pending.schema) # Look up the held schema inside the write transaction (ITL-1367). existing = self._stored_columns(table_name, schema) if table_exists else None check = self._pending_commits.schema_check(record_key) if check is not None: - check(pending.schema if existing is None else pa.schema(existing)) + if existing is None: + schema_now = pending.schema + elif store is not None: + # As recorded: field and schema metadata included, as + # ``get_table_schema`` gives it. + schema_now = store.arrow_schema(table_name) + else: + schema_now = pa.schema(existing) + if store is None: + check(schema_now) + else: + # The caller's check runs outside this operation: a public call it + # makes looks every name up again, and the write opens its table again. + with store.outside_operation(): + check(schema_now) if existing is not None: - if self.keeps_field_metadata: + if self.keeps_field_metadata and store is None: # A different handle may have created the table after this batch # was queued. The connector's ColumnInfo omits field metadata. held = self._read_stored_schema(table_name, schema) @@ -1074,7 +1353,13 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # Another writer can commit an ID after it was checked at add time. # Use the connector's atomic insert-if-missing for both modes. - if self._sql_store is None: + if store is not None: + # Writes only the keys the write's fresh key read does not show: a row + # visible then is never overwritten (SpiralDB's append replaces a row of + # the same key). A key another writer stores after that read can still + # be replaced until the one-writer lease (ITL-1452). + store.write(table_name, pending) + elif self._sql_store is None: self._connector.create_table_if_not_exists( table_name, columns, pk_column=self.RECORD_ID_COLUMN ) @@ -1109,6 +1394,7 @@ def _fmt(cols: Mapping[str, pa.DataType]) -> str: # ── Read methods ────────────────────────────────────────────────────────── + @_one_store_operation def get_record_by_id( self, record_path: tuple[str, ...], @@ -1158,6 +1444,7 @@ def get_record_by_id( report_records(record_key, added=set(), durable={record_id}) return self._handle_record_id_column(filtered, record_id_column) + @_one_store_operation def get_all_records( self, record_path: tuple[str, ...], @@ -1189,6 +1476,7 @@ def get_all_records( table = parts[0] if len(parts) == 1 else pa.concat_tables(_alike(parts)) return self._handle_record_id_column(table, record_id_column) + @_one_store_operation def get_records_by_ids( self, record_path: tuple[str, ...], @@ -1213,6 +1501,7 @@ def get_records_by_ids( return None return self._handle_record_id_column(filtered, record_id_column) + @_one_store_operation def get_records_with_column_value( self, record_path: tuple[str, ...], diff --git a/src/orcapod/databases/spiral_store_identity.py b/src/orcapod/databases/spiral_store_identity.py index baae18c2b..bc0521355 100644 --- a/src/orcapod/databases/spiral_store_identity.py +++ b/src/orcapod/databases/spiral_store_identity.py @@ -174,13 +174,63 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord """ if not any(k in metadata for k in _RECORD_KEYS): return None - missing = [k for k in _RECORD_KEYS if k not in metadata] - if missing: - raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + _require_complete(metadata) if metadata[STORE_KEY] != STORE_FORMAT.encode(): raise SpiralStoreTableCollisionError( f"its format is {metadata[STORE_KEY]!r}, not {STORE_FORMAT!r}" ) + return _read_record(metadata) + + +def read_store_table_record_of_any_format( + metadata: Mapping[str, bytes], +) -> tuple[StoreTableRecord, str] | None: + """Return a table's record and the store format it names, whatever the format. + + For a listing only: it places a table of another store format by its recorded + path, so the listing can report it without reading it. Every check + ``read_store_table_metadata`` makes is made, except that the format must be this + store's; a table is never opened through what this returns. + + Args: + metadata: The table's metadata, as SpiralDB returns it. + + Returns: + The record and its format, or ``None`` when the table holds none of its + entries. + + Raises: + SpiralStoreTableCollisionError: If the record is partial or unreadable (its + format included, or empty). + """ + if not any(k in metadata for k in _RECORD_KEYS): + return None + _require_complete(metadata) + try: + store_format = metadata[STORE_KEY].decode() + except UnicodeDecodeError as exc: + raise SpiralStoreTableCollisionError( + f"its record cannot be read: {exc}" + ) from exc + if not store_format: + raise SpiralStoreTableCollisionError("its record names no store format") + return _read_record(metadata), store_format + + +def _require_complete(metadata: Mapping[str, bytes]) -> None: + """Refuse a record that lacks one of its entries.""" + missing = [k for k in _RECORD_KEYS if k not in metadata] + if missing: + raise SpiralStoreTableCollisionError(f"its record lacks {missing}") + + +def _read_record(metadata: Mapping[str, bytes]) -> StoreTableRecord: + """The record of complete metadata, its format aside. + + Raises: + SpiralStoreTableCollisionError: If the record cannot be read, or its path, + layout or data context is not one a store table records. + """ try: path: object = json.loads(metadata[PATH_KEY].decode()) # pyright: ignore[reportAny] # checked below layout = metadata[LAYOUT_KEY].decode() @@ -211,6 +261,46 @@ def read_store_table_metadata(metadata: Mapping[str, bytes]) -> StoreTableRecord return StoreTableRecord(components, layout, data_context_key) +OTHER_FORMAT_SEPARATOR = "/" +"""Joins a recorded layout and a store format in the last component a listing gives a +table of another store format. No store path component holds it +(``require_store_path_domain``), so that component never names a layout or a path.""" + + +def other_format_last_component(record: StoreTableRecord, store_format: str) -> str: + """The last component a listing gives a table of another store format. + + Args: + record: The table's record. + store_format: The store format the record names. + + Returns: + ``"/"``. + """ + return f"{record.layout}{OTHER_FORMAT_SEPARATOR}{store_format}" + + +def refuse_other_format_path(path: Sequence[str]) -> None: + """Refuse a path a listing gives a table of another store format. + + Args: + path: A record path to open. + + Raises: + ValueError: If the path's last component is of the form + ``"/"`` (``other_format_last_component``). + """ + if not path or not isinstance(path[-1], str): + return + layout, separator, store_format = path[-1].partition(OTHER_FORMAT_SEPARATOR) + if separator and layout and store_format: + raise ValueError( + f"{list(path)} is how list_table_paths shows a table of another store " + f"format ({store_format!r}): it is not this store's table and cannot be " + "opened" + ) + + def require_store_table_path(record: StoreTableRecord, path: Sequence[str]) -> None: """Refuse a store table whose record is of another path than ``path``. diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 7067b2daf..f0de7c74e 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -49,6 +49,7 @@ describe_difference, ) from orcapod.databases.spiraldb_sign_in import require_sign_in, saved_login_path +from orcapod.databases.spiraldb_store_tables import StoreTables from orcapod.errors import ( NullInNonNullableColumnError, SpiralDBWriteNotSupportedError, @@ -228,6 +229,16 @@ def _open_keyed_table( return None +def _open_keyed_table_by_id(client: Any, table_id: str) -> Any: + """Return the latest snapshot of the keyed table with id ``table_id``. + + Opened here, so spiral-sdk's keyed-table deprecation is ignored for it as for every + other open Orcapod makes (``_ignore_keyed_table_deprecation``). + """ + _ignore_keyed_table_deprecation() + return client.keyed_table_by_id(table_id) + + def _create_keyed_table( client: Any, project_id: str, @@ -949,6 +960,11 @@ class SpiralDBConnector: dataset: Dataset within the project. Defaults to ``"default"``. overrides: Optional: ``{"server.url": "https://api.spiraldb.dev"}``, the address of the service. Any other key is refused. + _store: Open the dataset as a pipeline store (``spiraldb_store_tables``), for + ``ConnectorArrowDatabase``: tables named from their paths, rows through the + store codec. Private until the store is switched on (ITL-1446): such a + connector is not saved, and its tables are read and written only through + ``ConnectorArrowDatabase``. """ def __init__( @@ -956,6 +972,8 @@ def __init__( project_id: str, dataset: str = "default", overrides: dict[str, str] | None = None, + *, + _store: bool = False, ) -> None: self._project_id = project_id self._dataset = dataset @@ -979,6 +997,27 @@ def __init__( lambda doing: _service_call(f"{doing} of {project_id}/{dataset}", health), _kept_rows_for(_api_url(overrides), project_id, dataset), ) + # Kept after ``close`` releases the store's tables, so a closed store connector + # never acts as a plain one. + self._store_mode = _store + self._store: StoreTables | None = None + if _store: + self._store = StoreTables( + sp, + project_id, + dataset, + lambda name: _open_keyed_table( + client, project_id, dataset, name, health + ), + lambda table_id: _open_keyed_table_by_id(client, table_id), + lambda name, key: _create_keyed_table( + client, project_id, dataset, name, key, exist_ok=False + ), + lambda: _list_keyed_tables(client, project_id, dataset), + lambda doing: _service_call( + f"{doing} of {project_id}/{dataset}", health + ), + ) def _require_open(self) -> None: """Raise RuntimeError if this connector has been closed.""" @@ -986,6 +1025,27 @@ def _require_open(self) -> None: raise RuntimeError("SpiralDBConnector is closed") require_same_process(self._pid) + def _store_tables(self) -> StoreTables | None: + """The store's tables, or ``None`` on a plain connector. + + For ``ConnectorArrowDatabase``, the only reader and writer of a store's tables. + + Raises: + RuntimeError: If this is a store-mode connector and it has been closed. + """ + if not self._store_mode: + return None + self._require_open() + return self._store + + def _refuse_in_store_mode(self) -> None: + """Refuse an operation on raw tables of a store-mode connector.""" + if self._store_mode: + raise ValueError( + "a store-mode SpiralDB connector reads and writes its tables through " + "ConnectorArrowDatabase only, never as raw tables" + ) + def share_client(self) -> SpiralDBConnector: """Return an independently closable connector in the same SDK client scope.""" self._require_open() @@ -1020,6 +1080,7 @@ def get_table_names(self) -> list[str]: Sorted list of plain table name strings (no ``dataset.`` prefix). """ self._require_open() + self._refuse_in_store_mode() with self._service_call("list the tables of", "*"): listed = _list_keyed_tables(self._client, self._project_id, self._dataset) with _about_table(f"{self._project_id}/{self._dataset}"): @@ -1046,9 +1107,11 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: Raises: SpiralDBTableNotFoundError: If there is no such table. - ValueError: If the name is the schema table's. + ValueError: If the name is the schema table's, or this connector is in store + mode. """ self._require_open() + self._refuse_in_store_mode() self._require_user_table(table_name) missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}" if ( @@ -1187,6 +1250,7 @@ def iter_batches( non-nullable column (naming the table and the column). """ self._require_open() + self._refuse_in_store_mode() if params is not None: logger.warning( "SpiralDBConnector does not support query parameters; " @@ -1397,6 +1461,9 @@ def close(self) -> None: del self._client del self._shared del self._schemas + # The store's tables hold the client too; a connector from + # ``share_client`` keeps its own reference to them. + self._store = None def __enter__(self) -> SpiralDBConnector: return self @@ -1413,7 +1480,13 @@ def to_config(self) -> dict[str, Any]: Raises: RuntimeError: If this connector has been closed. + ValueError: If this connector is in store mode, which is not saved yet. """ + if self._store_mode: + raise ValueError( + "a store-mode SpiralDB connector is not saved: the store is not " + "switched on yet (ITL-1446)" + ) self._require_open() return { "connector_type": "spiraldb", diff --git a/src/orcapod/databases/spiraldb_store_tables.py b/src/orcapod/databases/spiraldb_store_tables.py new file mode 100644 index 000000000..303213446 --- /dev/null +++ b/src/orcapod/databases/spiraldb_store_tables.py @@ -0,0 +1,1223 @@ +"""The tables of a SpiralDB pipeline store, one dataset's (ITL-1840). + +What ``ConnectorArrowDatabase`` does with the tables of a ``SpiralDBConnector`` opened in +store mode (a private constructor argument: nothing about the store is public yet). The +design is ``docs/dev/specs/itl-1446-round2-spiral-sdk.md`` (PR 588), section 2, carried +from PR 595 onto ``main``'s database structure. + +- A table's name is computed from its full record path (``spiral_store_identity``); a + table is found by opening that name, never by listing. +- Its metadata holds its identity record and its manifest (``spiral_store``): the record + path, layout, data context, and the logical schema with the stored names. They are + written in one upsert before its first rows. +- A table under the name that records another path or format, or holds rows without a + record, is refused (``SpiralStoreTableCollisionError``). A table with no rows (a + creation that stopped before its first rows) is new to any first writer. +- Rows are encoded on write and decoded on read by the codec; a read gives the logical + columns, logical types live. +- Which of a set of record ids a table holds is answered by one read of the key column + alone and a set intersection (``existing_record_ids``): never by a range of ids, which + would rely on how the service orders binary values. +- A table's name is opened on every call (a table can be renamed and another made under + its name); what a table holding rows records is kept by its table id, and only once an + append to it succeeded or a read found its rows. +- The store's tables are listed by one listing of the dataset, narrowed by name, and the + metadata of each candidate (cached by table id): that is how stale layouts are found + (ITL-954). + +One writer at a time, and no lease yet (ITL-1452): a first write re-reads the table just +before recording it and never overwrites what that read shows, but without a +compare-and-set two concurrent writers can still race in between. +""" + +from __future__ import annotations + +import threading +from collections.abc import Callable, Collection, Iterator, Mapping +from contextlib import AbstractContextManager, contextmanager +from dataclasses import dataclass +from typing import Any, Protocol, cast + +import pyarrow as pa +import pyarrow.compute as pc + +import orcapod.databases.spiral_store as codec +import orcapod.databases.spiral_store_identity as identity +from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +from orcapod.databases.store_table_names import require_store_path_domain +from orcapod.errors import InputValidationError +from orcapod.logical_types.canonical_form import ( + EXTENSION_METADATA_KEY, + EXTENSION_NAME_KEY, + declaration_form_field, + storage_form_field, +) +from orcapod.logical_types.identifier import arrow_type_identifier +from orcapod.system_constants import constants +from orcapod.types import ColumnInfo + +DATA_CONTEXT_COLUMN = constants.DATA_CONTEXT_COL +"""The column every stored row's data context is in.""" + + +class _Scan(Protocol): + """The part of spiral-sdk's scan the store uses.""" + + def to_table(self) -> pa.Table: + """The rows the scan reads, as one Arrow table.""" + ... + + +class _KeyedTable(Protocol): + """The part of spiral-sdk's ``KeyedTable`` the store uses.""" + + @property + def resource_id(self) -> str: ... + + @property + def key_columns(self) -> tuple[str, ...]: ... + + def schema(self) -> pa.Schema: ... + + def get_metadata(self) -> dict[str, bytes]: + """The table's metadata entries, as stored.""" + ... + + def set_metadata(self, metadata: dict[str, bytes]) -> None: + """Record metadata entries (an upsert of the given keys).""" + ... + + def scan( + self, + columns: list[str] | None = None, + *, + filter: Any = None, # pyright: ignore[reportExplicitAny] # an SDK expression + limit: int | None = None, + ) -> _Scan: + """A read of the table's current snapshot: only ``columns`` when given (every + column otherwise), the rows ``filter`` keeps, at most ``limit`` rows.""" + ... + + def append(self, data: pa.Table) -> _KeyedTable: + """Write rows; a row whose key the table holds replaces that row. The returned + table is not used: the store opens the table by name again.""" + ... + + +@dataclass(frozen=True) +class _Found: + """A store table that holds rows, with what its metadata records. + + Attributes: + table_id: SpiralDB's id of the table. + record: Its identity record. + manifest: Its manifest. + """ + + table_id: str + record: identity.StoreTableRecord + manifest: codec.StoreManifest + + +@dataclass(frozen=True) +class _Opened: + """A store table found under its name now: what it records, and the snapshot it + was opened as (every read and write of the call goes through that snapshot). + + Attributes: + found: What the table records. + table: The snapshot opened under the name. + """ + + found: _Found + table: _KeyedTable + + +_Seen = tuple[str, object] +"""What a table recorded when judged: ``("none", None)``, ``("manifest", manifest)``, or +``("unreadable", header bytes)`` for a manifest that cannot be decoded (never equal to +anything: ``_same_seen``).""" + + +@dataclass(frozen=True) +class _New: + """A store table found under its name with no rows yet: new to any first writer. + + Attributes: + seen: What it recorded when it was judged (``_seen_manifest``): its first write + records it only as it was then. + record: The identity record it held when it was judged, if any: compared with + ``seen`` before the first write records over it. + """ + + seen: _Seen + record: identity.StoreTableRecord | None + + +_Judgment = _Opened | _New | None +"""What a name was judged: a table with rows, a table with none, or no table.""" + + +class StoreTables: + """The store tables of one SpiralDB dataset. + + Every keyed table is opened or created through the connector's callables, never + through the SDK client here: the connector owns every call that opens a keyed table + (spiral-sdk's keyed-table deprecation is ignored for its own calls only). + + Args: + sdk: The spiral-sdk module (its error class). + project_id: The project. + dataset: The dataset. + open_table: Opens a keyed table by name; ``None`` when there is none. + open_table_by_id: Opens a keyed table by its id. + create_table: Creates a keyed table in the dataset, by name and key schema. + list_tables: Lists the dataset's keyed tables: names by table id. + service_call: A context that notes on a failing SDK call what it was doing. + """ + + def __init__( + self, + sdk: Any, # pyright: ignore[reportExplicitAny] # the optional spiral-sdk module + project_id: str, + dataset: str, + open_table: Callable[[str], _KeyedTable | None], + open_table_by_id: Callable[[str], _KeyedTable], + create_table: Callable[[str, pa.Schema], object], + list_tables: Callable[[], dict[str, str]], + service_call: Callable[[str], AbstractContextManager[None]], + ) -> None: + self._sdk: Any = sdk # pyright: ignore[reportExplicitAny] + self._project_id: str = project_id + self._dataset: str = dataset + self._open_table: Callable[[str], _KeyedTable | None] = open_table + self._open_table_by_id: Callable[[str], _KeyedTable] = open_table_by_id + self._create_table: Callable[[str, pa.Schema], object] = create_table + self._list_tables: Callable[[], dict[str, str]] = list_tables + self._service_call: Callable[[str], AbstractContextManager[None]] = service_call + self._paths: dict[str, tuple[str, ...]] = {} + # What a table that holds rows records, by its id: a table's key, record and + # manifest never change once it holds rows. Which table a name opens is asked + # on every call (a table can be renamed, and another made under its name). + self._found_by_id: dict[str, _Found] = {} + # The record of a listed table that holds rows and the store format it names, + # by its id (a table that holds rows never loses them). + self._records_by_id: dict[str, tuple[identity.StoreTableRecord, str]] = {} + # Within one public operation (``operation``): what each name was judged, its + # name opened once and its handle reused. Empty outside an operation. + # Kept per thread: an operation is one thread's call, and no other operation + # can change what this one judged (a table with no rows stays one, and what it + # recorded stays what its first write compares with). + self._now: threading.local = threading.local() + + key_column: str = codec.KEY_COLUMN + """The key column of every store table.""" + + def unstorable_column_reason( + self, name: str, arrow_type: pa.DataType, primary_key: bool + ) -> str | None: + """Why the codec cannot keep a column. + + Args: + name: The column's name. + arrow_type: Its Arrow type. + primary_key: Whether it is the record id column. + + Returns: + The reason, or ``None`` when the codec keeps it. + """ + if primary_key: + if name == codec.KEY_COLUMN and pa.types.is_large_binary(arrow_type): + return None + return f"a store table's key is {codec.KEY_COLUMN!r}, large_binary" + key = pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False) + try: + _ = codec.logical_schema(pa.schema([pa.field(name, arrow_type), key])) + except codec.UnstorableInSpiralError as exc: + return str(exc) + return None + + def data_context(self, records: pa.Table) -> str: + """Return the one data context of rows to store (``_one_data_context``). + + Args: + records: The rows. + + Returns: + Their data context key. + + Raises: + ValueError: If the rows hold no data context column, a null or several + values in it. + InputValidationError: If the data context is not one this Orcapod has. + """ + return _one_data_context(records) + + def validate(self, records: pa.Table, table_name: str | None) -> None: + """Check rows to buffer: their one data context, the one the table at + ``table_name`` records when it holds rows, and the codec on the last row of each + key, as kept. + + Args: + records: The rows. + table_name: A name ``table_name`` returned, or ``None`` for no table in + particular. + + Raises: + ValueError: If the rows hold no data context column, a null or several + values in it. + InputValidationError: If the data context is not one this Orcapod has, + or not the table's. + UnstorableInSpiralError: If the codec refuses the rows. + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. + """ + if records.num_rows == 0: + return + context = _one_data_context(records) + if table_name is not None: + opened = self._judge(table_name) + if opened is not None: + _require_data_context(opened.found, context) + _ = codec.encode_rows(_last_of_each_key(records)) + + # ── names ──────────────────────────────────────────────────────────────── + + def table_name(self, path: tuple[str, ...]) -> str: + """Return the table name of a full record path, and remember the path. + + Args: + path: The full record path. + + Returns: + The table's name. + + Raises: + ValueError: If the path is how ``table_paths`` lists a table of another + store format (``identity.refuse_other_format_path``), or is outside the + store path domain (``store_table_names.require_store_path_domain``), + which the table's identity record and manifest apply too. + """ + identity.refuse_other_format_path(path) + components = require_store_path_domain(path) + name = identity.spiral_store_table_name(components) + self._paths[name] = components + return name + + def _path_of(self, table_name: str) -> tuple[str, ...]: + """The path a name was computed from (``table_name``).""" + path = self._paths.get(table_name) + if path is None: + raise KeyError( + f"{table_name!r} is not a name this store computed for a path" + ) + return path + + @contextmanager + def _about(self, table_name: str) -> Iterator[None]: + """Name the table on a refusal raised inside: a collision error is raised again + with the table, any other error gets a note naming it. + + Args: + table_name: The table's name in the dataset. + """ + try: + yield + except SpiralStoreTableCollisionError as exc: + if exc.table is not None: + raise + raise SpiralStoreTableCollisionError( + exc.reason, table=self._qualified(table_name) + ) from exc + except Exception as exc: + exc.add_note(f"SpiralDB store table {self._qualified(table_name)}") + raise + + # ── operations ─────────────────────────────────────────────────────────── + + @contextmanager + def operation(self) -> Iterator[None]: + """One public operation of ``ConnectorArrowDatabase`` (an add, a flush, a read): + each name is opened and judged once inside it, and that handle reused for + reads; a write always opens its name afresh. Operations nest; the handles are + forgotten when the outermost ends, so the next operation opens each name again + (a table can be renamed, and another made under its name, between them). Code + the store does not control runs ``outside_operation``. + """ + depth = cast(int, getattr(self._now, "depth", 0)) + if depth == 0: + self._now.judged = {} + self._now.depth = depth + 1 + try: + yield + finally: + self._now.depth = depth + if depth == 0: + self._now.judged = None + + @contextmanager + def outside_operation(self) -> Iterator[None]: + """Run code this store does not control (a caller's callback) outside the + current operation: a public call it makes opens every name afresh in an + operation of its own, and the enclosing operation forgets every handle it held + once the code returns, since that code may have renamed or replaced a table. + """ + depth = cast(int, getattr(self._now, "depth", 0)) + judged = self._judged_now() + self._now.depth = 0 + self._now.judged = None + try: + yield + finally: + self._now.depth = depth + self._now.judged = None if judged is None else {} + + def _judged_now(self) -> dict[str, _Judgment] | None: + """What each name was judged in this thread's operation; ``None`` outside one.""" + return cast("dict[str, _Judgment] | None", getattr(self._now, "judged", None)) + + def _forget_opened(self, table_name: str) -> None: + """Forget a name's handle in the current operation: this store writes to it.""" + judged = self._judged_now() + if judged is not None: + _ = judged.pop(table_name, None) + + # ── finding a table ────────────────────────────────────────────────────── + + def _judge(self, table_name: str) -> _Opened | None: + """Return the table under a name now if it holds rows of this path; ``None`` if + it is absent or new: no rows yet, with or without a record (spec 2.5: any first + writer records it again). ``_judgment`` tells the two apart. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The table and what it records, or ``None``. + """ + judgment = self._judgment(table_name) + return judgment if isinstance(judgment, _Opened) else None + + def _judgment(self, table_name: str) -> _Judgment: + """What the name holds now: a table with rows of this path, a table with none + (``_New``, with what it recorded), or no table (``None``). + + The name is opened once per public operation (``operation``; on every call + outside one), so a table renamed away, or replaced by another under the name, is + never read or written through an earlier operation's answer; what a table + holding rows records is read once per table id. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The judgment. + + Raises: + SpiralStoreTableCollisionError: If the table's key is not the store's, it + records another path or format, or it holds rows without a manifest. + """ + judged = self._judged_now() + if judged is not None and table_name in judged: + return judged[table_name] + with self._about(table_name): + judgment = self._judge_table(table_name, self._path_of(table_name)) + if judged is not None: + judged[table_name] = judgment + return judgment + + def _judge_table(self, table_name: str, path: tuple[str, ...]) -> _Judgment: + """``_judgment`` without naming the table on a refusal. + + Args: + table_name: A name ``table_name`` returned. + path: The full record path it was computed from. + + Returns: + The judgment. + """ + table = self._open_table(table_name) + if table is None: + return None + known = self._found_by_id.get(str(table.resource_id)) + if known is not None and known.record.path == path: + return _Opened(known, table) + _require_key(table, self._service_call) + with self._service_call("read the metadata of a store table"): + metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + if not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]): + # New: its first write records it, unless what it saw here changed. + return _New(_seen_manifest(metadata, path), record) + try: + manifest = None if record is None else codec.read_manifest(metadata, path) + except codec.ManifestError as exc: + raise SpiralStoreTableCollisionError(str(exc)) from exc + if record is None or manifest is None: + raise SpiralStoreTableCollisionError("it holds rows but no store manifest") + found = _Found(str(table.resource_id), record, manifest) + self._found_by_id[found.table_id] = found + return _Opened(found, table) + + def has_table(self, table_name: str) -> bool: + """Whether the store table at a computed name holds rows (and a manifest). + + Args: + table_name: A name ``table_name`` returned. + """ + return self._judge(table_name) is not None + + def _qualified(self, table_name: str) -> str: + """The table as ``"//"``.""" + return f"{self._project_id}/{self._dataset}/{table_name}" + + # ── listing ────────────────────────────────────────────────────────────── + + def table_paths( + self, prefix: tuple[str, ...], pending: Collection[tuple[str, ...]] + ) -> list[tuple[str, ...]]: + """Return the full paths of the store tables under ``prefix``, and of the + pending ones. + + One listing of the dataset; the names that start as a table under ``prefix`` + must; then the record of each candidate, read once per table id. A listed table + whose record is of a path with another name is refused, and so is a partial or + unreadable record. A table with no rows is not listed (a first write that + stopped after recording the table and before its rows leaves one); a pending + path is listed all the same. + + A table whose complete, readable record names another store format, with its + recorded path under ``prefix``, is listed as its recorded path with the last + component ``"/"`` + (``identity.other_format_last_component``): no layout and no store path has that + component, so the table is reported as one of another layout, and opening that + path is refused (``table_name``). Its name is not checked: another format may + name its tables otherwise. + + Args: + prefix: The full path prefix. + pending: The full paths of tables with rows not written yet. + + Returns: + The paths, sorted. + """ + start = identity.spiral_store_table_name_prefix(prefix) + found = {p for p in pending if p[: len(prefix)] == prefix} + with self._service_call("list the store tables"): + listed = self._list_tables() + for table_id, table_name in listed.items(): + if not table_name.startswith(start): + continue + with self._about(table_name): + read = self._record_of(table_id, table_name) + if read is None: + continue + record, store_format = read + if record.path[: len(prefix)] != prefix: + continue + if store_format == identity.STORE_FORMAT: + found.add(record.path) + else: + last = identity.other_format_last_component(record, store_format) + found.add((*record.path[:-1], last)) + return sorted(found) + + def _record_of( + self, table_id: str, table_name: str + ) -> tuple[identity.StoreTableRecord, str] | None: + """The record of a listed table and the store format it names, read once per + id; ``None`` without one, or when the table holds no rows. + + For this store's format, the name it is listed under now is checked against its + record on every call, the cached one included: a table renamed keeps its id. + Whether it holds rows is asked until it does. + + Args: + table_id: The listed table's id. + table_name: The name it is listed under. + """ + read = self._records_by_id.get(table_id) + table: _KeyedTable | None = None + if read is None: + table = self._open_table_by_id(table_id) + with self._service_call("read the metadata of a store table"): + metadata = table.get_metadata() + read = identity.read_store_table_record_of_any_format(metadata) + if read is None: + return None # never kept: its record may be written later + record, store_format = read + if ( + store_format == identity.STORE_FORMAT + and identity.spiral_store_table_name(record.path) != table_name + ): + raise SpiralStoreTableCollisionError( + f"it records path {list(record.path)}, whose table has another name" + ) + if table is not None: + # Another format's key column is its own: one row of every column. + columns = ( + [codec.KEY_COLUMN] if store_format == identity.STORE_FORMAT else None + ) + if not _holds_rows(table, self._service_call, columns): + return None # never kept: its rows may be written later + self._records_by_id[table_id] = read + return read + + # ── reading ────────────────────────────────────────────────────────────── + + def _require(self, table_name: str) -> _Found: + """What the table under a name records. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If no table under the name holds rows. + """ + opened = self._judge(table_name) + if opened is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + return opened.found + + def recorded_schema(self, table_name: str) -> pa.Schema: + """The logical schema the table's manifest records, exactly as recorded: a + logical type in its storage form with the identifier bytes it was written with. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If the table holds no rows. + """ + return self._require(table_name).manifest.schema + + def arrow_schema(self, table_name: str) -> pa.Schema: + """The schema rows of the table are read with: logical types live, field and + schema metadata as recorded. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If the table holds no rows. + """ + found = self._require(table_name) + return _live(found.manifest.schema, found.record.data_context_key) + + def column_info(self, table_name: str) -> list[ColumnInfo]: + """The table's columns, as ``arrow_schema`` gives them. + + Args: + table_name: A name ``table_name`` returned. + """ + return [ + ColumnInfo(name=f.name, arrow_type=f.type, nullable=f.nullable) + for f in self.arrow_schema(table_name) + ] + + def scan(self, table_name: str) -> Iterator[pa.RecordBatch]: + """Every row of the table, decoded; nothing for a table with no rows. + + Args: + table_name: A name ``table_name`` returned. + + Raises: + KeyError: If there is no table at the name. + """ + opened = self._judgment(table_name) + if opened is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + if isinstance(opened, _New): + return # it exists, with no rows + found = opened.found + schema = _live(found.manifest.schema, found.record.data_context_key) + with self._about(table_name), self._service_call("read a store table"): + stored = opened.table.scan().to_table() + if stored.num_rows == 0: + return + rows = codec.decode_rows(stored, found.manifest, schema) + yield from rows.to_batches() + + def existing_record_ids( + self, table_name: str, ids: Collection[bytes] + ) -> set[bytes]: + """Return the ids among ``ids`` the table at ``table_name`` holds. + + One read of the key column alone, and the intersection here. Never a range or + an ordering of the ids: how the service orders binary values is not measured, + and a range read in another order than the service's would miss stored ids (a + stored row would then be replaced). spiral-sdk 0.16.78 has no membership + expression, and an equality per id is one request per id or an expression as + long as the ids. Nothing for a table that is absent or holds no rows. + + Args: + table_name: A name ``table_name`` returned. + ids: Record ids. + + Returns: + The ids the table holds. + """ + if not ids: + return set() + opened = self._judge(table_name) + if opened is None: + return set() + with self._about(table_name): + return self._held_ids(opened.table, ids) + + def _held_ids(self, table: _KeyedTable, ids: Collection[bytes]) -> set[bytes]: + """The ids among ``ids`` a snapshot holds (``existing_record_ids``). + + Args: + table: The snapshot opened under the table's name. + ids: Record ids. + + Returns: + The ids it holds. + """ + with self._service_call("read the keys of a store table"): + stored = table.scan([codec.KEY_COLUMN]).to_table() + held = cast( + "list[bytes]", + stored.column(codec.KEY_COLUMN).cast(pa.large_binary()).to_pylist(), + ) + return set(ids).intersection(held) + + # ── writing ────────────────────────────────────────────────────────────── + + def _create_or_open(self, table_name: str) -> _KeyedTable: + """The table at a computed name, created now if absent. + + Args: + table_name: A name ``table_name`` returned. + + Returns: + The table, as opened under the name after any creation. + + Raises: + KeyError: If no table is under the name even after it was created. + """ + table = self._open_table(table_name) + if table is not None: + return table + key = pa.schema([pa.field(codec.KEY_COLUMN, pa.large_binary(), nullable=False)]) + try: + with self._service_call(f"create {table_name}"): + _ = self._create_table(table_name, key) + except self._sdk.SpiralError as exc: # pyright: ignore[reportAny] + if "status 409" not in str(exc): # pyright: ignore[reportAny] + raise + # Made meanwhile: the caller compares it with what it judged. + table = self._open_table(table_name) + if table is None: + raise KeyError(f"no store table {self._qualified(table_name)}") + return table + + def _unchanged_since_judged( + self, + table: _KeyedTable, + path: tuple[str, ...], + seen: _Seen, + seen_record: identity.StoreTableRecord | None, + ) -> bool: + """Whether a table opened to be recorded is still as it was judged new: the same + identity record (or none), an equivalent manifest (or none; compared by name, + never by order or bytes) and no rows. + + Read immediately before the manifest is written, so a record that read shows is + never overwritten. It narrows, and cannot close, the window in which two + writers race: spiral-sdk has no compare-and-set, so another writer can still + record the table between this read and the write. Concurrent writers are not + supported until the lease (ITL-1452). + + Args: + table: The table, opened under its name. + path: The full record path the name was computed from. + seen: What the table recorded when it was judged new. + seen_record: The identity record it held then, if any. + + Returns: + Whether it is unchanged. + + Raises: + SpiralStoreTableCollisionError: If the table's identity record, read with + the manifest, is of another path or cannot be read: an identity is + never recorded over. + """ + with self._service_call("read the metadata of a store table"): + metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + now = _seen_manifest(metadata, path) + return ( + record == seen_record + and _same_seen(now, seen) + and not _holds_rows(table, self._service_call, [codec.KEY_COLUMN]) + ) + + def _require_same_manifest( + self, table: _KeyedTable, path: tuple[str, ...], manifest: codec.StoreManifest + ) -> _Found: + """Refuse a table another writer recorded since it was judged, unless it records + the same manifest: another writer's record is never overwritten. + + Args: + table: The table, opened under its name. + path: The full record path the name was computed from. + manifest: The manifest this writer would record. + + Returns: + The table as it is recorded: its record and manifest stay, not this + writer's equivalent ones. + + Raises: + SpiralStoreTableCollisionError: If it records another path or manifest, or + holds rows without one. + """ + with self._service_call("read the metadata of a store table"): + metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + if record is not None: + identity.require_store_table_path(record, path) + try: + current = None if record is None else codec.read_manifest(metadata, path) + except codec.ManifestError as exc: + raise SpiralStoreTableCollisionError(str(exc)) from exc + if record is None or current is None or not _same_manifest(current, manifest): + raise SpiralStoreTableCollisionError( + "another writer recorded it since it was judged, with another manifest" + ) + return _Found(str(table.resource_id), record, current) + + def write(self, table_name: str, records: pa.Table) -> None: + """Write rows whose keys the table does not hold yet; the first write creates the + table and records its identity and manifest. Every check runs before anything is + created or written. A row the write's fresh key read shows is never overwritten: + ``ConnectorArrowDatabase`` refuses a stored id when the rows are added (unless + asked to skip it), and a key another writer stored before that read is left as + that writer stored it. A key another writer stores after that read can still be + replaced (SpiralDB's append replaces a row of the same key) until the one-writer + lease (ITL-1452). + + What a table records is kept only once an append to it succeeded; a write that + fails forgets it, so the next call judges the table again as the service has it + (also when the service stored the rows before the error reached this client). + + Args: + table_name: A name ``table_name`` returned. + records: The rows, record id column included. + + Raises: + ValueError: If the rows hold no ``__data_context`` column, or several data + contexts, their path cannot be recorded, or their columns are not the + table's. + UnstorableInSpiralError: If the codec refuses the rows. + InputValidationError: If their data context is not one this Orcapod has, + or not the one the table records (checked when they are buffered too). + SpiralStoreTableCollisionError: If the table under the name is not this + path's store table. + """ + path = self._path_of(table_name) + context = _one_data_context(records) + # Opened by name afresh at the write, never through a handle opened earlier in + # the operation: a caller's check may have run since (``outside_operation``), + # and another writer may have stored a key, or the table may have been renamed + # away and another made under its name. The keys are read from this snapshot. + self._forget_opened(table_name) + opened = self._judgment(table_name) + with self._about(table_name): + if not isinstance(opened, _Opened): + # Compared with what this write's own judgment saw, never with what + # another call judged since. + if isinstance(opened, _New): + seen, seen_record = opened.seen, opened.record + else: + seen, seen_record = ("none", None), None + self._write_first(table_name, path, context, records, seen, seen_record) + return + found = opened.found + _require_data_context(found, context) + difference = codec.schema_difference(found.manifest.schema, records.schema) + if difference is not None: + raise ValueError( + f"the rows are not of the table's schema ({difference}): " + + "schema evolution is not supported" + ) + difference = _stored_names_difference(found.manifest, records.schema) + if difference is not None: + # The codec writes the stored names its rule gives; the reader reads + # those the manifest records. Rows written under other names could not + # be read back, so they are never written. + raise ValueError( + f"the table stores its columns under other names ({difference}): " + + "an append would write columns its manifest does not record" + ) + # The keys are read again at every write, also for ids the add found + # absent: until the one-writer lease (ITL-1452), another writer may have + # stored one since, and an append would replace its row. + held = self._held_ids(opened.table, _ids(records)) + encoded = _encoded(_without_ids(records, held)) + if encoded.num_rows == 0: + return # a write of no rows is never sent + self._forget_opened(table_name) + self._append(opened.table, found, encoded) + + def _write_first( + self, + table_name: str, + path: tuple[str, ...], + context: str, + records: pa.Table, + seen: _Seen, + seen_record: identity.StoreTableRecord | None, + ) -> None: + """The first write of a table judged absent or new (``write``). + + Args: + table_name: A name ``table_name`` returned. + path: The full record path it was computed from. + context: The rows' data context. + records: The rows, record id column included. + seen: What the table recorded when this write judged it + (``_seen_manifest``; ``("none", None)`` when it was absent). + seen_record: The identity record it held then (``None`` when absent or + unrecorded): a changed record is never recorded over. + """ + manifest = codec.new_manifest(path, path[-1], records.schema) + metadata = { + **identity.store_table_metadata(path, context), + **codec.manifest_entries(manifest), + } + encoded = _encoded(records) + if encoded.num_rows == 0: + return # nothing to write, so nothing is created + self._forget_opened(table_name) + table = self._create_or_open(table_name) + _require_key(table, self._service_call) + if self._unchanged_since_judged(table, path, seen, seen_record): + with self._service_call("record a store table"): + table.set_metadata(metadata) + recorded = _Found( + str(table.resource_id), + identity.StoreTableRecord(path, path[-1], context), + manifest, + ) + else: + recorded = self._require_same_manifest(table, path, manifest) + _require_data_context(recorded, context) + # Another writer may have written these keys meanwhile. + held = self._held_ids(table, _ids(records)) + encoded = _encoded(_without_ids(records, held)) + if encoded.num_rows > 0: + self._append(table, recorded, encoded) + + def _append(self, table: _KeyedTable, found: _Found, encoded: pa.Table) -> None: + """Append encoded rows; keep what the table records only once that succeeded. + + Args: + table: The table, opened under its name. + found: What it records. + encoded: The rows, encoded. + """ + try: + with self._service_call("write a store table"): + _ = table.append(encoded) + except BaseException: + # The service may hold the rows, some, or none: judged again next call. + _ = self._found_by_id.pop(found.table_id, None) + raise + self._found_by_id[found.table_id] = found + + +def _stored_names_difference( + manifest: codec.StoreManifest, schema: pa.Schema +) -> str | None: + """Where the stored names ``codec.encode_rows`` gives rows of ``schema`` differ from + those ``manifest`` records, at any depth; ``None`` when they are the same. + + Columns are matched by logical name (their order never counts). A manifest records + the stored names it was written with, and the reader reads those; the codec always + applies its current rule. + + Args: + manifest: The table's manifest. + schema: The schema of rows to append, of the manifest's logical schema. + """ + written = dict( + zip(codec.logical_schema(schema).names, codec.physical_schema(schema)) + ) + for logical, recorded in zip(manifest.schema, manifest.physical): + field = written.get(logical.name) + if field is not None and _names_of(field) != _names_of(recorded): + return f"column {logical.name!r} is stored as {recorded}, not as {field}" + return None + + +def _names_of(field: pa.Field[Any]) -> tuple[object, ...]: + """A field's name and the names of its child fields, at every depth.""" + arrow_type = cast(Any, field.type) # pyright: ignore[reportExplicitAny] + children = [ + _names_of(cast("pa.Field[Any]", arrow_type.field(i))) + for i in range(cast(int, arrow_type.num_fields)) + ] + return (field.name, tuple(children)) + + +def _require_key( + table: _KeyedTable, service_call: Callable[[str], AbstractContextManager[None]] +) -> None: + """Refuse a table whose key is not the store's: ``__record_id``, binary. + + Args: + table: The table. + service_call: The store's ``service_call``. + + Raises: + SpiralStoreTableCollisionError: If its key is another. + """ + key_type = None + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + with service_call("read the schema of a store table"): + key_type = table.schema().field(codec.KEY_COLUMN).type + if key_type is not None and ( + pa.types.is_binary(key_type) or pa.types.is_large_binary(key_type) + ): + return + if tuple(table.key_columns) == (codec.KEY_COLUMN,): + raise SpiralStoreTableCollisionError( + f"its key {codec.KEY_COLUMN!r} is {key_type}, not binary" + ) + raise SpiralStoreTableCollisionError( + f"its key columns are {list(table.key_columns)}, not [{codec.KEY_COLUMN!r}]" + ) + + +def _holds_rows( + table: _KeyedTable, + service_call: Callable[[str], AbstractContextManager[None]], + columns: list[str] | None, +) -> bool: + """Whether a keyed table has a row. + + Args: + table: The table. + service_call: The store's ``service_call``. + columns: The columns of the one row read (``None`` for all of them). + """ + with service_call("read a key of a store table"): + keys = table.scan(columns, limit=1).to_table() + return keys.num_rows > 0 + + +def _ids(records: pa.Table) -> list[bytes]: + """The record ids of rows, in row order.""" + return cast("list[bytes]", records.column(codec.KEY_COLUMN).to_pylist()) + + +def _without_ids(records: pa.Table, held: set[bytes]) -> pa.Table: + """The rows whose id is not in ``held``.""" + if not held: + return records + return records.filter( + pc.invert( + pc.is_in( + records.column(codec.KEY_COLUMN), + pa.array(list(held), pa.large_binary()), + ) + ) + ) + + +def _last_of_each_key(records: pa.Table) -> pa.Table: + """The last row of each key, in row order (what ``ConnectorArrowDatabase`` keeps).""" + if codec.KEY_COLUMN not in records.column_names: + return records # refused by the codec, naming the key + keys = records.column(codec.KEY_COLUMN).to_pylist() + last = {key: i for i, key in enumerate(keys)} + if len(last) == len(keys): + return records + return records.take(pa.array(sorted(last.values()), pa.int64())) + + +def _encoded(records: pa.Table) -> pa.Table: + """The rows as written, or an empty table for no rows (never sent).""" + if records.num_rows == 0: + return records + return codec.encode_rows(records) + + +def _one_data_context(records: pa.Table) -> str: + """The one data context of rows to store (one per datagram, ITL-1359), a key this + Orcapod resolves: a table recording another could never be read back (its logical + types are made live with that context's converter, ``_live``). + + Raises: + ValueError: If there is no data context column, a null in it, or two values. + InputValidationError: If the key is not one of a data context this Orcapod + has (an unknown, a short or an empty key), naming it. + """ + if DATA_CONTEXT_COLUMN not in records.column_names: + raise ValueError( + f"a SpiralDB store keeps rows with a {DATA_CONTEXT_COLUMN!r} column only" + ) + values = cast( + "list[object]", pc.unique(records.column(DATA_CONTEXT_COLUMN)).to_pylist() + ) + if values == [""]: + raise InputValidationError( + "the rows' data context '' is not one this Orcapod has: a table recording " + "it could not be read" + ) + if len(values) != 1 or not isinstance(values[0], str): + raise ValueError( + f"rows of one write to a SpiralDB store hold one data context, not {values}" + ) + key = values[0] + from orcapod.contexts import resolve_context + from orcapod.contexts.core import ContextResolutionError + + try: + resolved = resolve_context(key).context_key + except ContextResolutionError as exc: + raise InputValidationError( + f"the rows' data context {key!r} is not one this Orcapod has: a table " + "recording it could not be read" + ) from exc + if resolved != key: + raise InputValidationError( + f"the rows' data context {key!r} is not a full data context key " + f"({resolved!r} is)" + ) + return key + + +def _require_data_context(found: _Found, context: str) -> None: + """Refuse rows of another data context than the table records: a table's logical + types are read back with its data context's type converter (``_live``). + + Raises: + InputValidationError: If ``context`` is not the table's, naming both keys + (``contexts.stored.require_same_data_context``). + """ + from orcapod.contexts.stored import require_same_data_context + + require_same_data_context(context, found.record.data_context_key) + + +def declared_keeping_identifier( + field: pa.Field[Any], + type_converter: Any, # pyright: ignore[reportExplicitAny] # a data context's converter +) -> pa.Field[Any]: + """The one declaration rule of a SpiralDB store: a field in the declaration form + (``declaration_form_field``) only when that keeps its identifier's bytes. + + A logical type in its storage form is made live when the live type the converter + resolves states exactly the identifier bytes recorded. A type the converter also + reads under other bytes (an older identifier) resolves to a live type stating the + current bytes: such a field stays in its storage form, so the bytes it was written + with are never replaced (ITL-1371). The same rule gives the rows to buffer and + flush, the schema a table reports and the schema its rows are decoded under, so a + table first written with an older identifier reads back and appends with it. + + Args: + field: A field, live or in its storage form. + type_converter: The type converter of the rows' data context. + + Returns: + The field, live or in its storage form. + + Raises: + LogicalTypeIdentifierError: If the field names a known logical type with + metadata or storage that type does not read, naming the column. + """ + declared = declaration_form_field(field, type_converter) + live = declared.type + if declared is field or not isinstance(live, pa.ExtensionType): + return declared + stored = storage_form_field(field) + metadata = stored.metadata or {} + given = ( + metadata.get(EXTENSION_NAME_KEY), + metadata.get(EXTENSION_METADATA_KEY, b""), + ) + identifier = arrow_type_identifier(live) + if (identifier.name.encode("utf-8"), identifier.metadata) != given: + return stored # another identifier the converter reads: kept as recorded + return declared + + +def declared_schema_keeping_identifier( + schema: pa.Schema, + type_converter: Any, # pyright: ignore[reportExplicitAny] # a data context's converter +) -> pa.Schema: + """``declared_keeping_identifier`` on every field; schema metadata kept. + + Args: + schema: A schema. + type_converter: The type converter of the rows' data context. + + Returns: + The schema; ``schema`` itself when nothing changes. + """ + fields = [declared_keeping_identifier(field, type_converter) for field in schema] + if all(new is old for new, old in zip(fields, schema)): + return schema + metadata = cast("dict[bytes | str, bytes | str] | None", schema.metadata) + return pa.schema(fields, metadata=metadata) + + +def _live(schema: pa.Schema, data_context: str) -> pa.Schema: + """A manifest's schema as its rows are read: logical types live where that keeps + the recorded identifier (``declared_keeping_identifier``), by the type converter of + the data context the table records.""" + from orcapod.contexts import resolve_context + + return declared_schema_keeping_identifier( + schema, resolve_context(data_context).type_converter + ) + + +def _same_manifest(one: codec.StoreManifest, other: codec.StoreManifest) -> bool: + """Whether two manifests record one table: the same path and kind, equivalent + logical schemas (``schema_difference``) and the same stored schema. Never by their + bytes, which differ for equivalent schemas represented differently.""" + return ( + one.record_path == other.record_path + and one.kind == other.kind + and codec.schema_difference(one.schema, other.schema) is None + and _by_name(one.physical) == _by_name(other.physical) + ) + + +def _by_name(schema: pa.Schema) -> dict[str, pa.Field[Any]]: + """A stored schema's fields by name: their order never counts.""" + return {field.name: field for field in schema} + + +def _seen_manifest(metadata: Mapping[str, bytes], path: tuple[str, ...]) -> _Seen: + """What a table's metadata records, to compare later (``_same_seen``).""" + try: + manifest = codec.read_manifest(metadata, path) + except codec.ManifestError: + return ("unreadable", metadata.get(codec.MANIFEST_KEY)) + return ("none", None) if manifest is None else ("manifest", manifest) + + +def _same_seen(one: _Seen, other: _Seen) -> bool: + """Whether two readings record the same: equivalent manifests compared by name. + + A manifest that cannot be decoded never equals anything, itself included (when in + doubt, refuse): the write then goes through ``_require_same_manifest``, which + refuses it.""" + if one[0] == "unreadable" or other[0] == "unreadable": + return False + if one[0] != other[0]: + return False + if one[0] == "manifest": + return _same_manifest( + cast(codec.StoreManifest, one[1]), cast(codec.StoreManifest, other[1]) + ) + return one[1] == other[1] diff --git a/tests/test_databases/test_fake_spiral_sdk.py b/tests/test_databases/test_fake_spiral_sdk.py index c572d95e8..0e9131d9a 100644 --- a/tests/test_databases/test_fake_spiral_sdk.py +++ b/tests/test_databases/test_fake_spiral_sdk.py @@ -64,5 +64,10 @@ def test_an_encoded_column_with_no_chunk_is_written_as_no_rows( ) rows = pa.Table.from_batches([], schema=schema) assert rows.column("v").num_chunks == 0 + writer = table.writer() + writer.append(rows) + (staged,) = writer._parts # pyright: ignore[reportPrivateUsage] + assert staged.num_rows == 0 + assert staged.schema.field("v").type == pa.string() # its values' type written = table.append(rows) assert written.scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_spiraldb_store_mode.py b/tests/test_databases/test_spiraldb_store_mode.py new file mode 100644 index 000000000..aa43dfc05 --- /dev/null +++ b/tests/test_databases/test_spiraldb_store_mode.py @@ -0,0 +1,2220 @@ +"""A SpiralDB connector in store mode, under ``ConnectorArrowDatabase`` (ITL-1840). + +On the fake (``fake_spiral_sdk``); no live SpiralDB. Store mode is private: a +``SpiralDBConnector`` built with ``_store=True``. The tests cover each table kind's +layout written and read back, the write rules of ITL-1386, refusals of tables that are +not the store's, the data-context checks and the listing the stale-layout check uses. +""" + +from __future__ import annotations + +import datetime as dt +import json +from collections.abc import Iterator +from pathlib import Path +from typing import Any, cast + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, function_pod +from orcapod.contexts.stored import ( + account_for_stale_tables, + find_stale_tables, + tables_of_another_layout, +) +from orcapod.core.operators import SelectDataColumns +from orcapod.core.sources.cached_source import CachedSource +from orcapod.databases import ConnectorArrowDatabase, SpiralDBConnector +from orcapod.databases import spiral_store as codec +from orcapod.databases import spiral_store_identity as identity +from orcapod.databases.spiral_store_identity import SpiralStoreTableCollisionError +from orcapod.databases.spiraldb_store_tables import StoreTables +from orcapod.errors import ( + InputValidationError, + OrcapodDatabaseReadError, + SideEffectLogDataContextError, + SpiralDBWriteNotSupportedError, +) +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.pipeline.observer import NoOpObserver +from orcapod.side_effects import SideEffectPod, sink_pod +from orcapod.sources import ArrowTableSource, DictSource +from orcapod.types import CacheMode +from tests.test_databases import fake_spiral_sdk as fake + +CONTEXT = "std:v1:default" +H = "0123456789abcdef" * 4 +RESULT = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +utc = dt.timezone.utc + + +@pytest.fixture +def root(tmp_path: Path) -> Iterator[Path]: + with fake.install(tmp_path): + yield tmp_path + + +def store(project: str = "p", dataset: str = "d") -> SpiralDBConnector: + return SpiralDBConnector(project, dataset, _store=True) + + +def tables_of(connector: SpiralDBConnector) -> StoreTables: + tables = connector._store_tables() # pyright: ignore[reportPrivateUsage] + assert tables is not None + return tables + + +def rows(ids: list[str], *, context: str = CONTEXT, offset: int = 0) -> pa.Table: + """Rows of a stored table: names the codec escapes, an instant, a struct.""" + n = len(ids) + return pa.table( + { + "__record_id": pa.array([i.encode() for i in ids], pa.large_binary()), + "__data_context": pa.array([context] * n, pa.large_string()), + "a.b": pa.array([offset + i for i in range(n)], pa.int64()), + "__pod_ts": pa.array( + [dt.datetime(2026, 1, 1, tzinfo=utc)] * n, pa.timestamp("us", tz="UTC") + ), + "s": pa.array([{"x": i} for i in range(n)], pa.struct([("x", pa.int8())])), + } + ) + + +def by_id(table: pa.Table) -> pa.Table: + return table.sort_by("__record_id") + + +def _client() -> Any: + return fake.FakeClient() + + +def _table(name: str) -> Any: + return _client().keyed_table("p", "d", name) + + +def _tables() -> list[dict[str, Any]]: + return fake.FakeClient()._store.tables() # pyright: ignore[reportPrivateUsage] + + +# ------------------------------------------------------------------ write and read + + +@pytest.mark.usefixtures("root") +def test_rows_round_trip() -> None: + db = ConnectorArrowDatabase(store()) + written = rows(["r1", "r0", "r2"]) + db.add_records(RESULT, written, record_id_column="__record_id") + assert db.table_exists(RESULT) # pending + db.flush() + assert db.table_exists(RESULT) + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + assert by_id(got).equals(by_id(written)) + one = db.get_record_by_id(RESULT, b"r2", record_id_column="__record_id") + assert one is not None and one.column("a.b").to_pylist() == [2] + some = db.get_records_by_ids(RESULT, [b"r2", b"r0"], record_id_column="__record_id") + assert some is not None and set(some["a.b"].to_pylist()) == {1, 2} + schema = db.get_table_schema(RESULT) + assert schema is not None and schema.names == written.schema.names + + +@pytest.mark.usefixtures("root") +def test_the_table_is_named_from_its_full_path_and_records_it() -> None: + db = ConnectorArrowDatabase(store()).at("team", "store") + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + db.flush() + full = ("team", "store", *RESULT) + table = _table(identity.spiral_store_table_name(full)) + metadata = table.get_metadata() + record = identity.read_store_table_metadata(metadata) + assert record == identity.StoreTableRecord(full, "rdb_v1", CONTEXT) + manifest = codec.read_manifest(metadata, full) + assert manifest is not None and "a.b" in manifest.schema.names + # the stored column names are the codec's, not Orcapod's + assert "a.b" not in table.schema().names + + +@pytest.mark.usefixtures("root") +def test_a_path_too_long_for_a_joined_name_is_stored() -> None: + long_path = ("f" * 300, H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") + db = ConnectorArrowDatabase(store()) + db.add_records(long_path, rows(["r0"]), record_id_column="__record_id") + db.flush() + assert len(identity.spiral_store_table_name(long_path)) <= 164 + assert db.list_table_paths(("f" * 300,)) == [long_path] + + +@pytest.mark.usefixtures("root") +def test_a_new_connector_reads_what_another_wrote() -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + fresh = ConnectorArrowDatabase(store()) + assert fresh.table_exists(RESULT) + got = fresh.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None and got.num_rows == 1 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["as_written", "reversed"]) +def test_rows_with_the_columns_in_another_order_append(order: str) -> None: + """Columns match by name: an append with the columns in any order is one table.""" + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + second = rows(["r1"], offset=10) + if order == "reversed": + second = second.select(list(reversed(second.column_names))) + db.add_records(RESULT, second, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 10, + } + assert got.schema.names == rows(["x"]).schema.names + + +# ------------------------------------------------- the write rules of ITL-1386 + + +@pytest.mark.usefixtures("root") +def test_a_stored_id_is_refused_without_buffering_other_rows() -> None: + """A write to a stored id raises unless ``skip_duplicates``; nothing of the add is + buffered.""" + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0", "r1"]), record_id_column="__record_id") + db.flush() + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_records( + RESULT, rows(["r9", "r1"], offset=100), record_id_column="__record_id" + ) + with pytest.raises(ValueError, match="already exist.*stored"): + db.add_record(RESULT, b"r0", rows(["r0"]).drop_columns(["__record_id"])) + db.flush() + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 1, + } + + +@pytest.mark.usefixtures("root") +def test_a_pending_id_is_refused_unless_skipped() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(ValueError, match="already exist in the pending batch"): + db.add_records(RESULT, rows(["r0"], offset=5), record_id_column="__record_id") + db.add_records( + RESULT, + rows(["r0", "r1"], offset=5), + record_id_column="__record_id", + skip_duplicates=True, + ) + db.flush() + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"r0": 0, + b"r1": 6, + } + + +@pytest.mark.usefixtures("root") +def test_skip_duplicates_keeps_stored_rows_and_writes_the_rest() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0", "r1"]), record_id_column="__record_id") + db.flush() + db.add_records(RESULT, rows(["r2"]), record_id_column="__record_id") + db.flush() + again = rows(["r1", "r3"], offset=100) + db.add_records(RESULT, again, record_id_column="__record_id", skip_duplicates=True) + db.flush() + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None + values = dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) + assert values == {b"r0": 0, b"r1": 1, b"r2": 0, b"r3": 101} + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_an_id_another_writer_stored_since_the_add_keeps_its_first_commit( + skip_duplicates: bool, +) -> None: + """Accepted when added, stored by another writer before this flush: the stored row + is kept (a SpiralDB append would replace it), the other keys are written.""" + a = ConnectorArrowDatabase(store()) + b = ConnectorArrowDatabase(store()) + b.add_records(RESULT, rows(["seed"]), record_id_column="__record_id", flush=True) + a.add_records( + RESULT, + rows(["x", "y"], offset=100), + record_id_column="__record_id", + skip_duplicates=skip_duplicates, + ) + b.add_records(RESULT, rows(["x"]), record_id_column="__record_id", flush=True) + a.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) == { + b"seed": 0, + b"x": 0, + b"y": 101, + } + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "asked", + [[b"r1", b"r3"], [b"r3", b"r1"], [b"a", b"r2", b"zz"], [b"q"], []], + ids=["two", "two reversed", "around the stored", "none stored", "empty"], +) +def test_stored_ids_are_answered_by_one_key_column_read(asked: list[bytes]) -> None: + """``existing_record_ids``: one scan of the key column alone, with no filter (no + range: how the service orders binary values is not relied on), and a set + intersection.""" + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records( + RESULT, rows(["r0", "r1", "r2", "r3"]), record_id_column="__record_id" + ) + db.flush() + tables = tables_of(connector) + name = tables.table_name(RESULT) + fake.scan_log.clear() + fake.count_log.clear() + held = tables.existing_record_ids(name, asked) + scans = [*fake.scan_log, *fake.count_log] + assert held == set(asked) & {b"r0", b"r1", b"r2", b"r3"} + keyed = [s for s in scans if s.limit is None] + assert len(keyed) == (1 if asked else 0) + assert all(s.filter is None for s in keyed), keyed + assert all(s.columns == ["__record_id"] for s in scans), scans + + +@pytest.mark.usefixtures("root") +def test_another_schema_is_refused() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + other = rows(["r1"]).append_column("more", pa.array([1])) + fresh = ConnectorArrowDatabase(store()) + with pytest.raises((ValueError, InputValidationError), match="(?i)schema|column"): + fresh.add_records(RESULT, other, record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_column_of_other_field_metadata_is_refused_on_append() -> None: + """Storage metadata must match on append (ITL-1334, ITL-1386).""" + db = ConnectorArrowDatabase(store()) + first = rows(["r0"]) + field = first.schema.field("a.b").with_metadata({"unit": "m"}) + first = first.set_column(2, field, first.column("a.b")) + db.add_records(RESULT, first, record_id_column="__record_id", flush=True) + second = rows(["r1"]) + other = second.schema.field("a.b").with_metadata({"unit": "s"}) + second = second.set_column(2, other, second.column("a.b")) + with pytest.raises(InputValidationError, match="a.b"): + ConnectorArrowDatabase(store()).add_records( + RESULT, second, record_id_column="__record_id" + ) + + +# ---------------------------------------------------------------- refusals + + +@pytest.mark.parametrize( + "bad", + [ + rows(["r0"]).drop_columns(["__data_context"]), + pa.concat_tables([rows(["r0"]), rows(["r1"], context="std:v2:other")]), + rows(["r0"]).set_column( + 4, "s", pa.array([None], pa.struct([("x", pa.int8())])) + ), + ], + ids=["no data context", "two data contexts", "a null struct"], +) +@pytest.mark.usefixtures("root") +def test_rows_the_store_cannot_keep_are_refused_before_anything_is_written( + bad: pa.Table, +) -> None: + db = ConnectorArrowDatabase(store()) + with pytest.raises((ValueError, codec.UnstorableInSpiralError)): + db.add_records(RESULT, bad, record_id_column="__record_id") + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_column_the_codec_cannot_keep_is_named_by_require_storable() -> None: + """A job attaching the database is refused before it runs, naming the column.""" + from orcapod.errors import UnstorableColumnError + + db = ConnectorArrowDatabase(store()) + with pytest.raises(UnstorableColumnError, match="d"): + db.require_storable(pa.schema([pa.field("d", pa.duration("s"))])) + db.require_storable(rows(["r0"]).schema) + + +def _make_table(name: str, metadata: dict[str, bytes], *, with_rows: bool) -> None: + key = pa.schema([pa.field("__record_id", pa.large_binary(), nullable=False)]) + table = _client().project("p").create_keyed_table("d", name, key) + if metadata: + table.set_metadata(metadata) + if with_rows: + _ = table.append( + pa.table( + { + "__record_id": pa.array([b"x"], pa.large_binary()), + "v": pa.array([1]), + } + ) + ) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_path_under_the_name_is_refused() -> None: + other = ("another", "rdb_v1") + _make_table( + identity.spiral_store_table_name(RESULT), + identity.store_table_metadata(other, CONTEXT), + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="another"): + _ = db.table_exists(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_foreign_table_with_rows_and_no_record_is_refused() -> None: + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="no store manifest"): + _ = db.table_exists(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + _ = db.get_all_records(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_without_a_record_is_adopted() -> None: + """A creation that stopped before the first write.""" + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(store()) + assert not db.table_exists(RESULT) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + got = db.get_all_records(RESULT, record_id_column="__record_id") + assert got is not None and got.num_rows == 1 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "key", + [ + pa.field("k", pa.large_string(), nullable=False), + pa.field("__record_id", pa.large_string(), nullable=False), + ], + ids=["another name", "another type"], +) +def test_an_empty_table_with_another_key_is_refused_untouched( + key: "pa.Field[Any]", +) -> None: + name = identity.spiral_store_table_name(RESULT) + _ = _client().project("p").create_keyed_table("d", name, pa.schema([key])) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="key"): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert _table(name).get_metadata() == {} + + +@pytest.mark.usefixtures("root") +def test_a_path_too_long_to_record_is_refused_before_any_table_is_made() -> None: + path = ("x" * 9000, "rdb_v1") + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="path|entry"): + db.add_records(path, rows(["r0"]), record_id_column="__record_id", flush=True) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_recorded_table_with_no_rows_is_new_to_any_first_writer() -> None: + """A first write that failed after its metadata leaves a table any first writer may + record again, with another schema too.""" + other = rows(["r0"]).drop_columns(["s"]) + manifest = codec.new_manifest(RESULT, "rdb_v1", other.schema) + _make_table( + identity.spiral_store_table_name(RESULT), + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(manifest), + }, + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + assert not db.table_exists(RESULT) + written = rows(["r0", "r1"]) + db.add_records(RESULT, written, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and by_id(got).equals(by_id(written)) + + +@pytest.mark.usefixtures("root") +def test_a_recorded_empty_table_with_a_corrupt_manifest_is_refused() -> None: + """Metadata that cannot be decoded never equals anything, so a table whose manifest + chunk is corrupt is never recorded over.""" + manifest = codec.new_manifest(RESULT, "rdb_v1", rows(["x"]).schema) + entries = codec.manifest_entries(manifest) + corrupt = { + **entries, + f"{codec.MANIFEST_KEY}/0": entries[f"{codec.MANIFEST_KEY}/0"] + b" ", + } + name = identity.spiral_store_table_name(RESULT) + _make_table( + name, + {**identity.store_table_metadata(RESULT, CONTEXT), **corrupt}, + with_rows=False, + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError): + db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id", flush=True) + assert ( + _table(name).get_metadata()[f"{codec.MANIFEST_KEY}/0"] + == corrupt[f"{codec.MANIFEST_KEY}/0"] + ) + + +# ------------------------------------------------------------- data contexts + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("context", ["std:v999:default", "v1", "not a key", ""]) +def test_a_data_context_this_orcapod_cannot_resolve_is_refused_before_anything( + context: str, +) -> None: + """A table recording a data context key no reader can resolve would be unreadable: + such rows (an unknown key, or a short one) are refused when they are added, before + they are buffered, and by a write that reaches the store directly, before any table + is created.""" + db = ConnectorArrowDatabase(store()) + with pytest.raises(InputValidationError, match="data context"): + db.add_records( + RESULT, rows(["r0"], context=context), record_id_column="__record_id" + ) + assert not db.table_exists(RESULT) + assert db.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") is None + db.flush() + tables = tables_of(store()) + name = tables.table_name(RESULT) + with pytest.raises(InputValidationError, match="data context"): + tables.write(name, rows(["r0"], context=context)) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_two_data_contexts_buffered_for_one_table_are_refused_before_it_is_made() -> ( + None +): + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(InputValidationError, match="data context"): + db.add_records( + RESULT, rows(["r1"], context="std:v2:other"), record_id_column="__record_id" + ) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_rows_of_another_data_context_are_refused_before_they_are_buffered() -> None: + """Rows of another data context than the table records are refused when they are + added (naming both keys), before they are buffered: a flush asked for with them + writes nothing, not even another table's pending batch.""" + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["old"]), record_id_column="__record_id", flush=True + ) + recorded = "std:v0:legacy" + _table(identity.spiral_store_table_name(RESULT)).set_metadata( + identity.store_table_metadata(RESULT, recorded) + ) + other = (*RESULT[:-1], "rdb_v9") + db = ConnectorArrowDatabase(store()) + db.add_records(other, rows(["valid"]), record_id_column="__record_id") + with pytest.raises(InputValidationError) as raised: + db.add_records( + RESULT, rows(["bad"]), record_id_column="__record_id", flush=True + ) + assert recorded in str(raised.value) and CONTEXT in str(raised.value) + assert not ConnectorArrowDatabase(store()).table_exists(other) + assert db.table_exists(other) + db.flush() + assert ConnectorArrowDatabase(store()).table_exists(other) + stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() + assert keys == [b"old"] + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_data_context_made_after_buffering_is_refused_at_flush() -> ( + None +): + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["mine"]), record_id_column="__record_id") + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["old"]), record_id_column="__record_id", flush=True + ) + recorded = "std:v0:legacy" + _table(identity.spiral_store_table_name(RESULT)).set_metadata( + identity.store_table_metadata(RESULT, recorded) + ) + with pytest.raises(InputValidationError) as raised: + db.flush() + assert recorded in str(raised.value) and CONTEXT in str(raised.value) + stored = _client().keyed_table("p", "d", identity.spiral_store_table_name(RESULT)) + keys = stored.scan(["__record_id"]).to_table()["__record_id"].to_pylist() + assert keys == [b"old"] + + +@pytest.mark.usefixtures("root") +def test_logical_types_are_read_with_the_data_context_the_table_records( + monkeypatch: pytest.MonkeyPatch, +) -> None: + import orcapod.contexts as contexts + + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + asked: list[object] = [] + real = contexts.resolve_context + + def resolve(context_info: Any = None) -> Any: + asked.append(context_info) + return real(context_info) + + monkeypatch.setattr(contexts, "resolve_context", resolve) + fresh = ConnectorArrowDatabase(store()) + assert fresh.get_all_records(RESULT, record_id_column="__record_id") is not None + assert CONTEXT in asked + + +# ------------------------------------------------------------- logical types + + +def _with_path_column(table: pa.Table, *, live: bool) -> pa.Table: + from pathlib import Path as PathValue + + from orcapod.contexts import get_default_context + from orcapod.logical_types.canonical_form import storage_form_schema + + converter = get_default_context().type_converter + paths = converter.python_dicts_to_arrow_table( + [{"p": PathValue(f"a/{i}")} for i in range(table.num_rows)], + python_schema={"p": PathValue}, + ) + if not live: + schema = storage_form_schema(paths.schema) + column: Any = paths.column("p").combine_chunks() # an extension array + paths = pa.Table.from_arrays([column.storage], schema=schema) + return table.append_column(paths.schema.field("p"), paths.column("p")) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_live", [True, False]) +def test_a_logical_type_live_or_in_storage_form_is_one_column(first_live: bool) -> None: + db = ConnectorArrowDatabase(store()) + first = _with_path_column(rows(["r0"]), live=first_live) + second = _with_path_column(rows(["r1"]), live=not first_live) + db.add_records(RESULT, first, record_id_column="__record_id", flush=True) + db.add_records(RESULT, second, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and got.num_rows == 2 + assert isinstance(got.schema.field("p").type, pa.BaseExtensionType) + + +@pytest.mark.usefixtures("root") +def test_a_storage_form_identifier_no_type_is_registered_for_is_kept_as_given() -> None: + field = pa.field( + "u", + pa.large_string(), + metadata={ + b"ARROW:extension:name": b"test.unregistered.kind", + b"ARROW:extension:metadata": b'{"version":1}', + }, + ) + table = rows(["r0"]).append_column(field, pa.array(["x"], pa.large_string())) + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, table, record_id_column="__record_id", flush=True) + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert got.schema.field("u").type == pa.large_string() + assert got.schema.field("u").metadata == field.metadata + assert got["u"].to_pylist() == ["x"] + + +# ---------------------------------------------------------------- listing + + +PATHS = [ + RESULT, + ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v0"), + ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2"), + ("my_fnx", H, "rdb_v1"), + ("side_effects", "Notify Pod", f"schema:{H}", "tdb_v2"), + ("my_op", H, "odb_v3"), + ("my", "cache", "sdb_v2"), +] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["forward", "reversed"]) +def test_tables_are_listed_by_their_recorded_paths(order: str) -> None: + db = ConnectorArrowDatabase(store()) + for path in PATHS if order == "forward" else list(reversed(PATHS)): + db.add_records(path, rows(["r0"]), record_id_column="__record_id") + db.flush() + db.add_records( + ("my_fn", "pending", "rdb_v1"), rows(["r0"]), record_id_column="__record_id" + ) + _make_table("someone_elses", {}, with_rows=True) + _make_table("o1_unmarked_" + "0" * 64, {}, with_rows=False) + assert db.list_table_paths() == sorted([*PATHS, ("my_fn", "pending", "rdb_v1")]) + assert db.list_table_paths(("my_fn",)) == sorted( + [p for p in PATHS if p[0] == "my_fn"] + [("my_fn", "pending", "rdb_v1")] + ) + assert db.list_table_paths(("side_effects", "Notify Pod")) == [PATHS[4]] + assert db.at("my_fn").list_table_paths((H,)) == sorted( + p[1:] for p in PATHS if p[:2] == ("my_fn", H) + ) + + +@pytest.mark.usefixtures("root") +def test_stale_layouts_are_found_by_their_recorded_paths() -> None: + """ITL-954: by the recorded path, never by a computed hash.""" + db = ConnectorArrowDatabase(store()) + for path in PATHS: + db.add_records(path, rows(["r0"]), record_id_column="__record_id") + db.flush() + # Under ("my_fn",): the current result and pipeline tables, and one of layout + # rdb_v0; ("my_fnx", ...) shares the name's beginning, not the path. + assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [ + PATHS[1] + ] + + +@pytest.mark.usefixtures("root") +def test_a_listed_table_recording_a_path_of_another_name_is_refused() -> None: + _make_table( + "o1_my_fn_" + "0" * 64, + identity.store_table_metadata(RESULT, CONTEXT), + with_rows=True, + ) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +OTHER_FORMAT = "orcapod.spiral_store.v1" +OTHER = ("my_fn", H, "v0", "python.function.v1", "rev1", "rdb_v1") +OTHER_LISTED = (*OTHER[:-1], f"rdb_v1/{OTHER_FORMAT}") + + +def _make_other_format_table(path: tuple[str, ...]) -> None: + """A table of another store format, its record complete and readable.""" + metadata = { + **identity.store_table_metadata(path, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + } + _make_table(identity.spiral_store_table_name(path), metadata, with_rows=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("order", ["current_first", "other_first"]) +def test_a_table_of_another_store_format_is_listed_with_a_marked_last_component( + order: str, +) -> None: + """Only that table is marked; the listing of the others goes on.""" + current = ("my_fn", H, "v0", "python.function.v1", f"schema:{H}", "pdb_v2") + outside = ("my_fnx", H, "rdb_v1") + db = ConnectorArrowDatabase(store()) + if order == "other_first": + _make_other_format_table(OTHER) + _make_other_format_table(outside) + db.add_records(current, rows(["r0"]), record_id_column="__record_id", flush=True) + if order == "current_first": + _make_other_format_table(OTHER) + _make_other_format_table(outside) + assert db.list_table_paths(("my_fn",)) == sorted([current, OTHER_LISTED]) + assert db.at("my_fn").list_table_paths((H,)) == sorted( + [current[1:], OTHER_LISTED[1:]] + ) + + +@pytest.mark.usefixtures("root") +def test_the_whole_store_lists_a_table_of_another_store_format() -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + db.add_records(PATHS[3], rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths() == sorted([OTHER_LISTED, PATHS[3]]) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_store_format_is_a_stale_table() -> None: + """A side-effect node refuses before acting; any other node reports and runs.""" + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + assert tables_of_another_layout(db, ("my_fn",), result_revision="rev1") == [ + OTHER_LISTED + ] + found = find_stale_tables(db, name_path=("my_fn",), result_revision="rev1") + assert [t.record_path for t in found.tables] == [OTHER_LISTED] + with pytest.raises(SideEffectLogDataContextError): + account_for_stale_tables( + found, delivers_side_effects=True, current_context=CONTEXT + ) + account_for_stale_tables( + found, delivers_side_effects=False, current_context=CONTEXT + ) + + +@pytest.mark.usefixtures("root") +def test_a_table_of_another_store_format_opened_by_its_path_is_refused() -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + with pytest.raises(SpiralStoreTableCollisionError, match="format"): + _ = db.table_exists(OTHER) + with pytest.raises(SpiralStoreTableCollisionError, match="format"): + db.add_records(OTHER, rows(["r0"]), record_id_column="__record_id", flush=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "open_", + [ + lambda db, path: db.table_exists(path), + lambda db, path: db.get_all_records(path), + lambda db, path: db.get_table_schema(path), + lambda db, path: db.add_records( + path, rows(["r0"]), record_id_column="__record_id" + ), + ], + ids=["table_exists", "get_all_records", "get_table_schema", "add_records"], +) +def test_a_listed_path_of_another_store_format_cannot_be_opened(open_: Any) -> None: + _make_other_format_table(OTHER) + db = ConnectorArrowDatabase(store()) + for listed in (db.list_table_paths(("my_fn",)), db.list_table_paths()): + assert listed == [OTHER_LISTED] + with pytest.raises(ValueError, match="another store format") as raised: + _ = open_(db, OTHER_LISTED) + assert OTHER_FORMAT in str(raised.value) + assert not isinstance(raised.value, SpiralStoreTableCollisionError) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "metadata", + [ + {identity.STORE_KEY: OTHER_FORMAT.encode()}, + { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + identity.PATH_KEY: b"[not json", + }, + { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: b"\xff\xfe", + }, + ], + ids=["partial", "unreadable_path", "undecodable_format"], +) +def test_a_doubtful_record_of_another_store_format_still_refuses_the_listing( + metadata: dict[str, bytes], +) -> None: + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +@pytest.mark.usefixtures("root") +def test_a_table_listed_before_its_record_is_listed_after_it() -> None: + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=False) + db = ConnectorArrowDatabase(store()) + assert db.list_table_paths(("my_fn",)) == [] + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths(("my_fn",)) == [RESULT] + + +def _rename(table_name: str, new_name: str) -> None: + """Rename a table in the fake, keeping its id (as the service does).""" + found = fake._store().find("p", "d", table_name) # pyright: ignore[reportPrivateUsage] + assert found is not None + found["name"] = new_name + root = fake._store().root # pyright: ignore[reportPrivateUsage] + (root / found["id"] / "table.json").write_text(json.dumps(found)) + + +@pytest.mark.usefixtures("root") +def test_a_listed_table_renamed_since_its_record_was_read_is_refused() -> None: + db = ConnectorArrowDatabase(store()) + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert db.list_table_paths(("my_fn",)) == [RESULT] + other = (*RESULT[:-1], "rdb_v9") + _rename( + identity.spiral_store_table_name(RESULT), + identity.spiral_store_table_name(other), + ) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = db.list_table_paths(("my_fn",)) + with pytest.raises(SpiralStoreTableCollisionError, match="another name"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +# ------------------------------------------------------ concurrent first writers + + +def _made_meanwhile(connector: SpiralDBConnector, make: Any) -> None: + """Run ``make`` (another party's act) just before ``connector`` creates or opens a + table for its first write.""" + tables = tables_of(connector) + create_or_open = tables._create_or_open # pyright: ignore[reportPrivateUsage] + + def other_first(table_name: str) -> Any: + make(table_name) + return create_or_open(table_name) + + tables._create_or_open = other_first # pyright: ignore[reportPrivateUsage] + + +def _interleaved(first_rows: pa.Table, second_rows: pa.Table) -> Any: + """Writer 1 judges the table absent; writer 2 then creates and fills it; then + writer 1 goes on. Returns writer 1's database.""" + first = store() + db1 = ConnectorArrowDatabase(first) + db1.add_records(RESULT, first_rows, record_id_column="__record_id") + + def the_other_writer(_: str) -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, second_rows, record_id_column="__record_id", flush=True + ) + + _made_meanwhile(first, the_other_writer) + return db1 + + +def _reordered(table: pa.Table) -> pa.Table: + return table.select(list(reversed(table.column_names))) + + +@pytest.mark.usefixtures("root") +def test_a_writer_never_overwrites_another_writers_manifest() -> None: + other_schema = rows(["b0"]).drop_columns(["s"]) + db1 = _interleaved(rows(["a0"]), other_schema) + with pytest.raises(SpiralStoreTableCollisionError): + db1.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None and by_id(got).equals(by_id(other_schema)) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("second", ["same", "metadata order", "column order"]) +def test_a_writer_of_an_equivalent_manifest_appends_beside_another( + second: str, +) -> None: + first = rows(["a0"]).replace_schema_metadata({"x": "1", "y": "2"}) + other = rows(["b0"]).replace_schema_metadata({"x": "1", "y": "2"}) + if second == "metadata order": + other = rows(["b0"]).replace_schema_metadata({"y": "2", "x": "1"}) + elif second == "column order": + other = _reordered(other) + db1 = _interleaved(first, other) + db1.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + assert set(got["__record_id"].to_pylist()) == {b"a0", b"b0"} + # The writer's own connector reads the columns as the table records them. + mine = db1.get_table_schema(RESULT) + fresh = ConnectorArrowDatabase(store()).get_table_schema(RESULT) + assert mine is not None and fresh is not None and mine.names == fresh.names + + +@pytest.mark.usefixtures("root") +def test_an_identity_of_another_path_made_meanwhile_is_never_recorded_over() -> None: + other = identity.store_table_metadata(("another", "rdb_v1"), CONTEXT) + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records(RESULT, rows(["a0"]), record_id_column="__record_id") + _made_meanwhile(connector, lambda name: _make_table(name, other, with_rows=False)) + with pytest.raises(SpiralStoreTableCollisionError, match="another"): + db.flush() + metadata = _table(identity.spiral_store_table_name(RESULT)).get_metadata() + assert identity.read_store_table_metadata( + metadata + ) == identity.read_store_table_metadata(other) + assert codec.MANIFEST_KEY not in metadata + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_a_first_writer_keeps_the_rows_another_writer_stored_meanwhile( + skip_duplicates: bool, +) -> None: + connector = store() + db = ConnectorArrowDatabase(connector) + db.add_records( + RESULT, + rows(["r1", "r9"], offset=100), + record_id_column="__record_id", + skip_duplicates=skip_duplicates, + ) + + def the_other_writer(_: str) -> None: + ConnectorArrowDatabase(store()).add_records( + RESULT, rows(["r1"]), record_id_column="__record_id", flush=True + ) + + _made_meanwhile(connector, the_other_writer) + db.flush() + got = ConnectorArrowDatabase(store()).get_all_records( + RESULT, record_id_column="__record_id" + ) + assert got is not None + values = dict(zip(got["__record_id"].to_pylist(), got["a.b"].to_pylist())) + assert values == {b"r1": 0, b"r9": 101} + + +# ------------------------------------------------------ private, plain, closed + + +@pytest.mark.usefixtures("root") +def test_a_store_mode_connector_is_not_saved() -> None: + with pytest.raises(ValueError, match="not saved"): + _ = store().to_config() + with pytest.raises(ValueError, match="not saved"): + _ = ConnectorArrowDatabase(store()).to_config() + + +@pytest.mark.usefixtures("root") +def test_raw_access_is_refused_in_store_mode() -> None: + connector = store() + for call in ( + lambda: connector.lookup_table("x"), + lambda: list(connector.scan_batches("x")), + lambda: list(connector.iter_batches('SELECT * FROM "x"')), + lambda: connector.get_table_names(), + lambda: connector.get_column_info("x"), + lambda: connector.get_arrow_schema("x"), + ): + with pytest.raises(ValueError, match="store-mode"): + _ = call() + for write in ( + lambda: connector.create_table_if_not_exists("x", [], "__record_id"), + lambda: connector.upsert_records("x", rows(["r0"]), "__record_id"), + lambda: connector.existing_record_ids("x", "__record_id", {b"r0"}), + lambda: connector.validate_records(rows(["r0"])), + ): + with pytest.raises(SpiralDBWriteNotSupportedError): + write() + + +@pytest.mark.usefixtures("root") +def test_a_plain_connector_still_writes_nothing() -> None: + """Main's behaviour: a database on a plain connector refuses every write.""" + db = ConnectorArrowDatabase(SpiralDBConnector("p", "d")) + with pytest.raises(SpiralDBWriteNotSupportedError): + db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + with pytest.raises(SpiralDBWriteNotSupportedError): + db.require_storable(rows(["r0"]).schema) + assert _tables() == [] + + +@pytest.mark.usefixtures("root") +def test_a_closed_store_connector_refuses_every_call_and_releases_its_tables() -> None: + connector = store() + db = ConnectorArrowDatabase(connector) + shared = connector.share_client() + connector.close() + assert connector._store is None # pyright: ignore[reportPrivateUsage] + for call in ( + lambda: db.table_exists(RESULT), + lambda: db.list_table_paths(), + lambda: db.add_records(RESULT, rows(["r0"]), record_id_column="__record_id"), + lambda: db.require_storable(rows(["r0"]).schema), + ): + with pytest.raises(RuntimeError, match="closed"): + _ = call() + # the connector sharing its client keeps its own reference + other = ConnectorArrowDatabase(shared) + other.add_records(RESULT, rows(["r0"]), record_id_column="__record_id", flush=True) + assert other.table_exists(RESULT) + + +@pytest.mark.usefixtures("root") +def test_an_existing_empty_table_is_read_as_no_rows() -> None: + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + with pytest.raises(KeyError): + _ = list(tables.scan(name)) + _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) + fresh = tables_of(store()) + assert fresh.table_name(RESULT) == name + assert not fresh.has_table(name) + assert list(fresh.scan(name)) == [] + assert ConnectorArrowDatabase(store()).get_all_records(RESULT) is None + + +# ------------------------------------------------- every table kind, end to end + +JOB = "itl1840" +SOURCE_ROWS = [{"k": "a", "x": 1}, {"k": "b", "x": 2}, {"k": "c", "x": 3}] +LAYOUTS = ("pdb_v2", "rdb_v1", "odb_v3", "sdb_v2", "tdb_v2") + +calls: list[int] = [] +delivered: list[int] = [] + + +@function_pod(output_keys="double") +def double(x: int) -> int: + calls.append(x) + return 2 * x + + +def _deliver(double: int, ctx: Any) -> None: + delivered.append(double) + + +def _job(database: ConnectorArrowDatabase, rows_given: list[dict[str, Any]]) -> Any: + """A function node, a logged operator node and a sink: four table kinds.""" + job = PipelineJob(name=JOB, database=database) + with job: + source = DictSource( + data=rows_given, tag_columns=["k"], tag_only_columns=True, source_id="src" + ) + out = double.pod(source, label="dbl") + SelectDataColumns(["double"])(out, label="sel") + sink = sink_pod(_deliver) + assert isinstance(sink, SideEffectPod) + sink.process(out, label="sink") + job.nodes["sel"].attach_databases( + pipeline_database=database.at(JOB), cache_mode=CacheMode.LOG + ) + return job + + +def _cached(database: ConnectorArrowDatabase) -> CachedSource: + table = pa.table({"k": ["a", "b"], "x": [1, 2]}) + return CachedSource( + ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="fixed" + ), + cache_database=database, + ) + + +@pytest.fixture +def _cleared() -> Iterator[None]: + calls.clear() + delivered.clear() + yield + calls.clear() + delivered.clear() + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_every_table_kind_is_written_and_read_back(orchestrator: str) -> None: + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + database = ConnectorArrowDatabase(store()) + _ = _job(database, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) + cached = _cached(database).as_table() + assert sorted(calls) == [1, 2, 3] and sorted(delivered) == [2, 4, 6] + + fresh = ConnectorArrowDatabase(store()) + paths = fresh.list_table_paths() + assert sorted(p[-1] for p in paths) == sorted(LAYOUTS) + for path in paths: + stored = fresh.get_all_records(path) + assert stored is not None and stored.num_rows > 0, path + assert set(stored.column("__data_context").to_pylist()) == {CONTEXT}, path + + # A second run in a fresh process reads what the first stored: no call, no delivery. + calls.clear() + delivered.clear() + again = _job(fresh, SOURCE_ROWS) + _ = again.run(orchestrator=run[orchestrator]()) + assert calls == [] and delivered == [] + assert sorted(again.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] + assert sorted(again.nodes["sel"].as_table()["double"].to_pylist()) == [2, 4, 6] + assert _cached(fresh).as_table().equals(cached) + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_new_input_adds_rows_to_every_table_and_keeps_the_others( + orchestrator: str, +) -> None: + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + database = ConnectorArrowDatabase(store()) + _ = _job(database, SOURCE_ROWS[:2]).run(orchestrator=run[orchestrator]()) + before = { + p: database.get_all_records(p, record_id_column="__rid") + for p in database.list_table_paths() + } + # Every table kind of the job is in the snapshot, the operator cache included: a + # kind missing here would never be compared below. + assert sorted(p[-1] for p in before) == sorted(k for k in LAYOUTS if k != "sdb_v2") + calls.clear() + delivered.clear() + fresh = ConnectorArrowDatabase(store()) + _ = _job(fresh, SOURCE_ROWS).run(orchestrator=run[orchestrator]()) + assert calls == [3] and delivered == [6] + for path, earlier in before.items(): + assert earlier is not None + now = fresh.get_all_records(path, record_id_column="__rid") + assert now is not None + kept = {r["__rid"]: r for r in now.to_pylist()} + for row in earlier.to_pylist(): + assert kept[row["__rid"]] == row, path + assert now.num_rows > earlier.num_rows, path + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize( + "component", + ["", "a/b", "a\0b", "\ud800"], + ids=["empty", "slash", "nul", "not utf-8"], +) +@pytest.mark.parametrize("where", ["record path", "base path"]) +def test_a_path_outside_the_store_path_domain_is_refused_before_anything( + component: str, where: str +) -> None: + """The store applies the one path domain its identity record and manifest apply + (``require_store_path_domain``), in the record path and in the base path alike.""" + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="component"): + if where == "record path": + db.add_records( + ("ok", component, "rdb_v1"), + rows(["r0"]), + record_id_column="__record_id", + ) + else: + db.at("base", component).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id" + ) + db.flush() + assert _tables() == [] + assert db.list_table_paths() == [] + + +# ------------------------------------------- review round 1 (PR 692): regressions + + +def _add(db: ConnectorArrowDatabase, data: pa.Table, **kwargs: Any) -> None: + db.add_records(RESULT, data, record_id_column="__record_id", **kwargs) + + +def _get(db: ConnectorArrowDatabase) -> pa.Table | None: + return db.get_all_records(RESULT, record_id_column="__record_id") + + +def _binary_ids(ids: list[bytes], *, offset: int = 0) -> pa.Table: + data = rows(["unused"] * len(ids), offset=offset) + return data.set_column(0, "__record_id", pa.array(ids, pa.large_binary())) + + +def _signed_byte_order(monkeypatch: pytest.MonkeyPatch) -> None: + """Make the fake compare binary values as signed bytes, not unsigned: a service + order the store must not rely on.""" + unsigned = fake._ordered # pyright: ignore[reportPrivateUsage] + + def ordered(value: Any) -> Any: + if isinstance(value, bytes): + return tuple(b if b < 128 else b - 256 for b in value) + return unsigned(value) + + monkeypatch.setattr(fake, "_ordered", ordered) + + +def _failing_append(monkeypatch: pytest.MonkeyPatch, *, after_commit: bool) -> None: + """Make every append fail: before the service stores anything, or after it stored + the rows (the error reaching the client only then).""" + append = fake.FakeKeyedTable.append + + def fail(self: Any, data: pa.Table) -> Any: + if after_commit: + _ = append(self, data) + raise fake.SpiralError("injected append failure") + + monkeypatch.setattr(fake.FakeKeyedTable, "append", fail) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("ids", [[b"\x00", b"\xff"], [b"\xff", b"\x00"]]) +@pytest.mark.parametrize("skip_duplicates", [False, True]) +def test_stored_ids_are_found_whatever_order_the_service_gives_binary_values( + monkeypatch: pytest.MonkeyPatch, ids: list[bytes], skip_duplicates: bool +) -> None: + """Finding 1: the existence check reads no range of ids, so a service that orders + binary values in another order than Python's never hides a stored id; no stored row + is replaced, strict or skipping duplicates, in either input order.""" + _signed_byte_order(monkeypatch) + db = ConnectorArrowDatabase(store()) + original = _binary_ids(ids) + _add(db, original, flush=True) + again = _binary_ids(ids, offset=100) + if skip_duplicates: + _add(db, again, skip_duplicates=True, flush=True) + else: + with pytest.raises(ValueError, match="already exist"): + _add(db, again) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(original)) + + +@pytest.mark.usefixtures("root") +def test_a_failed_first_append_leaves_no_table_known( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2: a first write whose append fails keeps nothing: the writer judges the + table again, as a fresh one does (recorded, no rows: new).""" + db = ConnectorArrowDatabase(store()) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["r0"]), flush=True) + fresh = ConnectorArrowDatabase(store()) + assert _get(db) is None and _get(fresh) is None + assert not db.table_exists(RESULT) and not fresh.table_exists(RESULT) + + +@pytest.mark.usefixtures("root") +def test_a_failed_first_append_lets_another_writer_record_the_table_anew( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2: after a failed first append, another writer records the empty table + with other columns; the first writer reads the table as that writer recorded it.""" + first = ConnectorArrowDatabase(store()) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(first, rows(["r0"]), flush=True) + second = ConnectorArrowDatabase(store()) + other = rows(["r1"]).rename_columns( + ["__record_id", "__data_context", "other", "__pod_ts", "s"] + ) + _add(second, other, flush=True) + for reader in (second, first): + got = _get(reader) + assert got is not None + assert by_id(got).equals(by_id(other), check_metadata=True) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_write", [True, False]) +def test_an_append_stored_before_its_error_reached_the_client_is_judged_again( + monkeypatch: pytest.MonkeyPatch, first_write: bool +) -> None: + """Finding 2: the service stored the rows, then the append raised. Nothing kept + from before the error is trusted: the rows are found, and are never stored + twice or replaced.""" + db = ConnectorArrowDatabase(store()) + if not first_write: + _add(db, rows(["r0"]), flush=True) + given = rows(["r1"], offset=10) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=True) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, given, flush=True) + expected = given if first_write else pa.concat_tables([rows(["r0"]), given]) + for reader in (db, ConnectorArrowDatabase(store())): + assert reader.table_exists(RESULT) + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(expected)) + with pytest.raises(ValueError, match="already exist"): + _add(ConnectorArrowDatabase(store()), rows(["r1"], offset=99)) + + +@pytest.mark.usefixtures("root") +def test_a_failed_append_to_a_table_with_rows_keeps_them( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 2, a later write: the stored rows stay, and the table is read again.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=False) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["r2"], offset=2), flush=True) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and by_id(got).equals(by_id(rows(["r0", "r1"]))) + + +OLDER = b'{"value_hash":"stored","version":0}' +"""Extension metadata of ``orcapod.path`` the tests make the type read too.""" + + +def _reads_an_older_identifier( + monkeypatch: pytest.MonkeyPatch, current: pa.Table, older: bytes +) -> None: + """Make ``orcapod.path`` read ``older`` beside the metadata ``current`` has.""" + from orcapod.contexts import get_default_context + + converter: Any = get_default_context().type_converter + path_type = converter.get_logical_type_by_arrow_extension_name("orcapod.path") + assert path_type is not None + recorded = (current.schema.field("p").metadata or {})[b"ARROW:extension:metadata"] + monkeypatch.setattr( + type(path_type), + "readable_extension_metadata", + lambda self: (recorded, older), # pyright: ignore[reportUnknownLambdaType] + ) + + +def _older_identifier(table: pa.Table, older: bytes) -> pa.Table: + """The table with its storage-form ``p`` column naming ``older`` metadata.""" + field = table.schema.field("p") + metadata: dict[bytes | str, bytes | str] = { + key: value for key, value in (field.metadata or {}).items() + } + metadata[b"ARROW:extension:metadata"] = older + position = table.schema.get_field_index("p") + return table.set_column(position, field.with_metadata(metadata), table.column("p")) + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("committed", [False, True]) +@pytest.mark.parametrize("first_live", [True, False]) +def test_an_identifier_the_reader_also_reads_is_still_another_identifier( + monkeypatch: pytest.MonkeyPatch, committed: bool, first_live: bool +) -> None: + """Finding 3: a logical type's identifier bytes are compared as given, before a + storage-form column is made live, against the pending batch and the manifest as + recorded (ITL-1371): one the type also reads (an older identifier) is refused, and + nothing of it is written.""" + first = _with_path_column(rows(["r0"]), live=first_live) + current = _with_path_column(rows(["r1"]), live=False) + _reads_an_older_identifier(monkeypatch, current, OLDER) + older = OLDER + db = ConnectorArrowDatabase(store()) + _add(db, first, flush=committed) + with pytest.raises(InputValidationError, match="'p'"): + _add(db, _older_identifier(current, older)) + db.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + + +@pytest.mark.usefixtures("root") +def test_an_older_identifier_found_only_at_flush_is_refused( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Finding 3, the flush side: rows buffered before another handle recorded the + table with other identifier bytes are compared with the manifest as recorded.""" + current = _with_path_column(rows(["r0"]), live=False) + _reads_an_older_identifier(monkeypatch, current, OLDER) + older = _older_identifier(_with_path_column(rows(["r1"]), live=False), OLDER) + buffered = ConnectorArrowDatabase(store()) + _add(buffered, older) + _add(ConnectorArrowDatabase(store()), current, flush=True) + with pytest.raises(InputValidationError, match="'p'"): + buffered.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("through", ["read", "write"]) +def test_a_table_renamed_away_is_never_used_through_its_earlier_name( + through: str, +) -> None: + """Finding 4: after the table is renamed and a foreign table made under its name, + the handle that knew it refuses the foreign table on read and on write, as a fresh + handle does: the name is resolved on every call.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + fake.FakeClient().project("p").create_keyed_table( + "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) + ) + with pytest.raises(SpiralStoreTableCollisionError): + _get(ConnectorArrowDatabase(store())) + db.refresh_table(RESULT) + with pytest.raises(SpiralStoreTableCollisionError): + if through == "read": + _get(db) + else: + _add(db, rows(["r1"]), flush=True) + + +@pytest.mark.usefixtures("root") +def test_a_table_replaced_under_its_name_is_read_as_the_replacement() -> None: + """Finding 4: what a table records is kept by its id, never by its name: another + store table of the same path made under the name is read as itself.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + _add(ConnectorArrowDatabase(store()), rows(["r5"], offset=5), flush=True) + got = _get(db) + assert got is not None and got.column("__record_id").to_pylist() == [b"r5"] + + +@pytest.mark.usefixtures("root") +def test_a_storage_form_column_is_resolved_under_the_rows_data_context( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Should fix: a write resolves a storage-form logical type under the rows' own + data context, as a read does, not the default one.""" + from dataclasses import replace + from types import SimpleNamespace + + from orcapod import contexts + + alternate_key = "std:v2:review" + default = contexts.get_default_context() + alternate = replace(default, context_key=alternate_key) + unaware = replace( + default, + type_converter=SimpleNamespace( + get_logical_type_by_arrow_extension_name=lambda name: None, # pyright: ignore[reportUnknownLambdaType] + register_logical_type_from_arrow_metadata=_raise_value_error, + ), + ) + resolve = contexts.resolve_context + first = _with_path_column(rows(["r0"], context=alternate_key), live=True) + second = _with_path_column(rows(["r1"], context=alternate_key), live=False) + monkeypatch.setattr(contexts, "get_default_context", lambda: unaware) + monkeypatch.setattr( + contexts, + "resolve_context", + lambda key=None: alternate if key == alternate_key else resolve(key), # pyright: ignore[reportUnknownLambdaType] + ) + db = ConnectorArrowDatabase(store()) + _add(db, first, flush=True) + _add(db, second, flush=True) + got = _get(db) + assert got is not None and got.num_rows == 2 + assert isinstance(got.schema.field("p").type, pa.BaseExtensionType) + + +def _raise_value_error(*args: Any) -> Any: + raise ValueError("no type registered") + + +@pytest.mark.usefixtures("root") +def test_the_table_schema_keeps_field_and_schema_metadata_across_a_flush() -> None: + """Should fix: ``get_table_schema`` of a stored table is the manifest's, field + metadata included, equal to the schema while the rows are queued.""" + db = ConnectorArrowDatabase(store()) + data = rows(["r0"]) + field = data.schema.field("a.b").with_metadata({b"unit": b"m"}) + data = data.set_column( + data.schema.get_field_index("a.b"), field, data["a.b"] + ).replace_schema_metadata({b"source": b"test", b"opaque": b"\xff"}) + _add(db, data) + queued = db.get_table_schema(RESULT) + db.flush() + for reader in (db, ConnectorArrowDatabase(store())): + stored = reader.get_table_schema(RESULT) + assert stored is not None and queued is not None + assert stored.equals(queued, check_metadata=True) + assert stored.field("a.b").metadata == {b"unit": b"m"} + assert stored.metadata == {b"source": b"test", b"opaque": b"\xff"} + rows_read = reader.get_all_records(RESULT) + assert rows_read is not None and rows_read.schema.metadata == stored.metadata + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("entry", ["run", "run_async"]) +def test_a_store_backed_job_holds_its_rows_and_reports_observer_losses( + entry: str, +) -> None: + """Should fix: a job on the store through both public entry points; a rerun holds + the rows it ran, and an observer's lost events are reported.""" + import asyncio + import warnings + + from tests.test_pipeline.test_observer_event_losses import ( + StatusObserver, + _database, # pyright: ignore[reportPrivateUsage] + ) + + database = ConnectorArrowDatabase(store()) + job = _job(database, SOURCE_ROWS) + + def run(**kwargs: Any) -> Any: + if entry == "run_async": + return asyncio.run(job.run_async(**kwargs)) + return job.run(**kwargs) + + with warnings.catch_warnings(record=True): + summary = run(observer=StatusObserver(_database())) + assert summary.ok and summary.lost_observer_events["status"].count > 0 + assert sorted(job.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4, 6] + calls.clear() + delivered.clear() + held = run() + assert held.nodes["dbl"].held == 3 + assert held.lost_observer_events == {} + assert calls == [] and delivered == [] + + +# ------------------------------------------- review round 2 (PR 692): regressions + + +def _record_ids(table: pa.Table) -> list[bytes]: + return cast("list[bytes]", table.column("__record_id").to_pylist()) + + +def _older_rows(ids: list[str]) -> pa.Table: + """Rows whose storage-form ``p`` column names the older identifier ``OLDER``.""" + return _older_identifier(_with_path_column(rows(ids), live=False), OLDER) + + +@pytest.fixture +def older_first(root: Path, monkeypatch: pytest.MonkeyPatch) -> ConnectorArrowDatabase: + """A table first written with an identifier ``orcapod.path`` also reads (older).""" + _reads_an_older_identifier( + monkeypatch, _with_path_column(rows(["r0"]), live=False), OLDER + ) + db = ConnectorArrowDatabase(store()) + _add(db, _older_rows(["r0"]), flush=True) + return db + + +def _p_identifier(schema: pa.Schema) -> bytes: + from orcapod.logical_types.canonical_form import storage_form_schema + + metadata = storage_form_schema(schema).field("p").metadata or {} + return metadata[b"ARROW:extension:metadata"] + + +def test_a_first_write_with_an_older_identifier_reads_back_with_it( + older_first: ConnectorArrowDatabase, +) -> None: + """Round 2, P1: a table first written with an older identifier the type reads is + read back, by the writer and a fresh handle, with the identifier bytes it was + written with (one declaration rule for the read and the write).""" + for reader in (older_first, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None and got.column("__record_id").to_pylist() == [b"r0"] + assert _p_identifier(got.schema) == OLDER + + +def test_the_schema_of_a_table_written_with_an_older_identifier_keeps_it( + older_first: ConnectorArrowDatabase, +) -> None: + """Round 2, P1: ``get_table_schema`` reports the identifier bytes as recorded, + never the current ones the type would state live.""" + for reader in (older_first, ConnectorArrowDatabase(store())): + schema = reader.get_table_schema(RESULT) + assert schema is not None and _p_identifier(schema) == OLDER + + +@pytest.mark.parametrize("fresh", [False, True]) +def test_rows_with_the_same_older_identifier_append( + older_first: ConnectorArrowDatabase, fresh: bool +) -> None: + """Round 2, P1: a later batch with the same older bytes is accepted at add and at + flush (the stored layout and the pending rows in one form), by the first writer + and by a fresh handle; the current identifier is still refused beside it.""" + db = ConnectorArrowDatabase(store()) if fresh else older_first + _add(db, _older_rows(["r1"]), flush=True) + with pytest.raises(InputValidationError, match="'p'"): + _add(db, _with_path_column(rows(["r2"]), live=False)) + for reader in (db, ConnectorArrowDatabase(store())): + got = _get(reader) + assert got is not None + assert sorted(_record_ids(got)) == [b"r0", b"r1"] + assert _p_identifier(got.schema) == OLDER + + +def _counted(monkeypatch: pytest.MonkeyPatch) -> dict[str, int]: + """Count the fake's name opens and full key reads.""" + counts = {"opens": 0, "key_reads": 0} + keyed_table = fake.FakeClient.keyed_table + scan = fake.FakeKeyedTable.scan + + def open_by_name(self: Any, *args: Any, **kwargs: Any) -> Any: + counts["opens"] += 1 + return keyed_table(self, *args, **kwargs) + + def counted_scan(self: Any, *args: Any, **kwargs: Any) -> Any: + if args and kwargs.get("limit") is None: + counts["key_reads"] += 1 + return scan(self, *args, **kwargs) + + monkeypatch.setattr(fake.FakeClient, "keyed_table", open_by_name) + monkeypatch.setattr(fake.FakeKeyedTable, "scan", counted_scan) + return counts + + +@pytest.mark.usefixtures("root") +def test_one_operation_opens_the_name_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: an add opens the table's name once and reads its keys once. The + flush that follows opens it once to check the rows and once more at the write, + after the caller's schema check, and reads the keys again from that last + snapshot (another writer may have stored one since: an append would replace its + row).""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + counts = _counted(monkeypatch) + _add(db, rows(["r2", "r3"], offset=2)) + assert counts == {"opens": 1, "key_reads": 1} + db.flush() + assert counts == {"opens": 3, "key_reads": 2} + _add(db, rows(["r3", "r4"], offset=3), skip_duplicates=True, flush=True) + assert counts == {"opens": 5, "key_reads": 3} + got = _get(db) + assert got is not None + assert sorted(_record_ids(got)) == [ + b"r0", + b"r1", + b"r2", + b"r3", + b"r4", + ] + + +@pytest.mark.usefixtures("root") +def test_ids_checked_by_two_handles_are_written_once( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: two databases on one connector both find an id absent; the first + flush writes it, and the second reads the keys again and keeps the first row, + never replacing it (the handle reused within an operation is never an earlier + operation's).""" + connector = store() + first, second = ConnectorArrowDatabase(connector), ConnectorArrowDatabase(connector) + _add(first, rows(["r0"]), flush=True) + _add(first, rows(["r1"], offset=1)) + _add(second, rows(["r1"], offset=50)) + first.flush() + second.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"r1": 1, + } + + +@pytest.mark.usefixtures("root") +def test_a_retry_after_a_failed_append_reads_the_keys_again( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Round 2, P2: after an append that stored its rows and then raised, a retry on + the same handle reads the keys again: the stored id is refused, or kept when + skipped.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + with monkeypatch.context() as patch: + _failing_append(patch, after_commit=True) + with pytest.raises(fake.SpiralError, match="injected append failure"): + _add(db, rows(["retry"], offset=10), flush=True) + with pytest.raises(ValueError, match="already exist"): + _add(db, rows(["retry"], offset=99)) + _add(db, rows(["retry", "new"], offset=99), skip_duplicates=True, flush=True) + got = _get(db) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"retry": 10, + b"new": 100, + } + + +def _replace_with_a_foreign_table() -> None: + """Rename the store table away and make a table of another key under its name.""" + name = identity.spiral_store_table_name(RESULT) + _rename(name, "renamed_away") + _ = ( + fake.FakeClient() + .project("p") + .create_keyed_table( + "d", name, pa.schema([pa.field("foreign", pa.int64(), nullable=False)]) + ) + ) + + +@pytest.mark.usefixtures("root") +def test_a_key_committed_during_the_schema_check_is_kept() -> None: + """Round 3, finding 1: another writer stores a key while the caller's schema check + runs; the flush reads the keys again after the check and keeps that writer's + row, never replacing it.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + peer = ConnectorArrowDatabase(store()) + _add(db, rows(["r1"], offset=90)) + + def commit_first(_schema: pa.Schema) -> None: + _add(peer, rows(["r1"], offset=10), flush=True) + + with db.guard_table_schema(RESULT, commit_first): + db.flush() + got = _get(peer) + assert got is not None + assert {r["__record_id"]: r["a.b"] for r in got.to_pylist()} == { + b"r0": 0, + b"r1": 10, + } + + +@pytest.mark.usefixtures("root") +def test_a_table_replaced_during_the_schema_check_is_refused() -> None: + """Round 3, finding 2: the table is renamed away and a foreign table made under + its name while the caller's schema check runs; the flush refuses the replacement + and never appends to the table renamed away.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + _add(db, rows(["r1"], offset=1)) + + def replace_table(_schema: pa.Schema) -> None: + _replace_with_a_foreign_table() + + with db.guard_table_schema(RESULT, replace_table): + with pytest.raises(SpiralStoreTableCollisionError): + db.flush() + old = fake.FakeClient().keyed_table("p", "d", "renamed_away") + assert old.scan().to_table().num_rows == 1 + + +@pytest.mark.usefixtures("root") +def test_a_read_inside_the_schema_check_looks_the_name_up_again() -> None: + """Round 3, finding 3: a public read made by the caller's schema check never + reuses the enclosing flush's handle: after the table is replaced it refuses the + replacement, as a read after the flush does.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + _add(db, rows(["r1"], offset=1)) + + def read_after_replacing(_schema: pa.Schema) -> None: + _replace_with_a_foreign_table() + with pytest.raises(SpiralStoreTableCollisionError): + _ = _get(db) + raise RuntimeError("stop before the write") + + with db.guard_table_schema(RESULT, read_after_replacing): + with pytest.raises(RuntimeError, match="stop before the write"): + db.flush() + with pytest.raises(SpiralStoreTableCollisionError): + _ = _get(db) + + +# ------------------------------------------------- review of 6fb1b6e16 + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("first_alternate", [False, True]) +def test_rows_of_another_data_context_than_the_pending_ones_are_refused_at_add( + monkeypatch: pytest.MonkeyPatch, first_alternate: bool +) -> None: + """Two data contexts this Orcapod resolves: rows of one buffered for a table, rows + of the other are refused when they are added, never buffered, and the flush + writes the first rows only (it used to fail at the flush, keeping both).""" + from dataclasses import replace + + from orcapod import contexts + + alternate_key = "std:v9:alternate" + alternate = replace(contexts.get_default_context(), context_key=alternate_key) + resolve = contexts.resolve_context + monkeypatch.setattr( + contexts, + "resolve_context", + lambda key=None: alternate if key == alternate_key else resolve(key), # pyright: ignore[reportUnknownLambdaType] + ) + first, second = CONTEXT, alternate_key + if first_alternate: + first, second = second, first + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"], context=first)) + with pytest.raises(InputValidationError) as raised: + _add(db, rows(["r2"], context=second, offset=2)) + assert first in str(raised.value) and second in str(raised.value) + db.flush() + got = _get(ConnectorArrowDatabase(store())) + assert got is not None + assert sorted(_record_ids(got)) == [b"r0", b"r1"] + assert set(got.column("__data_context").to_pylist()) == {first} + + +@pytest.mark.usefixtures("root") +def test_an_append_to_a_table_recording_other_stored_names_is_refused() -> None: + """A manifest records the stored names a table was written with, and the reader + reads those; the codec writes the names its rule gives. An append to a table + whose manifest records other names (another writer, or another rule) is refused + before anything is written: it used to write columns the manifest does not + record, and the next read failed.""" + written = rows(["r0"]) + ConnectorArrowDatabase(store()).add_records( + RESULT, written, record_id_column="__record_id", flush=True + ) + current = codec.new_manifest(RESULT, "rdb_v1", written.schema) + renamed = pa.schema( + [ + f.with_name(f"{f.name}_v0") if logical.name == "s" else f + for logical, f in zip(current.schema, current.physical) + ] + ) + other = codec.StoreManifest(RESULT, current.kind, current.schema, renamed) + name = identity.spiral_store_table_name(RESULT) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(other), + } + ) + db = ConnectorArrowDatabase(store()) + with pytest.raises(ValueError, match="other names") as raised: + _add(db, rows(["r1", "r2"], offset=1), flush=True) + assert "'s'" in str(raised.value) + stored = _table(name).scan().to_table() + assert stored.column("__record_id").to_pylist() == [b"r0"] + assert "s_v0" not in stored.column_names + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_judged_in_an_operation_stays_empty_after_another_writes() -> ( + None +): + """What a table was judged is kept by the operation that judged it: a table + judged empty is read as no rows in that operation even after another thread's + first write fills it (it used to raise ``KeyError``, as for no table).""" + import threading + + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + _make_table(name, identity.store_table_metadata(RESULT, CONTEXT), with_rows=False) + failures: list[BaseException] = [] + + def write_elsewhere() -> None: + try: + ConnectorArrowDatabase(connector).add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + except BaseException as exc: # noqa: BLE001 # reported by the test + failures.append(exc) + + with tables.operation(): + assert not tables.has_table(name) + writer = threading.Thread(target=write_elsewhere) + writer.start() + writer.join() + assert failures == [] + assert list(tables.scan(name)) == [] + got = _get(ConnectorArrowDatabase(store())) + assert got is not None and _record_ids(got) == [b"r0"] + + +@pytest.mark.usefixtures("root") +def test_a_first_writer_compares_the_table_with_its_own_observation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A first write compares the table with what its own judgment saw, never with + what another call judged since: another writer records the empty table with + another manifest and a second thread then judges it; the first write refuses it + and keeps that manifest (it used to take the second thread's judgment as its own + and record over it).""" + from concurrent.futures import ThreadPoolExecutor + + first_seen = rows(["x"]).drop_columns(["s"]) + _make_table( + identity.spiral_store_table_name(RESULT), + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries( + codec.new_manifest(RESULT, "rdb_v1", first_seen.schema) + ), + }, + with_rows=False, + ) + peers = rows(["x"]).drop_columns(["a.b"]) + peers_manifest = codec.new_manifest(RESULT, "rdb_v1", peers.schema) + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + new_manifest = codec.new_manifest + interfered: list[bool] = [] + + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + if not interfered: + interfered.append(True) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, CONTEXT), + **codec.manifest_entries(peers_manifest), + } + ) + # The peer's judgment must succeed: ``result()`` raises what it raised. + with ThreadPoolExecutor(max_workers=1) as peer: + assert peer.submit(tables.has_table, name).result() is False + return new_manifest(*args, **kwargs) + + monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) + with tables.operation(): + with pytest.raises(SpiralStoreTableCollisionError): + tables.write(name, rows(["a0"])) + assert interfered == [True] + kept = codec.read_manifest(_table(name).get_metadata(), RESULT) + assert kept is not None and kept.schema.equals(peers_manifest.schema) + assert _table(name).scan().to_table().num_rows == 0 + + +@pytest.mark.usefixtures("root") +def test_a_store_mode_add_flush_and_listing_raise_no_keyed_table_deprecation( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """spiral-sdk 0.16.79 and later warn on every keyed-table open and creation, + attributed to the module that calls the SDK (the fake warns the same way); Orcapod + ignores that warning for its connector's own calls only. So the store's creation, + opens by name and opens by id must all be the connector's: with every warning an + error, an add, a flush and a listing raise none (the store used to create a table + and open one by id itself, and raised). A direct call from elsewhere still warns.""" + import warnings + + from orcapod.databases import spiraldb_connector + + called: dict[str, int] = {} + + def spy(name: str) -> None: + original = getattr(spiraldb_connector, name) + + def call(*args: Any, **kwargs: Any) -> Any: + called[name] = called.get(name, 0) + 1 + return original(*args, **kwargs) + + monkeypatch.setattr(spiraldb_connector, name, call) + + spy("_open_keyed_table_by_id") + spy("_create_keyed_table") + with warnings.catch_warnings(): + warnings.simplefilter("error") + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0", "r1"]), flush=True) + _add(db, rows(["r2"], offset=2), flush=True) + assert ConnectorArrowDatabase(store()).list_table_paths() == [RESULT] + got = _get(db) + assert got is not None and sorted(_record_ids(got)) == [b"r0", b"r1", b"r2"] + with pytest.raises(DeprecationWarning, match="Keyed tables are deprecated"): + _ = _table(identity.spiral_store_table_name(RESULT)) + assert called.keys() == {"_open_keyed_table_by_id", "_create_keyed_table"} + + +class _CrashRecorder(NoOpObserver): + """Records every row an orchestrator reports as crashed.""" + + def __init__(self) -> None: + self.crashed: list[Exception] = [] + + def on_data_crash( + self, node_label: str, tag: Any, data: Any, error: Exception + ) -> None: + self.crashed.append(error) + + +@pytest.mark.usefixtures("root", "_cleared") +@pytest.mark.parametrize("orchestrator", ["sync", "async"]) +def test_a_stored_table_a_lookup_cannot_read_fails_a_continue_run( + orchestrator: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A read failure is the run's, never one row's, under ``error_policy="continue"``.""" + run = {"sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator} + + def build() -> Any: + job = PipelineJob(name=JOB, database=ConnectorArrowDatabase(store())) + with job: + source = DictSource( + data=SOURCE_ROWS, + tag_columns=["k"], + tag_only_columns=True, + source_id="src", + ) + _ = double.pod(source, label="dbl") + return job + + _ = build().run(orchestrator=run[orchestrator](error_policy="continue")) + calls.clear() + + def unreadable(self: StoreTables, table_name: str) -> Iterator[pa.RecordBatch]: + raise RuntimeError("the service could not read the table") + + monkeypatch.setattr(StoreTables, "scan", unreadable) + observer = _CrashRecorder() + with pytest.raises(OrcapodDatabaseReadError) as raised: + _ = build().run( + orchestrator=run[orchestrator](error_policy="continue"), observer=observer + ) + assert isinstance(raised.value.__cause__, RuntimeError) + assert observer.crashed == [] and calls == [] + + +@pytest.mark.usefixtures("root") +def test_a_table_left_empty_by_a_failed_first_write_is_not_listed( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Recorded, then its first append failed: no rows, so nothing stored there.""" + db = ConnectorArrowDatabase(store()) + + def failing(self: StoreTables, table: Any, found: Any, encoded: pa.Table) -> None: + raise RuntimeError("the append failed") + + with monkeypatch.context() as patched: + patched.setattr(StoreTables, "_append", failing) + with pytest.raises(Exception, match="the append failed"): + db.add_records( + RESULT, rows(["r0"]), record_id_column="__record_id", flush=True + ) + assert identity.spiral_store_table_name(RESULT) in [t["name"] for t in _tables()] + fresh = ConnectorArrowDatabase(store()) + assert fresh.list_table_paths(("my_fn",)) == [] + assert tables_of_another_layout(fresh, ("my_fn",), result_revision="rev1") == [] + # Pending rows are listed; once written, the table is listed by its rows. + fresh.add_records(RESULT, rows(["r0"]), record_id_column="__record_id") + assert fresh.list_table_paths(("my_fn",)) == [RESULT] + fresh.flush() + assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [RESULT] + + +@pytest.mark.usefixtures("root") +def test_an_empty_table_of_another_store_format_is_not_listed() -> None: + metadata = { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: OTHER_FORMAT.encode(), + } + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=False) + assert ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) == [] + + +@pytest.mark.usefixtures("root") +def test_the_commit_guard_is_given_the_recorded_schema_with_its_metadata() -> None: + """The schema check at the commit sees field metadata, as ``get_table_schema``.""" + + def with_metadata(table: pa.Table) -> pa.Table: + fields = [ + f.with_metadata({b"unit": b"mm"}) if f.name == "a.b" else f + for f in table.schema + ] + return table.cast(pa.schema(fields)) + + db = ConnectorArrowDatabase(store()) + _add(db, with_metadata(rows(["r0"])), flush=True) + _add(db, with_metadata(rows(["r1"], offset=1))) + seen: list[pa.Schema] = [] + with db.guard_table_schema(RESULT, seen.append): + db.flush() + assert len(seen) == 1 + assert seen[0].field("a.b").metadata == {b"unit": b"mm"} + recorded = db.get_table_schema(RESULT) + assert recorded is not None + assert seen[0].equals(recorded, check_metadata=True) + + +# ------------------------------------- review round 7 (PR 692): CodeRabbit, final head + + +@pytest.mark.usefixtures("root") +@pytest.mark.parametrize("lookup", ["by_id", "all"]) +def test_a_table_whose_metadata_cannot_be_read_fails_the_lookup_as_a_read_error( + lookup: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """Finding the table is a read too: a fresh reader whose metadata read fails + raises ``OrcapodDatabaseReadError``, as a failing scan does, never the service's + own error.""" + db = ConnectorArrowDatabase(store()) + _add(db, rows(["r0"]), flush=True) + + def unreadable(self: Any) -> dict[str, bytes]: + raise RuntimeError("the service could not read the metadata") + + monkeypatch.setattr(fake.FakeKeyedTable, "get_metadata", unreadable) + fresh = ConnectorArrowDatabase(store()) + with pytest.raises(OrcapodDatabaseReadError) as raised: + if lookup == "by_id": + _ = fresh.get_record_by_id(RESULT, b"r0", record_id_column="__record_id") + else: + _ = fresh.get_all_records(RESULT, record_id_column="__record_id") + assert isinstance(raised.value.__cause__, RuntimeError) + + +@pytest.mark.usefixtures("root") +def test_a_lookup_of_a_table_that_is_not_this_paths_still_raises_a_collision() -> None: + """A collision found while finding the table keeps its own type.""" + _make_table(identity.spiral_store_table_name(RESULT), {}, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError): + _ = ConnectorArrowDatabase(store()).get_all_records(RESULT) + + +@pytest.mark.usefixtures("root") +def test_a_record_with_an_empty_store_format_refuses_the_listing() -> None: + """An empty format is a malformed record, not another format to list.""" + metadata = { + **identity.store_table_metadata(OTHER, CONTEXT), + identity.STORE_KEY: b"", + } + _make_table(identity.spiral_store_table_name(OTHER), metadata, with_rows=True) + with pytest.raises(SpiralStoreTableCollisionError, match="no store format"): + _ = ConnectorArrowDatabase(store()).list_table_paths(("my_fn",)) + + +@pytest.mark.usefixtures("root") +def test_a_first_write_refuses_an_empty_table_recorded_meanwhile_under_another_context( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """An empty table judged with manifest M under context A, then recorded by another + writer with M under context B before the write: the write refuses it and keeps B's + record (it used to see the same manifest and record A over it).""" + other_context = "std:v1:other" + written = rows(["r0"]) + manifest_entries = codec.manifest_entries( + codec.new_manifest(RESULT, "rdb_v1", written.schema) + ) + _make_table( + identity.spiral_store_table_name(RESULT), + {**identity.store_table_metadata(RESULT, CONTEXT), **manifest_entries}, + with_rows=False, + ) + connector = store() + tables = tables_of(connector) + name = tables.table_name(RESULT) + new_manifest = codec.new_manifest + interfered: list[bool] = [] + + def recorded_meanwhile(*args: Any, **kwargs: Any) -> codec.StoreManifest: + if not interfered: + interfered.append(True) + _table(name).set_metadata( + { + **identity.store_table_metadata(RESULT, other_context), + **manifest_entries, + } + ) + return new_manifest(*args, **kwargs) + + monkeypatch.setattr(codec, "new_manifest", recorded_meanwhile) + with tables.operation(): + with pytest.raises(InputValidationError): + tables.write(name, written) + assert interfered == [True] + kept = identity.read_store_table_metadata(_table(name).get_metadata()) + assert kept is not None and kept.data_context_key == other_context + assert _table(name).scan().to_table().num_rows == 0 diff --git a/tests/test_databases/test_sqlite_connector_integration.py b/tests/test_databases/test_sqlite_connector_integration.py index a32332ddd..b90e9e2a0 100644 --- a/tests/test_databases/test_sqlite_connector_integration.py +++ b/tests/test_databases/test_sqlite_connector_integration.py @@ -11,7 +11,7 @@ from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector from orcapod.databases._sql_store import STORE_PATH_CATALOG -from orcapod.errors import OrcapodDatabaseError +from orcapod.errors import OrcapodDatabaseError, OrcapodDatabaseReadError from orcapod.protocols.db_connector_protocol import DBConnectorProtocol from orcapod.types import ColumnInfo @@ -539,3 +539,26 @@ def test_catalog_operation_helper_rejects_unknown_operation() -> None: pa.table({"value": [1]}), "flsuh", ) + + +@pytest.mark.parametrize("read", ["by_id", "all"]) +def test_a_stored_table_the_connector_cannot_read_raises_a_read_error( + read: str, monkeypatch: pytest.MonkeyPatch +) -> None: + """A failing read is ``OrcapodDatabaseReadError``, which fails a run (ITL-1840).""" + path = ("fn", "test") + with SQLiteConnector(":memory:") as connector: + db = ConnectorArrowDatabase(connector) + db.add_record(path, b"r1", pa.table({"x": [1]}), flush=True) + + def unreadable(query: str, params: object = None, batch_size: int = 1000): + raise sqlite3.OperationalError("disk I/O error") + + monkeypatch.setattr(connector, "iter_batches", unreadable) + with pytest.raises(OrcapodDatabaseReadError) as raised: + if read == "by_id": + _ = db.get_record_by_id(path, b"r1") + else: + _ = db.get_all_records(path) + assert raised.value.record_path == path + assert isinstance(raised.value.__cause__, sqlite3.OperationalError)