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

- A column selection placed directly on a `SpiralDBTableSource` and read outside a
job (`select_data_columns`, `drop_data_columns`, `select_columns`, `drop_columns`,
and the automatic selection before a function pod) now scans only the columns
it keeps. Every tag column, every key column and the columns of a `where`
condition are still read. The result, its hashes, schema, record ids and stored
paths are those of the whole read followed by the selection. On a table with a
wide column the read is several times faster. A job still reads each SpiralDB
source whole.
9 changes: 9 additions & 0 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,15 @@ print(first.row_count_estimate) # rows in the whole table; reads every key to c
metadata lookup; it reads no row and moves nothing). `check_for_new_data()`, which every
run calls first, moves the pin. `head()` and the preview never ask.

**Reading only the columns a selection keeps.** A column selection placed directly on the
source (`select_data_columns`, `drop_data_columns`, `select_columns`, `drop_columns`, or the
selection a function pod adds before itself for columns it does not take) asks SpiralDB for
the columns it keeps, so a wide column it drops (images, long arrays) is never transferred.
Every tag column, every key column and the columns of a `where` condition are still read.
This is only how the rows are read: the result, its hashes, schema and record ids are those
of the whole read followed by the selection. For now it applies to a stream read outside a
job; a pipeline job reads each SpiralDB source whole.

**The row cap.** One read returns at most `max_rows` rows (default 100,000). A read that
would return more raises `SourceTooLargeError`, which says so and gives the ways out:
`limit=`, `where=`, or a larger `max_rows` (`max_rows=None` removes the cap). When nothing
Expand Down
66 changes: 53 additions & 13 deletions src/orcapod/core/operators/column_selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,20 @@
from collections.abc import Collection, Sequence
from typing import Any, ClassVar

import pyarrow as pa

from orcapod.channels import ReadableChannel, WritableChannel
from orcapod.core.data_tags import stream_data_tags, warn_materialized
from orcapod.core.operators.base import UnaryOperator
from orcapod.core.operators.meta_columns import WithoutMetaWriter
from orcapod.core.streams.arrow_table_stream import ArrowTableStream
from orcapod.errors import InputValidationError
from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol
from orcapod.protocols.core_protocols import (
DataProtocol,
SourceProtocol,
StreamProtocol,
TagProtocol,
)
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, ContentHash, Schema
from orcapod.utils.schema_utils import column_names
Expand All @@ -30,6 +37,25 @@ def _canonical_columns(columns: str | Collection[str]) -> tuple[str, ...]:
return tuple(sorted(set(column_names(columns))))


def _input_table(
stream: StreamProtocol, kept_data: Collection[str], columns: dict[str, Any]
) -> pa.Table:
"""Return the input's table for a column selection that keeps ``kept_data``.

A source that can scan fewer columns (``SourceProtocol.projected_table``)
reads only those the selection keeps (ITL-1776); any other input is read
whole. The selection keeps its own rule: it decides what to keep from the
whole input's keys and drops the removed columns that are present, so its
result, identity and route are those of the whole read (a narrowed input
stream would instead meet the "nothing to drop" shortcut).
"""
if isinstance(stream, SourceProtocol):
projected = stream.projected_table(kept_data, columns=columns)
if projected is not None:
return projected
return stream.as_table(columns=columns)


