Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/ITL-1446.md
Original file line number Diff line number Diff line change
@@ -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.
3 changes: 3 additions & 0 deletions docs/dev/design_issues/ITL-1162-CA3.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
25 changes: 25 additions & 0 deletions docs/dev/plans/2026-11-24-itl-1446-strict-fake.md
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 5 additions & 5 deletions docs/reference/database-types.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
91 changes: 69 additions & 22 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@
NullabilityRecordError,
NullabilityRecordMismatchError,
NullInNonNullableColumnError,
UnstorableColumnError,
UnstorableTableNameError,
UnsupportedValueError,
)
from orcapod.types import ColumnInfo
Expand All @@ -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:
Expand Down Expand Up @@ -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).

Expand Down Expand Up @@ -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 ``"<project>/<dataset>/<table>"``, the table as errors name it."""
return f"{self._project_id}/{self._dataset}/{table_name}"
Expand Down Expand Up @@ -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
Expand All @@ -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:
Expand Down Expand Up @@ -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,
Expand All @@ -924,33 +963,35 @@ 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
can be read and written through it.

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:
ValueError: If ``pk_column`` is not found in ``columns`` (including
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,
)
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
)
Expand Down Expand Up @@ -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.
Expand All @@ -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:
Expand All @@ -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'"
Expand All @@ -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:
Expand Down
19 changes: 7 additions & 12 deletions tests/test_core/data_tags/test_database_capability.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,34 +395,29 @@ 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:
raise RuntimeError("write failed")

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(
Expand Down
6 changes: 5 additions & 1 deletion tests/test_core/sources/test_spiraldb_table_source_fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading
Loading