Skip to content
Merged
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-1431.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Changed

- SpiralDB table sources reuse their SDK client and resolve the table once per read, including reads that also need a manifest row count. Construction looks up the requested table directly.
427 changes: 243 additions & 184 deletions src/orcapod/core/sources/spiraldb_table_source.py

Large diffs are not rendered by default.

91 changes: 72 additions & 19 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import re
from collections.abc import Callable, Iterator, Mapping
from contextlib import contextmanager
from copy import copy
from typing import TYPE_CHECKING, Any

import pyarrow as pa
Expand Down Expand Up @@ -448,6 +449,10 @@ def _holds_nested_field_metadata(arrow_type: pa.DataType) -> bool:
)


class SpiralDBTableNotFoundError(ValueError):
"""An exact table lookup found no matching table."""


class SpiralDBTable:
"""One SpiralDB table, looked up once (``SpiralDBConnector.lookup_table``).

Expand Down Expand Up @@ -487,15 +492,47 @@ def arrow_schema(self) -> pa.Schema:
"""
import pyarrow as _pa # noqa: PLC0415

self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle
declared = self._table.schema().to_arrow()
empty = _pa.RecordBatch.from_pylist([], schema=declared)
preparer = self._connector._batch_preparer(self._table, self._table_name) # pyright: ignore[reportPrivateUsage] # the connector's own preparer
return preparer(empty).schema

def version(self) -> int:
"""The table's current version (``get_table_version``)."""
self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle
return int(self._table.last_modified_at())

def scan_batches(
self,
*,
where: Mapping[str, object] | None = None,
limit: int | None = None,
asof: int | None = None,
) -> Iterator[pa.RecordBatch]:
"""Yield prepared Arrow batches from this resolved table in key order."""
connector = self._connector
connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle
table = self._table
prepare = connector._batch_preparer(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle
predicate = None
for column, value in (where or {}).items():
equals = table[column] == value
predicate = equals if predicate is None else predicate & equals
scan = connector._spiral.scan( # pyright: ignore[reportPrivateUsage] # owns the handle
table.select(), where=predicate, limit=limit, asof=asof
)
for batch in scan.to_record_batches():
yield prepare(batch)

def row_count_estimate(self, asof: int | None = None) -> int:
"""Return this resolved table's manifest row count at the requested version."""
connector = self._connector
connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle
snapshot = self._table.core.get_snapshot(asof=asof)
stats = connector._spiral.core.manifest_stats(snapshot) # pyright: ignore[reportPrivateUsage] # owns the handle
return int(stats.key_space_stats.total_rows)


class SpiralDBConnector:
"""DBConnectorProtocol implementation backed by SpiralDB (pyspiral).
Expand Down Expand Up @@ -531,6 +568,11 @@ def _require_open(self) -> None:
if self._closed:
raise RuntimeError("SpiralDBConnector is closed")

def share_client(self) -> SpiralDBConnector:
"""Return an independently closable connector in the same SDK client scope."""
self._require_open()
return copy(self)

def _table_id(self, table_name: str) -> str:
"""Return the dataset-qualified table identifier for a plain table name."""
return f"{self._dataset}.{table_name}"
Expand Down Expand Up @@ -563,9 +605,26 @@ 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()
return SpiralDBTable(
self, self._project.table(self._table_id(table_name)), table_name
)
identifier = self._table_id(table_name)
if (
not self._dataset
or not table_name
or "." in self._dataset
or "." in table_name
):
# The SDK omits empty filters and treats dots as identifier separators.
raise SpiralDBTableNotFoundError(
f"Table not found: {self._project_id}.{identifier}"
)
try:
table = self._project.table(identifier)
except ValueError as exc:
# pyspiral raises this exact ValueError for an empty name lookup. Preserve
# other failures, including errors in loading the returned table handle.
if str(exc) != f"Table not found: {self._project_id}.{identifier}":
raise
raise SpiralDBTableNotFoundError(str(exc)) from exc
return SpiralDBTable(self, table, table_name)

def get_pk_columns(self, table_name: str) -> list[str]:
"""Return primary-key column names in declaration order.
Expand Down Expand Up @@ -783,16 +842,9 @@ def scan_batches(
NullInNonNullableColumnError: If a batch holds a null in a recorded
non-nullable column (naming the table and the column).
"""
self._require_open()
tbl = self._project.table(self._table_id(table_name))
prepare = self._batch_preparer(tbl, table_name)
predicate = None
for column, value in (where or {}).items():
equals = tbl[column] == value
predicate = equals if predicate is None else predicate & equals
scan = self._spiral.scan(tbl.select(), where=predicate, limit=limit, asof=asof)
for batch in scan.to_record_batches():
yield prepare(batch)
yield from self.lookup_table(table_name).scan_batches(
where=where, limit=limit, asof=asof
)

def get_arrow_schema(self, table_name: str) -> pa.Schema:
"""Return the schema of the batches ``scan_batches`` yields, without scanning.
Expand Down Expand Up @@ -850,10 +902,7 @@ def get_row_count_estimate(self, table_name: str, asof: int | None = None) -> in
Returns:
The recorded row count.
"""
self._require_open()
tbl = self._project.table(self._table_id(table_name))
stats = self._spiral.core.manifest_stats(tbl.core.get_snapshot(asof=asof))
return int(stats.key_space_stats.total_rows)
return self.lookup_table(table_name).row_count_estimate(asof=asof)

def delete_table(self, table_name: str) -> None:
"""Drop a table from SpiralDB, if it exists.
Expand Down Expand Up @@ -1181,8 +1230,12 @@ def validate_records(self, records: pa.Table) -> None:
"""No-op: ``SpiralDBConnector`` preserves Arrow field metadata via the native KV store."""

def close(self) -> None:
"""Mark this connector as closed. Idempotent. No network teardown needed."""
self._closed = True
"""Close this connector and release its SDK client. Idempotent."""
if not self._closed:
self._closed = True
# pyspiral exposes no close method. Drop both owning references.
del self._project
del self._spiral

def __enter__(self) -> SpiralDBConnector:
return self
Expand Down
Loading
Loading