def require_a_data_column(remaining: Collection[str]) -> None:
"""Refuse a column operation whose result would have no data column.

Expand Down Expand Up @@ -229,8 +255,10 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
logger.info("All data columns are selected. Returning stream unaltered.")
return stream

table = stream.as_table(
columns={
table = _input_table(
stream,
new_data_columns,
{
"source": True,
"system_tags": True,
"context": True,
Expand All @@ -244,9 +272,13 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
# A data-tag whose data column is removed keeps its column as a plain
# tag with the same values (specification section 7.2).
data_tags = stream_data_tags(stream)
dropped = {
*(c for c in data_columns_to_drop if c not in data_tags),
*associated_source_fields,
}
# A source that scanned fewer columns has left some out already.
modified_table = table.drop_columns(
[c for c in data_columns_to_drop if c not in data_tags]
+ associated_source_fields
[c for c in table.column_names if c in dropped]
)

return ArrowTableStream._from_derived_table(
Expand Down Expand Up @@ -534,20 +566,26 @@ def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
associated_source_columns = [
f"{constants.SOURCE_PREFIX}{c}" for c in columns_to_drop
]
table = stream.as_table(
columns={
table = _input_table(
stream,
[c for c in data_columns if c not in columns_to_drop],
{
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
# A data-tag whose data column is removed keeps its column as a plain
# tag with the same values (specification section 7.2).
data_tags = stream_data_tags(stream)
dropped = {
*(c for c in columns_to_drop if c not in data_tags),
*associated_source_columns,
}
# A source that scanned fewer columns has left some out already.
modified_table = table.drop_columns(
[c for c in columns_to_drop if c not in data_tags]
+ associated_source_columns
[c for c in table.column_names if c in dropped]
)

return ArrowTableStream._from_derived_table(
Expand Down Expand Up @@ -774,13 +812,15 @@ def validate_unary_input(self, stream: StreamProtocol) -> None:
def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol:
tag_columns, data_columns = self._user_columns(stream)
tags_removed, data_removed = self._removals(tag_columns, data_columns)
table = stream.as_table(
columns={
table = _input_table(
stream,
[c for c in data_columns if c not in data_removed],
{
"source": True,
"system_tags": True,
"context": True,
"sort_by_tags": False,
}
},
)
removed = {
*tags_removed,
Expand Down
25 changes: 24 additions & 1 deletion src/orcapod/core/sources/base.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

import warnings
from collections.abc import Callable
from collections.abc import Callable, Collection
from typing import TYPE_CHECKING, Any, ClassVar, TypeVar, cast

from orcapod import contexts
Expand Down Expand Up @@ -400,6 +400,29 @@ def row_limit(self) -> int | None:
its kind can be limited (``SpiralDBTableSource(limit=...)``)."""
return None

def projected_table(
self,
data_columns: Collection[str],
*,
columns: ColumnConfig | dict[str, Any] | None = None,
) -> "pa.Table | None":
"""Read only the columns needed for ``data_columns``, when this kind can.

Asked by a column selection placed directly on the source (ITL-1776):
``SelectDataColumns``, ``DropDataColumns``, ``SelectColumns`` and
``DropColumns``. A kind that can scan fewer columns returns
``as_table(columns=columns)`` without the data columns not in
``data_columns`` (never a tag column, also a data-tag) and their
source-info columns; everything else in it is what the whole read gives.
It is an execution detail: no identity, schema, record id or stored path
depends on it.

Returns:
``None``: the source is read whole. ``SpiralDBTableSource`` scans fewer
columns.
"""
return None

# -------------------------------------------------------------------------
# Content identity
# -------------------------------------------------------------------------
Expand Down
92 changes: 84 additions & 8 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,18 @@
import copy
import dataclasses
import os
from collections.abc import AsyncIterator, Collection, Generator, Iterator, Mapping
from collections.abc import (
AsyncIterator,
Collection,
Generator,
Iterator,
Mapping,
Sequence,
)
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
from types import TracebackType
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple
from typing import TYPE_CHECKING, Any, ClassVar, NamedTuple, cast

import pyarrow as pa
from typing_extensions import override
Expand Down Expand Up @@ -83,6 +90,7 @@
require_same_process,
)
from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError
from orcapod.system_constants import constants
from orcapod.types import ColumnConfig, ColumnRef, Condition
from orcapod.types.condition import check_float_equalities, check_restriction
from orcapod.utils import arrow_utils
Expand Down Expand Up @@ -981,14 +989,19 @@ def _key_tokens(self, table: "pa.Table") -> list[str]:
) from exc

