diff --git a/changelog.d/ITL-1446.md b/changelog.d/ITL-1446.md new file mode 100644 index 000000000..8f3fe85b1 --- /dev/null +++ b/changelog.d/ITL-1446.md @@ -0,0 +1,3 @@ +### Fixed + +- SpiralDB reports table names longer than 255 characters and rejects fixed-size binary, duration, and NUL-containing column names before writing rows. diff --git a/docs/dev/design_issues/ITL-1162-CA3.md b/docs/dev/design_issues/ITL-1162-CA3.md index 73e1c1ee6..754204545 100644 --- a/docs/dev/design_issues/ITL-1162-CA3.md +++ b/docs/dev/design_issues/ITL-1162-CA3.md @@ -35,6 +35,9 @@ ruling, November 16, 2026). `PostgreSQLConnector` also states which table names (`UnstorableTableNameError`). The connectors' silent TEXT fallback in `CREATE TABLE` now raises. +ITL-1446 extends SpiralDB's refusal to table names over the measured limit of 255 +characters, fixed-size binary and duration columns, and column names containing NUL. + **Open (the real fix, a later release):** store list and struct columns (for example as JSON text read back as the same Arrow type) and timestamps on SQLite, and rename SpiralDB's reserved column names on write and recover them on read, and restore a timestamp's time diff --git a/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md b/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md new file mode 100644 index 000000000..d08a703e5 --- /dev/null +++ b/docs/dev/plans/2026-11-24-itl-1446-strict-fake.md @@ -0,0 +1,25 @@ +# ITL-1446 PR 1 SpiralDB client and service behavior + +Offline `spiral.core.table.spec.Schema.from_arrow` in pyspiral 0.16.33 rejects fixed-size +binary, duration, union, and interval. Fixed-size binary and duration also fail inside +containers. The installed native library carries the writer diagnostics for value names +starting with `$`, key-only writes, and duplicate keys in an input batch. It separately +diagnoses a key schema that contains a Null type field. + +The ITL-1446 service verification confirmed refusal of fixed-size binary, duration, +interval, empty structs, and null struct values both at the top level and in a struct field. +The service sorts the immediate fields of a top-level struct column by name. An absent +key requested with `Scan.to_table(key_table=...)` leaves an all-null output row in its +slot. A zero-row write panics in the client, so the fake raises an ordinary exception. +The service truncates a column name at its first NUL. The fake and connector refuse +such a name before writing. + +The installed client's `spiral.api.types.TableName` annotation imposes a 128-character +ASCII identifier constraint, but the actual create path accepted table names at 128, +129, and 255 characters and rejected 256. The connector and fake enforce the measured +limit on the table part. The service also keeps untyped Arrow `null` value columns, as +the offline schema conversion does. The database matrix measures their round trip +through the connector. + +Duplicate detection across input batches, restrictions on other characters in the table +part of a name, and sorting struct fields inside other containers remain unverified. diff --git a/docs/reference/database-types.md b/docs/reference/database-types.md index c7dd0063e..0914d2117 100644 --- a/docs/reference/database-types.md +++ b/docs/reference/database-types.md @@ -205,10 +205,10 @@ fields is not covered: a struct whose fields are in another order is another typ | `timestamp[ms, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | | `timestamp[us, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | | `timestamp[ns, tz=Europe/Berlin]` | kept | kept (recorded type) | refused | refused | refused | -| `duration[s]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ms]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[us]` | kept | kept (recorded type) | refused | refused | kept | -| `duration[ns]` | kept | kept (recorded type) | refused | refused | kept | +| `duration[s]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[ms]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[us]` | kept | kept (recorded type) | refused | refused | refused | +| `duration[ns]` | kept | kept (recorded type) | refused | refused | refused | ## String and binary @@ -218,7 +218,7 @@ fields is not covered: a struct whose fields are in another order is another typ | `large_string` | kept | kept | kept | kept (by rule) | kept | | `binary` | kept | kept | kept | kept (by rule) | kept | | `large_binary` | kept | kept | kept | kept (by rule) | kept | -| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | kept | +| `fixed_size_binary[4]` | kept | kept (recorded type) | refused | refused | refused | ## List diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index be80d8919..746ec71c5 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -44,6 +44,8 @@ NullabilityRecordError, NullabilityRecordMismatchError, NullInNonNullableColumnError, + UnstorableColumnError, + UnstorableTableNameError, UnsupportedValueError, ) from orcapod.types import ColumnInfo @@ -59,6 +61,8 @@ logger = logging.getLogger(__name__) _ARROW_METADATA_KEY = "__arrow_metadata__" +# ITL-1446 service probe: 255 characters accepted, 256 refused. +_TABLE_NAME_MAX_LENGTH = 255 def _serialize_field_meta_tree(field: pa.Field) -> dict | None: @@ -379,6 +383,20 @@ def _about_table(table: str) -> Iterator[None]: # --------------------------------------------------------------------------- +def _fixed_binary_or_duration_reason(arrow_type: pa.DataType) -> str | None: + """Find a fixed-size binary or duration type refused by pyspiral's schema converter.""" + # Both fail in pyspiral 0.16.33's Schema.from_arrow, including inside containers. + if pa.types.is_fixed_size_binary(arrow_type) or pa.types.is_duration(arrow_type): + return f"pyspiral does not support the Arrow type {arrow_type}" + if pa.types.is_dictionary(arrow_type): + return _fixed_binary_or_duration_reason(arrow_type.value_type) + for index in range(arrow_type.num_fields): + reason = _fixed_binary_or_duration_reason(arrow_type.field(index).type) + if reason is not None: + return reason + return None + + def _holds_zone_aware_timestamp(arrow_type: pa.DataType) -> bool: """Whether ``arrow_type`` is or nests a timestamp with a time zone (ITL-1162). @@ -575,8 +593,28 @@ def share_client(self) -> SpiralDBConnector: def _table_id(self, table_name: str) -> str: """Return the dataset-qualified table identifier for a plain table name.""" + reason = self.unstorable_table_name_reason(table_name) + if reason is not None: + raise UnstorableTableNameError( + database_kind=type(self).__name__, table_name=table_name, reason=reason + ) return f"{self._dataset}.{table_name}" + def _require_supported_column(self, column: str, arrow_type: pa.DataType) -> None: + """Reject a column the connector cannot write without loss.""" + reason = ( + "SpiralDB truncates a column name at NUL" + if "\0" in column + else _fixed_binary_or_duration_reason(arrow_type) + ) + if reason is not None: + raise UnstorableColumnError( + database_kind=type(self).__name__, + column=column, + arrow_type=arrow_type, + reason=reason, + ) + def _qualified(self, table_name: str) -> str: """Return ``"//"``, the table as errors name it.""" return f"{self._project_id}/{self._dataset}/{table_name}" @@ -605,7 +643,6 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: The table: its id and key columns, and its schema and version when asked. """ self._require_open() - identifier = self._table_id(table_name) if ( not self._dataset or not table_name @@ -614,8 +651,9 @@ def lookup_table(self, table_name: str) -> SpiralDBTable: ): # The SDK omits empty filters and treats dots as identifier separators. raise SpiralDBTableNotFoundError( - f"Table not found: {self._project_id}.{identifier}" + f"Table not found: {self._project_id}.{self._dataset}.{table_name}" ) + identifier = self._table_id(table_name) try: table = self._project.table(identifier) except ValueError as exc: @@ -912,8 +950,9 @@ def delete_table(self, table_name: str) -> None: if the table does not exist. """ self._require_open() + identifier = self._table_id(table_name) if table_name in self.get_table_names(): - self._project.drop_table(self._table_id(table_name)) + self._project.drop_table(identifier) def create_table_if_not_exists( self, @@ -924,9 +963,9 @@ def create_table_if_not_exists( """Create a SpiralDB table with a single-column key schema, idempotently. Only the primary-key column's type is registered with Spiral at creation - time (via ``key_schema``). Non-PK columns in ``columns`` are ignored — - Spiral infers value column schemas from the first write. A second call - with the same table name is a no-op (``exist_ok=True``). + time (via ``key_schema``). The connector checks the other columns for + unsupported physical types. Spiral infers their schemas from the first + write. A second call with the same table name is a no-op (``exist_ok=True``). Only single-column primary keys are supported via this method. Tables with composite primary keys must be created outside this connector but @@ -934,8 +973,7 @@ def create_table_if_not_exists( Args: table_name: Plain table name (no dataset prefix). - columns: Full column list; must include ``pk_column``. Non-PK entries - are accepted but not used at creation time. + columns: Full column list; must include ``pk_column``. pk_column: Name of the single primary-key column. Raises: @@ -943,14 +981,17 @@ def create_table_if_not_exists( when ``columns`` is empty). """ self._require_open() + identifier = self._table_id(table_name) col_names = [c.name for c in columns] if pk_column not in col_names: raise ValueError( f"pk_column {pk_column!r} not found in columns: {col_names}" ) pk_arrow_type = next(c.arrow_type for c in columns if c.name == pk_column) + for column in columns: + self._require_supported_column(column.name, column.arrow_type) self._project.create_table( - self._table_id(table_name), + identifier, key_schema=[(pk_column, pk_arrow_type)], exist_ok=True, ) @@ -1004,12 +1045,6 @@ def upsert_records( ``write_nullability_record`` after checking the data holds no null in the non-nullable columns. - Limitation: "no value columns yet" stands for "no rows yet", which saves a scan - on every first write. A table whose columns are all key columns, holding rows - and no record, is recorded by the next write; if that write adds value columns - declared non-nullable, the earlier rows hold nulls there and every read raises - ``NullInNonNullableColumnError`` (a null is never hidden). - Raises: ValueError: If ``id_column`` is not in the table key schema (including empty key schema), or if any key-schema column is absent from @@ -1043,6 +1078,8 @@ def upsert_records( f"records is missing key column(s) {missing} required by the " f"table key schema {pk_cols}." ) + for field in records.schema: + self._require_supported_column(field.name, field.type) # Nullability (ITL-936). SpiralDB keeps no non-null flag except on list items, and # stores a null written to a non-null struct field as the type's zero, so every @@ -1066,8 +1103,7 @@ def upsert_records( [render_path(p) for p in sorted(paths - recorded)], table=qualified, ) - # A table with no value columns yet holds no rows Orcapod did not record (but see - # the limitation in the docstring: a table whose columns are all keys may). + # A table with no value columns yet holds no rows: pyspiral refuses key-only writes. record_first = recorded is None and set(tbl.schema().to_arrow().names) <= set( pk_cols ) @@ -1173,7 +1209,8 @@ def unstorable_column_reason( class, ``set[int]``, a NumPy array) would read back as its storage type and is refused (ITL-1334; keeping it is a follow-up). A map whose key or item field has another name than ``key`` / ``value`` reads back with those names, - and is refused too. + and is refused too. The pyspiral schema converter refuses fixed-size + binary and duration, including inside containers. Args: name: The column's name. @@ -1183,6 +1220,8 @@ def unstorable_column_reason( Returns: A short reason, or ``None`` when SpiralDB stores the column. """ + if "\0" in name: + return "SpiralDB truncates a column name at NUL" if "." in name: return "SpiralDB reserves '.' in column names as its column-group separator" if name.startswith("__") and not primary_key: @@ -1202,6 +1241,9 @@ def unstorable_column_reason( "SpiralDB drops Arrow field metadata, so a logical (extension) type " "reads back as its storage type" ) + physical_reason = _fixed_binary_or_duration_reason(arrow_type) + if physical_reason is not None: + return physical_reason if arrow_utils.holds_renamed_map(arrow_type): return ( "SpiralDB gives a map's key and item fields back as 'key' and 'value'" @@ -1214,16 +1256,21 @@ def unstorable_column_reason( return None def unstorable_table_name_reason(self, table_name: str) -> str | None: - """Say why SpiralDB cannot hold a table of this name: it holds every name. - - The database's table names are letters, digits and ``_``. + """Say why SpiralDB cannot use this plain table name. Args: table_name: The table name. Returns: - Always ``None``. + A short reason, or ``None`` when the name is valid. """ + if len(table_name) > _TABLE_NAME_MAX_LENGTH: + return ( + f"SpiralDB allows at most {_TABLE_NAME_MAX_LENGTH} characters in a " + f"table name, and this name has {len(table_name)}" + ) + if not table_name or "." in table_name: + return "SpiralDB requires a non-empty plain table name without dots" return None def validate_records(self, records: pa.Table) -> None: diff --git a/tests/test_core/data_tags/test_database_capability.py b/tests/test_core/data_tags/test_database_capability.py index e33adaf88..52ed6b16e 100644 --- a/tests/test_core/data_tags/test_database_capability.py +++ b/tests/test_core/data_tags/test_database_capability.py @@ -395,21 +395,14 @@ def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: def test_spiraldb_failed_write_keeps_the_metadata_of_stored_rows( spiral: None, monkeypatch: pytest.MonkeyPatch ) -> None: - """A failed write restores the metadata entry the stored rows had, even key-only.""" + """A failed write restores the metadata entry the stored rows had.""" connector = SpiralDBConnector("p") connector.create_table_if_not_exists( "k", [ColumnInfo("rid", pa.large_binary())], pk_column="rid" ) - def key_only(ids: list[int]) -> pa.Table: - return mark_data_tags( - pa.table( - {"rid": pa.array([str(i).encode() for i in ids], pa.large_binary())} - ), - ["rid"], - ) - - connector.upsert_records("k", key_only([1]), id_column="rid") + # SpiralDB requires a value column alongside the key. + connector.upsert_records("k", _rows([1]), id_column="rid") real_write = fake_pyspiral.FakeTable.write def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: @@ -417,12 +410,14 @@ def failing_write(self: Any, *args: Any, **kwargs: Any) -> None: monkeypatch.setattr(fake_pyspiral.FakeTable, "write", failing_write) with pytest.raises(RuntimeError, match="write failed"): - connector.upsert_records("k", key_only([2]), id_column="rid") + connector.upsert_records( + "k", mark_data_tags(_rows([2]), ["rid"]), id_column="rid" + ) monkeypatch.setattr(fake_pyspiral.FakeTable, "write", real_write) table = pa.Table.from_batches(list(connector.iter_batches('SELECT * FROM "k"'))) assert table.column("rid").to_pylist() == [b"1"] - assert stored_data_tags(table.schema) == ("rid",) + assert stored_data_tags(table.schema) == ("unit",) def test_spiraldb_failed_metadata_read_leaves_no_nullability_record( diff --git a/tests/test_core/sources/test_spiraldb_table_source_fake.py b/tests/test_core/sources/test_spiraldb_table_source_fake.py index 8f46a99c8..66d798b2f 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_fake.py +++ b/tests/test_core/sources/test_spiraldb_table_source_fake.py @@ -373,9 +373,13 @@ def test_unreadable_record_raises_its_own_type(self, tmp_path: Path): project = fake_pyspiral.FakeSpiral().project(_PROJECT) keys = pa.schema([pa.field("subject_id", pa.string(), False)]) project.create_table("default.subject", key_schema=keys) + # SpiralDB requires a value column alongside the key. + rows = pa.table({"subject_id": ["m1"]}, schema=keys).append_column( + "value", pa.array([1]) + ) SpiralDBConnector(_PROJECT).upsert_records( "subject", - pa.table({"subject_id": ["m1"]}, schema=keys), + rows, id_column="subject_id", ) table = project.table("default.subject") diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index f1d08143f..cb1bf02a3 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -539,7 +539,6 @@ def _typed_rows() -> pa.Table: { "d64": pa.array([one, two, one], pa.date64()), "bin": pa.array([b"a", b"b", b"a"], pa.binary()), - "fbin": pa.array([b"aa", b"bb", b"aa"], pa.binary(2)), "i8": pa.array([-1, 2, -1], pa.int8()), "u8": pa.array([255, 2, 255], pa.uint8()), "i32": pa.array([1, 2, 1], pa.int32()), @@ -549,7 +548,6 @@ def _typed_rows() -> pa.Table: "t32": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time32("s")), "t64": pa.array([dt.time(1), dt.time(2), dt.time(1)], pa.time64("us")), "dec": pa.array([Decimal("1.50")] * 3, pa.decimal128(5, 2)), - "dur": pa.array([dt.timedelta(1)] * 3, pa.duration("us")), } ) return pa.table(columns) @@ -640,7 +638,6 @@ def test_two_zoned_units_and_a_key_together(self, typed): [ ("d64", dt.date(2026, 1, 1), [0, 2]), ("bin", b"a", [0, 2]), - ("fbin", b"aa", [0, 2]), ("i8", -1, [0, 2]), ("u8", 255, [0, 2]), ("i32", 2, [1]), @@ -656,24 +653,32 @@ def test_each_other_type_can_be_matched(self, typed, column, value, expected): @pytest.mark.parametrize( "column, value, match", [ - ("fbin", b"a", "cannot hold"), ("i8", 128, "cannot hold"), ("u8", -1, "cannot hold"), ("u32", 2**32, "cannot hold"), ("t32", 1, "does not support"), ("t64", 1, "does not support"), ("dec", 1.5, "does not support"), - ("dur", 1, "does not support"), ], ) def test_a_value_the_column_cannot_take_is_refused( self, typed, column, value, match ): - """Time of day, decimal and duration columns take no condition: a condition + """Time of day and decimal columns take no condition: a condition holds only a bool, int, float, str, bytes, datetime or date.""" with pytest.raises(TypeError, match=match): typed.where({column: value}) + def test_predicate_types_that_pyspiral_cannot_write(self): + """The predicate checker can be tested without writing an unsupported schema.""" + fixed_binary = pa.schema([pa.field("fbin", pa.binary(2))]) + assert _checked_conditions({"fbin": b"aa"}, fixed_binary) == {"fbin": b"aa"} + with pytest.raises(TypeError, match="cannot hold"): + _checked_conditions({"fbin": b"a"}, fixed_binary) + duration = pa.schema([pa.field("dur", pa.duration("us"))]) + with pytest.raises(TypeError, match="does not support"): + _checked_conditions({"dur": 1}, duration) + @pytest.mark.parametrize( "value", [dt.time(1), Decimal("1.50"), dt.timedelta(1)], ids=repr ) diff --git a/tests/test_databases/fake_pyspiral.py b/tests/test_databases/fake_pyspiral.py index 9bc7a0fb1..81c4b2d99 100644 --- a/tests/test_databases/fake_pyspiral.py +++ b/tests/test_databases/fake_pyspiral.py @@ -56,6 +56,7 @@ from collections.abc import Iterator from contextlib import contextmanager from dataclasses import asdict, dataclass +from hashlib import sha256 from pathlib import Path from typing import Any, cast from unittest.mock import patch @@ -99,6 +100,21 @@ class StorageBehaviour: reject_struct_nulls: bool = True +def _check_arrow_type(arrow_type: pa.DataType) -> None: + """Mirror the unsupported inputs to pyspiral 0.16.33's Schema.from_arrow.""" + if ( + pa.types.is_fixed_size_binary(arrow_type) + or pa.types.is_duration(arrow_type) + or pa.types.is_union(arrow_type) + or pa.types.is_interval(arrow_type) + ): + raise ValueError(f"Arrow data type not supported: {arrow_type}") + if pa.types.is_dictionary(arrow_type): + _check_arrow_type(arrow_type.value_type) + for index in range(arrow_type.num_fields): + _check_arrow_type(arrow_type.field(index).type) + + def _stored_type(t: pa.DataType, b: StorageBehaviour) -> pa.DataType: """Return the Arrow type SpiralDB hands back for a column written as ``t``. @@ -227,8 +243,13 @@ def _push_down_struct_nulls(col: pa.ChunkedArray[Any]) -> pa.ChunkedArray[Any]: def _has_struct_nulls(arr: pa.ChunkedArray[Any]) -> bool: - """Return whether ``arr`` is a struct column with a null struct value.""" - return pa.types.is_struct(arr.type) and arr.null_count > 0 + """Detect a null struct in a struct column or one of its struct fields.""" + if not pa.types.is_struct(arr.type): + return False + # ITL-1446 observed the refusal for a struct inside another struct too. + return arr.null_count > 0 or any( + _has_struct_nulls(field) for field in arr.flatten() + ) class _Store: @@ -246,20 +267,22 @@ def __init__(self, root: Path) -> None: ) def _path(self, project_id: str, identifier: str, suffix: str) -> Path: - # identifiers contain a dot (``dataset.table``), so never use ``with_suffix`` """Return the file holding ``identifier``'s part named by ``suffix``.""" - return self.root / project_id / f"{identifier}{suffix}" + # A 255-character table name plus its dataset and suffix can exceed the + # filesystem's component length, so use a fixed-width filename. + digest = sha256(identifier.encode()).hexdigest() + return self.root / project_id / f"{digest}{suffix}" def exists(self, project_id: str, identifier: str) -> bool: """Return whether table ``identifier`` exists in ``project_id``.""" - return self._path(project_id, identifier, ".keys.json").exists() + return self._path(project_id, identifier, ".identifier").exists() def identifiers(self, project_id: str) -> list[str]: """Return every table identifier of ``project_id``, sorted.""" pdir = self.root / project_id if not pdir.exists(): return [] - return sorted(p.name[: -len(".keys.json")] for p in pdir.glob("*.keys.json")) + return sorted(p.read_text(encoding="utf-8") for p in pdir.glob("*.identifier")) def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> None: """Create table ``identifier`` with ``key_schema`` and empty metadata.""" @@ -269,8 +292,8 @@ def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> Non self._path(project_id, identifier, ".keys.arrow").write_bytes( sink.getvalue().to_pybytes() ) - self._path(project_id, identifier, ".keys.json").write_text( - json.dumps(key_schema.names) + self._path(project_id, identifier, ".identifier").write_text( + identifier, encoding="utf-8" ) self._path(project_id, identifier, ".kv.json").write_text("{}") # SpiralDB gives every table its own id; a recreated table gets a new one. @@ -282,7 +305,7 @@ def create(self, project_id: str, identifier: str, key_schema: pa.Schema) -> Non def drop(self, project_id: str, identifier: str) -> None: """Remove every file of table ``identifier``.""" for suffix in ( - ".keys.json", + ".identifier", ".keys.arrow", ".kv.json", ".data.arrow", @@ -429,7 +452,7 @@ def __init__( self._where = where self._limit = limit - def _rows(self) -> pa.Table: + def _rows(self, key_table: pa.Table | None) -> pa.Table: """Return the rows matching ``where``, cut to ``limit``, in key order.""" rows = self._table._read_all() for name, value in self._where.equalities if self._where else []: @@ -438,15 +461,30 @@ def _rows(self) -> pa.Table: rows.column(name), pa.scalar(value, rows.schema.field(name).type) ) ) + if key_table is not None: + # Scan.to_table(key_table=...) takes keys in request order. The ITL-1446 + # service probe observed a null row in the slot of an absent key. + names = self._table.key_schema.names + by_key = { + key: index for index, key in enumerate(zip(*rows.select(names).columns)) + } + keys = [ + key_table.column(name).cast(rows.schema.field(name).type) + for name in names + ] + indices = pa.array([by_key.get(key) for key in zip(*keys)], type=pa.int64()) + rows = rows.take(indices) return rows if self._limit is None else rows.slice(0, self._limit) - def to_table(self) -> pa.Table: - """Return the scanned rows, in key order.""" - return self._rows() + def to_table(self, *, key_table: pa.Table | None = None) -> pa.Table: + """Return scanned rows in key order or in the requested key order.""" + return self._rows(key_table) - def to_record_batches(self, **kwargs: Any) -> pa.RecordBatchReader: - """Return the rows in key order, ``scan_batch_rows`` per batch, read on demand.""" - rows = self._rows() + def to_record_batches( + self, *, key_table: pa.Table | None = None, **kwargs: Any + ) -> pa.RecordBatchReader: + """Return up to ``scan_batch_rows`` rows per batch, read on demand.""" + rows = self._rows(key_table) def batches() -> Iterator[pa.RecordBatch]: # SpiralDB yields more than one batch for larger tables; split to exercise that. @@ -557,18 +595,36 @@ def write( **kwargs: Accepted for signature compatibility; unused. Raises: - ValueError: If a key column is missing, a column name is one SpiralDB - reserves (a ``.`` anywhere, or a ``__`` prefix on a value column), a - struct value is null without ``push_down_nulls``, or the column set + ValueError: If key columns are missing, the write has no value columns + or a batch repeats a key, a column uses an unsupported name or type, + a struct value is null without ``push_down_nulls``, or the column set differs from the stored table (live SpiralDB adds a new column: the fake does not model it). """ b = self._store.behaviour keys = self.key_schema + if table.num_rows == 0: + # The ITL-1446 service probe hit a native panic on an empty write. + raise ValueError("SpiralDB cannot write a zero-row table") missing = [k for k in keys.names if k not in table.column_names] if missing: raise ValueError(f"write is missing key columns {missing}") + values = sorted(name for name in table.column_names if name not in keys.names) + if not values: + # pyspiral 0.16.33 native writer diagnostic. + raise ValueError( + "Write array contains only key columns, no data columns to write" + ) + if keys.names: + for batch in table.select(keys.names).to_batches(): + # pyspiral 0.16.33 native writer diagnostic names the input batch. + batch_keys = set(zip(*batch.columns)) + if len(batch_keys) != batch.num_rows: + raise ValueError("Duplicate keys found in input batch") for name in table.column_names: + if "\0" in name: + # The ITL-1446 service probe observed truncation at the first NUL. + raise ValueError(f"SpiralDB truncates column name {name!r} at NUL") # SpiralDB's own refusals, with its messages as observed live (ITL-1164). if "." in name: raise ValueError(f"Column '{name}' contains a reserved dot-separator") @@ -577,6 +633,16 @@ def write( f"Column name '{name}' has reserved prefix: column group columns " "must not start with '__'" ) + if name.startswith("$") and name not in keys.names: + # pyspiral 0.16.33 native writer diagnostic in writer/extract.rs. + raise ValueError( + f"Field name {name!r} starts with '$', which is reserved for key columns." + ) + for field in table.schema: + _check_arrow_type(field.type) + if pa.types.is_struct(field.type) and not field.type.num_fields: + # A write of an empty struct was refused by the ITL-1446 service probe. + raise ValueError("SpiralDB cannot write an empty struct") if b.reject_struct_nulls and not push_down_nulls: for name in table.column_names: if _has_struct_nulls(table.column(name)): @@ -599,6 +665,14 @@ def write( ) col = _zero_struct_field_nulls(col, f.type) sf = _stored_field(f, b, nullable=b.server_nullability or None) + stored_type = sf.type + if pa.types.is_struct(stored_type) and f.name in values: + # ITL-1446 observed sorted fields on a top-level struct column. + children = [ + stored_type.field(index) for index in range(stored_type.num_fields) + ] + children.sort(key=lambda field: field.name) + sf = sf.with_type(pa.struct(children)) if isinstance(f.type, pa.ExtensionType): col = pa.chunked_array( [cast("pa.ExtensionArray[Any]", c).storage for c in col.chunks] @@ -611,9 +685,7 @@ def write( # SpiralDB matches a write's columns by name and stores them in its own # order, whatever the order written: the key columns in key-schema order, # then the value columns sorted by name, by code point (observed live, - # ITL-1367). Struct children are sorted live too; the fake keeps them as - # written (struct field order: ITL-1368). - values = sorted(n for n in incoming.column_names if n not in keys.names) + # ITL-1367). incoming = incoming.select([*keys.names, *values]) existing = self._store.read(self._project_id, self._identifier) if existing is not None: @@ -751,13 +823,13 @@ def create_table( root_uri: Any = None, exist_ok: bool = False, ) -> FakeTable: - """Create the table ``".
"`` with ``key_schema`` and open it. + """Create a table with ``key_schema`` and open it. Key columns are stored the way SpiralDB stores them, nullable under ``server_nullability`` however they were declared. Args: - identifier: ``".
"``. + identifier: ``".
"`` or a name in the default dataset. key_schema: An Arrow schema, or ``(name, type)`` pairs as pyspiral accepts. root_uri: Accepted for signature compatibility; unused. exist_ok: Open an existing table instead of raising. @@ -766,16 +838,31 @@ def create_table( The new table, or with ``exist_ok`` the existing one. Raises: - ValueError: If the table exists and ``exist_ok`` is false. + ValueError: If the name or key schema is invalid, or the table exists + and ``exist_ok`` is false. """ - if self._store.exists(self._project_id, identifier): - if not exist_ok: - raise ValueError(f"Table already exists: {identifier}") - return self.table(identifier) + parts = identifier.split(".") + if len(parts) == 1: + identifier = f"default.{identifier}" + # ITL-1446 service probe: 255 characters accepted, 256 refused. + name = parts[-1] + if len(parts) > 2 or not name or len(name) > 255: + raise ValueError(f"Invalid table name: {identifier!r}") if isinstance(key_schema, pa.Schema): schema = key_schema else: schema = pa.schema([pa.field(n, t, True) for n, t in key_schema]) + for field in schema: + _check_arrow_type(field.type) + if pa.types.is_null(field.type): + # pyspiral 0.16.33 native key schema diagnostic. + raise ValueError( + f"Key schema cannot contain Null type field: {field.name}" + ) + if self._store.exists(self._project_id, identifier): + if not exist_ok: + raise ValueError(f"Table already exists: {identifier}") + return self.table(identifier) b = self._store.behaviour # SpiralDB reports key columns nullable however they were declared (ITL-936). schema = pa.schema( diff --git a/tests/test_databases/test_spiraldb_connector_fake.py b/tests/test_databases/test_spiraldb_connector_fake.py index 6d78530da..d9ad02d1e 100644 --- a/tests/test_databases/test_spiraldb_connector_fake.py +++ b/tests/test_databases/test_spiraldb_connector_fake.py @@ -24,6 +24,8 @@ NullabilityRecordError, NullabilityRecordMismatchError, NullInNonNullableColumnError, + UnstorableColumnError, + UnstorableTableNameError, UnsupportedValueError, ) from orcapod.utils import arrow_utils @@ -31,6 +33,185 @@ from tests.test_databases import fake_pyspiral from tests.test_databases.type_matrix import map_of_fields + +@pytest.mark.parametrize("name", ["", "a.b", "a" * 256]) +def test_invalid_table_name(tmp_path, name): + with fake_pyspiral.install(tmp_path): + connector = SpiralDBConnector("p") + assert connector.unstorable_table_name_reason(name) + with pytest.raises(UnstorableTableNameError, match="table name"): + connector.create_table_if_not_exists(name, [], "id") + assert connector.get_table_names() == [] + + +@pytest.mark.parametrize("name", ["_T-9", "T" * 129, "T" * 255]) +def test_valid_table_name(tmp_path, name): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + connector = SpiralDBConnector("p") + assert connector.unstorable_table_name_reason(name) is None + table = project.create_table(f"default.{name}", key_schema=[("id", pa.int64())]) + table.write(pa.table({"id": [1], "value": ["v"]})) + assert connector.get_table_names() == [name] + assert table.schema().to_arrow().names == ["id", "value"] + + +@pytest.mark.parametrize("name", ["", "a.b", "a" * 256]) +def test_fake_refuses_invalid_table_names(tmp_path, name): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises(ValueError, match="table name"): + project.create_table(f"default.{name}", key_schema=[("id", pa.int64())]) + assert project.list_tables() == [] + + +@pytest.mark.parametrize( + ("arrow_type", "reason"), + [ + (pa.binary(16), "fixed_size_binary"), + (pa.duration("us"), "duration"), + (pa.list_(pa.struct([("value", pa.binary(4))])), "fixed_size_binary"), + (pa.map_(pa.int64(), pa.duration("ns")), "duration"), + (pa.month_day_nano_interval(), "month_day_nano_interval"), + (pa.sparse_union([pa.field("value", pa.int64())]), "sparse_union"), + ], +) +def test_fake_refuses_types_rejected_by_schema_from_arrow(tmp_path, arrow_type, reason): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises(ValueError, match=reason): + project.create_table("default.bad", key_schema=[("id", arrow_type)]) + table = project.create_table("default.t", key_schema=[("id", pa.int64())]) + rows = pa.table({"id": [0], "v": pa.nulls(1, type=arrow_type)}) + with pytest.raises(ValueError, match=reason): + table.write(rows) + assert table.schema().to_arrow().names == ["id"] + + +@pytest.mark.parametrize( + ("rows", "message"), + [ + ({"id": [1], "part": [2]}, "Write array contains only key columns"), + ({"id": [1, 1], "part": [2, 2], "v": [3, 4]}, "Duplicate keys found"), + ({"id": [1], "part": [2], "$value": [3]}, "reserved for key columns"), + ({"id": [1], "part": [2], "v\0suffix": [3]}, "at NUL"), + ({"id": [], "part": [], "v": []}, "zero-row"), + ], +) +def test_fake_refuses_invalid_write_batch(tmp_path, rows, message): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + table = project.create_table( + "default.t", key_schema=[("id", pa.int64()), ("part", pa.int64())] + ) + with pytest.raises(ValueError, match=message): + table.write(pa.table(rows)) + # A repeated component is valid, and a later write may upsert a complete key. + table.write(pa.table({"id": [1, 1], "part": [2, 3], "a$b": [3, 4]})) + table.write(pa.table({"id": [1], "part": [2], "a$b": [5]})) + assert table.schema().to_arrow().names == ["id", "part", "a$b"] + assert list(SpiralDBConnector("p").scan_batches("t"))[0].to_pylist() == [ + {"id": 1, "part": 2, "a$b": 5}, + {"id": 1, "part": 3, "a$b": 4}, + ] + + +def test_fake_refuses_null_key_type(tmp_path): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + with pytest.raises( + ValueError, match="Key schema cannot contain Null type field" + ): + project.create_table("t", key_schema=[("id", pa.null())]) + + +@pytest.mark.parametrize( + ("arrow_type", "reason"), + [ + (pa.binary(16), "fixed_size_binary"), + (pa.duration("us"), "duration"), + ], +) +def test_connector_refuses_unstorable_arrow_columns(tmp_path, arrow_type, reason): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + table = project.create_table("default.t", key_schema=[("id", pa.int64())]) + connector = SpiralDBConnector("p") + rows = pa.table({"id": [0], "v": pa.nulls(1, type=arrow_type)}) + with pytest.raises(UnstorableColumnError, match=reason) as exc_info: + connector.upsert_records("t", rows, id_column="id") + assert exc_info.value.column == "v" + assert table.get_metadata() == {} + assert table.schema().to_arrow().names == ["id"] + + +def test_connector_refuses_a_column_name_truncated_at_nul(tmp_path): + with fake_pyspiral.install(tmp_path): + project = fake_pyspiral.FakeSpiral().project("p") + table = project.create_table("t", key_schema=[("id", pa.int64())]) + connector = SpiralDBConnector("p") + name = "before\0after" + assert connector.unstorable_column_reason(name, pa.int64(), primary_key=False) + with pytest.raises(UnstorableColumnError, match="at NUL"): + connector.upsert_records("t", pa.table({"id": [1], name: [2]}), "id") + assert table.get_metadata() == {} + + +def test_key_table_returns_a_null_row_for_a_missing_key(tmp_path): + with fake_pyspiral.install(tmp_path): + client = fake_pyspiral.FakeSpiral() + table = client.project("p").create_table("t", key_schema=[("id", pa.binary())]) + table.write(pa.table({"id": [b"a", b"b"], "v": [1, 2]})) + keys = pa.table({"id": pa.array([b"b", b"x", b"a"], type=pa.large_binary())}) + scan = client.scan(table.select()) + expected = [{"id": b"b", "v": 2}, {"id": None, "v": None}, {"id": b"a", "v": 1}] + assert scan.to_table(key_table=keys).to_pylist() == expected + assert scan.to_record_batches(key_table=keys).read_all().to_pylist() == expected + + +def test_struct_fields_read_back_sorted_with_values_matched_by_name(tmp_path): + with fake_pyspiral.install(tmp_path): + client = fake_pyspiral.FakeSpiral() + table = client.project("p").create_table("t", key_schema=[("id", pa.int64())]) + for key, order in enumerate((("z", "a"), ("a", "z"))): + struct_type = pa.struct([(name, pa.int64()) for name in order]) + struct = pa.array([{"a": 1, "z": 2}], type=struct_type) + table.write(pa.table({"id": [key], "v": struct})) + rows = client.scan(table.select()).to_table() + assert rows.schema.field("v").type == pa.struct( + [("a", pa.int64()), ("z", pa.int64())] + ) + assert rows.to_pylist() == [ + {"id": 0, "v": {"a": 1, "z": 2}}, + {"id": 1, "v": {"a": 1, "z": 2}}, + ] + + +@pytest.mark.parametrize( + ("column", "message"), + [ + (pa.array([{}], type=pa.struct([])), "empty struct"), + ( + pa.array( + [{"inner": None}], + type=pa.struct([("inner", pa.struct([("v", pa.int64())]))]), + ), + "struct-level nulls", + ), + ], +) +def test_fake_refuses_unsupported_struct_values(tmp_path, column, message): + with fake_pyspiral.install(tmp_path): + table = ( + fake_pyspiral.FakeSpiral() + .project("p") + .create_table("t", key_schema=[("id", pa.int64())]) + ) + with pytest.raises(ValueError, match=message): + table.write(pa.table({"id": [0], "v": column})) + assert table.schema().to_arrow().names == ["id"] + + _NESTED = pa.schema( [ pa.field("id", pa.int64(), nullable=False),