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
9 changes: 9 additions & 0 deletions changelog.d/ITL-1801.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
### Changed

- Building a `SpiralDBTableSource` reads the dataset's schema table while it opens the
table (ITL-1801), on a worker thread made for the build and joined before the source is
returned. The first source of a process builds about 12% faster (a small read, build and
read together, went from about 1.75x to about 1.6x a native spiral-sdk read). Rows,
order, hashes, source ids, refusals and warnings are unchanged: when both fail, the
table's error is raised, as before. A build of a missing table now also reads the
schema table.
44 changes: 25 additions & 19 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,26 +385,32 @@ def __init__(
location = f"SpiralDB project {project_id!r}, dataset {dataset!r}"

try:
try:
table = self._connector().lookup_table(table_name)
except SpiralDBTableNotFoundError as exc:
raise ValueError(
f"{location}: Table {table_name!r} not found in database."
) from exc
primary_key = tuple(table.key_columns)
self._key_columns: tuple[str, ...] = (
given_key if given_key is not None else primary_key
)
if not self._key_columns:
raise ValueError(
f"{location}: Table {table_name!r} has no primary key columns, so "
"its rows cannot be identified: name key columns with "
"record_id_columns=[...]."
connector = self._connector()
# The dataset's schema table is read while the table is opened (ITL-1801):
# the two round trips are independent. Its errors are raised where the
# sequential read raised them (``arrow_schema``), so an error before it
# is still the one raised; the thread is joined at the end of the block.
with connector.schema_rows_meanwhile(table_name) as schema_rows:
try:
table = connector.lookup_table(table_name)
except SpiralDBTableNotFoundError as exc:
raise ValueError(
f"{location}: Table {table_name!r} not found in database."
) from exc
primary_key = tuple(table.key_columns)
self._key_columns: tuple[str, ...] = (
given_key if given_key is not None else primary_key
)
self._table_id = table.table_id
# The version every read scans is prepared now (its schema and schema
# record), also a given older one, so a read makes no metadata call.
schema = table.arrow_schema(asof=asof)
if not self._key_columns:
raise ValueError(
f"{location}: Table {table_name!r} has no primary key columns, "
"so its rows cannot be identified: name key columns with "
"record_id_columns=[...]."
)
self._table_id = table.table_id
# The version every read scans is prepared now (its schema and schema
# record), also a given older one, so a read makes no metadata call.
schema = table.arrow_schema(asof=asof, schema_rows=schema_rows)
require_source_column_names(schema.names)
require_supported_nullable_types(schema)
# One version for every read of this source object. A given version is
Expand Down
106 changes: 90 additions & 16 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
import urllib.parse
import urllib.request
import warnings
from collections.abc import Iterator, Mapping
from collections.abc import Callable, Iterator, Mapping
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
from copy import copy
from threading import Lock, local
Expand All @@ -42,6 +43,7 @@
schema_paths,
)
from orcapod.databases.spiraldb_schema_table import (
SchemaRow,
SCHEMA_TABLE,
KeptRows,
SchemaTable,
Expand Down Expand Up @@ -577,6 +579,10 @@ def _equals(array: Any, value: Any) -> Any:
return compute.fill_null(mask, False)


SchemaRows = Callable[[], Mapping[str, SchemaRow] | None]
"""Gives the rows of a dataset's schema table by table id (``SchemaTable.rows``)."""


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

Expand Down Expand Up @@ -615,12 +621,21 @@ def with_connector(self, connector: SpiralDBConnector) -> SpiralDBTable:
duplicate._connector = connector
return duplicate

def _reading(self, table: Any) -> _Reading:
"""Return how a snapshot of this table is read, worked out once per version."""
def _reading(self, table: Any, schema_rows: SchemaRows | None = None) -> _Reading:
"""Return how a snapshot of this table is read, worked out once per version.

Args:
table: The SDK's handle of the snapshot.
schema_rows: Gives the rows of the dataset's schema table, when they are
being read already (``SpiralDBConnector.schema_rows_meanwhile``);
``None`` reads them here.
"""
self._connector._require_open() # pyright: ignore[reportPrivateUsage] # owns the handle
version = str(table.version_id)
if version not in self._readings:
self._readings[version] = self._connector._reading(table, self._table_name) # pyright: ignore[reportPrivateUsage] # owns the handle
self._readings[version] = self._connector._reading( # pyright: ignore[reportPrivateUsage] # owns the handle
table, self._table_name, schema_rows
)
return self._readings[version]

@property
Expand All @@ -633,17 +648,22 @@ def key_columns(self) -> list[str]:
"""The primary-key column names in declaration order (no round trip)."""
return list(self._table.key_columns)

def arrow_schema(self, asof: int | None = None) -> pa.Schema:
def arrow_schema(
self, asof: int | None = None, *, schema_rows: SchemaRows | None = None
) -> pa.Schema:
"""The schema of the batches ``scan_batches`` yields (``get_arrow_schema``).

Args:
asof: Of this version; ``None`` for the version of the lookup.
schema_rows: Gives the rows of the dataset's schema table, when they are
being read already (``SpiralDBConnector.schema_rows_meanwhile``);
``None`` reads them when they are needed.

Raises:
TableSchemaError: If the table's row in the schema table cannot be read, or
disagrees with the table.
"""
return self._reading(self._at(asof)).schema
return self._reading(self._at(asof), schema_rows).schema

def version(self) -> int:
"""The table's version at the lookup (``get_table_version``)."""
Expand Down Expand Up @@ -947,12 +967,7 @@ def lookup_table(self, table_name: str) -> SpiralDBTable:
self._require_open()
self._require_user_table(table_name)
missing = f"Table not found: {self._project_id}.{self._dataset}.{table_name}"
if (
not self._dataset
or not table_name
or "." in self._dataset
or "." in table_name
):
if not self._can_name_a_table(table_name):
raise SpiralDBTableNotFoundError(missing)
table = _open_keyed_table(
self._client, self._project_id, self._dataset, table_name, self._health
Expand All @@ -961,21 +976,37 @@ def lookup_table(self, table_name: str) -> SpiralDBTable:
raise SpiralDBTableNotFoundError(missing)
return SpiralDBTable(self, table, table_name)

def _can_name_a_table(self, table_name: str) -> bool:
"""Whether ``table_name`` in this dataset can name a table at all (no call)."""
return bool(
self._dataset
and table_name
and "." not in self._dataset
and "." not in table_name
)

def _recorded_schema(
self, table: Any, table_name: str, found: pa.Schema
self,
table: Any,
table_name: str,
found: pa.Schema,
schema_rows: SchemaRows | None = None,
) -> pa.Schema | None:
"""Return the schema recorded for an opened table; ``None``: as SpiralDB reports.

Args:
table: The SDK's handle.
table_name: Plain table name.
found: The handle's schema, as SpiralDB reports it.
schema_rows: Gives the schema table's rows when they are being read
already; ``None`` reads them now.

Raises:
TableSchemaError: If the dataset's schema table cannot be read or is not
complete, or the table's row disagrees with the table.
"""
row = self._schemas.row(str(table.resource_id))
rows = (self._schemas.rows if schema_rows is None else schema_rows)()
row = None if rows is None else rows.get(str(table.resource_id))
if row is None:
_warn_unrecorded(self._qualified(table_name), str(table.resource_id))
return None
Expand All @@ -997,9 +1028,16 @@ def _recorded_schema(
)
return row.schema

def _reading(self, table: Any, table_name: str) -> _Reading:
def _reading(
self, table: Any, table_name: str, schema_rows: SchemaRows | None = None
) -> _Reading:
"""Return how an opened snapshot of ``table_name`` is read.

Args:
table: The SDK's handle.
table_name: Plain table name.
schema_rows: As for ``_recorded_schema``.

Raises:
TableSchemaError: If the table's row cannot be read or disagrees with it.
"""
Expand All @@ -1008,9 +1046,45 @@ def _reading(self, table: Any, table_name: str) -> _Reading:
with self._service_call("read the schema of", table_name):
found = table.schema()
with _about_table(qualified):
recorded = self._recorded_schema(table, table_name, found)
recorded = self._recorded_schema(table, table_name, found, schema_rows)
return _Reading(found, recorded, qualified)

@contextmanager
def schema_rows_meanwhile(self, table_name: str) -> Iterator[SchemaRows]:
"""Read the dataset's schema table on a worker thread while the block runs
(ITL-1801).

Opening a table and reading its schema-table row are independent round trips:
a caller that does both (a source being built) starts this one first and hands
what this yields to ``SpiralDBTable.arrow_schema``, which waits for the rows
where it would otherwise read them. Every error is raised where the sequential
read raises it, so the one raised is the same: an error of the block before
the rows are asked for wins, and an error of the read is raised by the call
that asks for them. A read nobody asks for is waited for and dropped.

The thread is made for the block and joined when it ends, however it ends, so
no thread outlives it, and a fork after it sees none. For a name that
``lookup_table`` refuses without a call (the schema table's own, an empty or
qualified name), nothing is started: the rows are read when asked for, as
before.

Args:
table_name: The table the block looks up.

Yields:
A call that waits for the rows and returns them as ``SchemaTable.rows``
does, or raises its error.
"""
self._require_open()
if table_name == SCHEMA_TABLE or not self._can_name_a_table(table_name):
yield self._schemas.rows
return
with ThreadPoolExecutor(
max_workers=1, thread_name_prefix="orcapod-spiraldb-schema-table"
) as pool:
reading = pool.submit(self._schemas.rows)
yield reading.result

def get_pk_columns(self, table_name: str) -> list[str]:
"""Return primary-key column names in declaration order.

Expand Down
10 changes: 0 additions & 10 deletions src/orcapod/databases/spiraldb_schema_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -467,16 +467,6 @@ def __init__(
self._service_call = service_call
self._kept = KeptRows() if kept is None else kept

def row(self, table_id: str) -> SchemaRow | None:
"""Return the row of ``table_id`` as stored now; ``None`` when the dataset has no
schema table, or a complete one without that table.

Raises:
TableSchemaError: If the table cannot be read in full or is not complete.
"""
rows = self.rows()
return None if rows is None else rows.get(table_id)

def rows(self) -> Mapping[str, SchemaRow] | None:
"""Return every row by table id, as stored now; ``None`` when the dataset has no
schema table.
Expand Down
Loading
Loading