def _batch_streams(
self, *, with_source_info: bool = True, count_first: bool = True
self,
*,
with_source_info: bool = True,
table_columns: Sequence[str] | None = None,
count_first: bool = True,
) -> Generator["ArrowTableStream", None, None]:
"""Scan the table once and yield its rows as streams of at most ``batch_rows`` rows.

Each SpiralDB batch is held while its slices are yielded.

Args:
with_source_info: As for ``_read_batches``.
table_columns: As for ``_read_batches``.
count_first: As for ``_read_batches``.

Raises:
Expand All @@ -1005,6 +1018,7 @@ def _batch_streams(
limit=self._limit,
max_rows=self._max_rows,
with_source_info=with_source_info,
table_columns=table_columns,
count_first=count_first,
)

Expand All @@ -1016,6 +1030,7 @@ def _read_batches(
limit: int | None,
max_rows: int | None,
with_source_info: bool = True,
table_columns: Sequence[str] | None = None,
count_first: bool = True,
) -> Generator["ArrowTableStream", None, None]:
"""Scan the table once, reading at most ``limit`` rows, in streams of ``batch_rows``.
Expand All @@ -1030,11 +1045,14 @@ def _read_batches(
with_source_info: Whether each stream holds its rows' source-info tokens.
``False`` only where the caller returns no source-info column and
hashes no row (``_whole_table``): the streams then hold null tokens.
table_columns: The table columns to scan, in the table's order; ``None``
scans every column. Only ``projected_table`` passes them, and they
always hold every tag and key column (ITL-1776).
count_first: Whether an unrestricted read that ``limit`` does not keep under
``max_rows`` counts the table's rows before it hands any row on. A
caller that hands no row on before the read ends (``as_table``) passes
``False``: the scan then stops one row past ``max_rows`` and raises the
same error, with no separate count (ITL-1457).
caller that hands no row on before the read ends (``as_table`` or
``projected_table``) passes ``False``: the scan then stops one row past
``max_rows`` and raises the same error, with no separate count (ITL-1457).

Raises:
SourceTooLargeError: If the read would return, or returns, more than
Expand Down Expand Up @@ -1063,10 +1081,21 @@ def _read_batches(
seen = 0
# Keys must be unique across the whole read, not only within a slice.
identifiers: set[str] = set()
expected_schema = self._table_schema
if table_columns is not None:
scanned = set(table_columns)
expected_schema = pa.schema(
[f for f in self._table_schema if f.name in scanned],
metadata=cast(
"dict[bytes | str, bytes | str] | None",
self._table_schema.metadata,
),
)
for batch in table.scan_batches(
where=None if self._condition.is_empty else self._condition,
limit=scan_limit,
asof=asof,
columns=None if table_columns is None else expected_schema.names,
):
for start in range(0, max(batch.num_rows, 1), self._batch_rows):
raw = pa.Table.from_batches([batch.slice(start, self._batch_rows)])
Expand All @@ -1076,10 +1105,10 @@ def _read_batches(
rows = arrow_utils.drop_system_columns(raw)
# Metadata too: field metadata is how a column's logical type is
# recorded, and the schema hash was computed at construction.
if not rows.schema.equals(self._table_schema, check_metadata=True):
if not rows.schema.equals(expected_schema, check_metadata=True):
raise ValueError(
f"SpiralDB table {self._qualified!r}: "
f"{_schema_difference(rows.schema, self._table_schema)}. "
f"{_schema_difference(rows.schema, expected_schema)}. "
"The table changed after the source was built; build the "
"source again to read it as it is now."
)
Expand Down Expand Up @@ -1158,6 +1187,53 @@ def as_table(
all_info=all_info,
)

@override
def projected_table(
self,
data_columns: Collection[str],
*,
columns: ColumnConfig | dict[str, Any] | None = None,
) -> "pa.Table | None":
"""Scan only the columns needed for ``data_columns`` (ITL-1776).

The table is ``as_table(columns=columns)`` without the data columns not in
``data_columns`` and their source-info columns: the other columns, rows,
values, types, record ids, system tags (named with the whole source's
schema hash) and source-info tokens are those of the whole read. The scan
reads every tag column, every key column (the record ids are built from
them), the key column behind each ``tags_as_data`` copy, and the columns of
the ``where`` condition (dropped after the comparison); of the other
columns, only those in ``data_columns``. With no rows, the whole source's
zero-row table without the same columns: never computed from a read.

Returns:
The table, or ``None`` when there are no data columns to omit or the
column configuration requests a hash of each whole row.
"""
config = ColumnConfig.handle_config(columns)
if config.content_hash:
return None
tag_columns, data_keys = self._stream.keys()
wanted = set(data_columns)
unread = {c for c in data_keys if c not in wanted and c not in tag_columns}
if not unread:
return None
keys = set(self._key_columns)
table_columns = [
c for c in self._table_schema.names if c not in unread or c in keys
]
table = self._whole_table(
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
self._batch_streams(
with_source_info=_reads_source_info(config),
table_columns=table_columns,
count_first=False,
),
columns=columns,
all_info=False,
)
dropped = unread | {f"{constants.SOURCE_PREFIX}{c}" for c in unread}
return table.drop_columns([c for c in table.column_names if c in dropped])

def _whole_table(
self,
streams: Iterator["ArrowTableStream"],
Expand Down
Loading
Loading