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

- A `SpiralDBTableSource` restricted with `where(...)` now sends SpiralDB a key range
beside its filter when the condition fixes a prefix of the key columns by equality
(in key order), optionally followed by a range on the next key column. SpiralDB then
reads only that part of the table instead of the whole table. The rows read are
unchanged: the filter still applies every condition. A key range is sent only for
string and integer key columns. Other shapes, such as a gap in the key prefix or a
condition on a key column after the range, use the filter alone, as do conditions on
timestamp, date and other key types whose key order has yet to be verified.
9 changes: 9 additions & 0 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -709,6 +709,15 @@ converted, rounded or clamped. Ranges of strings, binary values, booleans and ot
unsupported types are refused, as are conditions such as `is_in`, null tests, `!=`,
comparisons between columns, `|`, and `~`.

How much of the table SpiralDB reads depends on the key columns. When the conditions fix
the first key columns by equality, in key order, optionally followed by a range on the next
key column (and name no later key column), the source also sends SpiralDB that part of the
key as a key range, and only that part of the table is read. Any other condition (for
example one with no condition on the first key column) reads through the whole table,
keeping the matching rows. Either way the rows are the same. A key range is sent only for
string and integer key columns. Conditions on timestamp, date and other key types use
the filter alone until their key order can be verified.

Use `filter` for float ranges. Orcapod evaluates `filter` after the read, treating `0.0` and
`-0.0` as equal and all NaNs as one value ordered after every number. `where` pushes the
condition into SpiralDB, whose IEEE 754 total order puts `-0.0` below `0.0`. For example,
Expand Down
136 changes: 134 additions & 2 deletions src/orcapod/databases/spiraldb_connector.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
from contextlib import contextmanager
from copy import copy
from threading import local
from typing import TYPE_CHECKING, Any, cast
from typing import TYPE_CHECKING, Any, NamedTuple, cast

import pyarrow as pa
import pyarrow.compute as pc
Expand Down Expand Up @@ -437,6 +437,133 @@ def _scan_terms(where: Condition | None) -> list[Term]:
return terms


class KeyRangePlan(NamedTuple):
"""The key range a scan's condition fixes (``key_range_plan``).

Attributes:
prefix: The equalities of the leading key columns, in key order.
lower: The ``>`` or ``>=`` term of the next key column, if any.
upper: The ``<`` or ``<=`` term of the next key column, if any.
"""

prefix: tuple[Term, ...]
lower: Term | None
upper: Term | None


def _is_key_bound_type(arrow_type: pa.DataType) -> bool:
"""Return whether an integer key column may supply an ordered bound."""
return pa.types.is_integer(arrow_type)


def _is_key_equality_type(arrow_type: pa.DataType) -> bool:
"""Return whether an equality of a key column of ``arrow_type`` may enter a key
bound: a ``_is_key_bound_type`` or a string."""
return (
pa.types.is_string(arrow_type)
or pa.types.is_large_string(arrow_type)
or _is_key_bound_type(arrow_type)
)


def key_range_plan(
terms: list[Term], key_columns: list[str], column_types: Mapping[str, pa.DataType]
) -> KeyRangePlan | None:
"""Decide the key range a scan may send beside its filter, or ``None`` for none.

A key range is planned only when the terms on the key columns are exactly, in key
order, equalities of a prefix of the key columns (one per column), optionally
followed by a range on the next key column (at most one lower and one upper bound,
not empty), and no term names a later key column. Every column of the prefix holds a
string or an integer, and the range column holds an integer. Timestamps, dates and
other key types use the filter alone until their key order can be verified.
Any other shape (a gap in the prefix, a key column with an equality and a
range, two bounds on one side, an empty range, a term on a key column after the
range, another type) plans none. Terms on other columns do not matter: the filter
still applies every term, so the key range only narrows what is read.

Args:
terms: The scan's terms (``_scan_terms``), each a plain column equal to, or
ordered against, a value.
key_columns: The table's key columns in key order.
column_types: The type of each column as SpiralDB stores it.

Returns:
The plan, or ``None`` when the scan sends the filter alone.
"""
by_column: dict[str, list[Term]] = {}
for term in terms:
by_column.setdefault(term.path.column, []).append(term)
prefix: list[Term] = []
lower: Term | None = None
upper: Term | None = None
covered = 0 # the key columns the plan accounts for
for column in key_columns:
on_column = by_column.get(column, [])
if not on_column:
break
arrow_type = column_types[column]
equalities = [t for t in on_column if t.operator == EQUALS]
if equalities:
if len(on_column) > 1 or not _is_key_equality_type(arrow_type):
return None
prefix.append(equalities[0])
covered += 1
continue
if not _is_key_bound_type(arrow_type):
return None
lowers = [t for t in on_column if t.operator in (">", ">=")]
uppers = [t for t in on_column if t.operator in ("<", "<=")]
if len(lowers) > 1 or len(uppers) > 1:
return None
lower = lowers[0] if lowers else None
upper = uppers[0] if uppers else None
if lower is not None and upper is not None:
low = cast("int", lower.value)
high = cast("int", upper.value)
if low > high or (
low == high and (lower.operator == ">" or upper.operator == "<")
):
return None
covered += 1
break
if any(column in by_column for column in key_columns[covered:]):
return None
if not prefix and lower is None and upper is None:
return None
return KeyRangePlan(tuple(prefix), lower, upper)


def _key_range(plan: KeyRangePlan, column_types: Mapping[str, pa.DataType]) -> Any: # pyright: ignore[reportExplicitAny] # an SDK key range, untyped
"""Return the SDK's key range of ``plan``.

A bound of SpiralDB compares a key by as many leading columns as the bound holds,
so the prefix alone, inclusive, takes every key that starts with it, and a bound of
the prefix and a range value takes or leaves every key that starts with both.

Args:
plan: A plan of ``key_range_plan``.
column_types: The type of each column as SpiralDB stores it.
"""

def literal(term: Term) -> Any: # pyright: ignore[reportExplicitAny] # an SDK expression
return _literal(term.value, column_types[term.path.column])

prefix = tuple(literal(term) for term in plan.prefix)
whole = sp.KeyBound(prefix, inclusive=True) if prefix else None
start = whole
if plan.lower is not None:
start = sp.KeyBound(
(*prefix, literal(plan.lower)), inclusive=plan.lower.operator == ">="
)
end = whole
if plan.upper is not None:
end = sp.KeyBound(
(*prefix, literal(plan.upper)), inclusive=plan.upper.operator == "<="
)
return sp.KeyRange(start, end)


def _equals(array: Any, value: Any) -> Any:
"""Return where ``array`` equals ``value``, as SpiralDB compares: floats as 64-bit
numbers, ``0.0`` not equal to ``-0.0`` and NaN equal to NaN; a null is no match.
Expand Down Expand Up @@ -573,7 +700,8 @@ def scan_batches(
predicate = None
# Every equality compared here, in the order given: two of one column both hold.
local: list[tuple[str, object]] = []
for term in _scan_terms(where):
terms = _scan_terms(where)
for term in terms:
column, value = term.path.column, term.value
column_type = reading.found.field(column).type
if term.operator != EQUALS:
Expand All @@ -590,9 +718,13 @@ def scan_batches(
continue
equals = sp.eq(sp.column(column), literal)
predicate = equals if predicate is None else sp.and_(predicate, equals)
column_types = {field.name: field.type for field in reading.found}
plan = key_range_plan(terms, list(table.key_columns), column_types)
with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle
reader = table.scan(
filter=predicate,
# Only narrows what is read: the filter still applies every term.
key_ranges=None if plan is None else [_key_range(plan, column_types)],
# The limit counts rows that match every condition.
limit=None if local else limit,
batch_rows=_SCAN_BATCH_ROWS,
Expand Down
78 changes: 76 additions & 2 deletions tests/test_databases/fake_spiral_sdk.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from contextlib import contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import Any, cast
from typing import Any, NamedTuple, cast
from unittest.mock import patch

import pyarrow as pa
Expand Down Expand Up @@ -104,6 +104,7 @@ class ScanRecord:
columns: list[str] | None
filter: Any
limit: int | None
key_ranges: list[KeyRange] | None = None
batches_read: int = 0
closed: bool = False

Expand Down Expand Up @@ -594,6 +595,67 @@ def and_(left: FakePredicate, right: FakePredicate) -> FakePredicate:
return FakePredicate(left.terms + right.terms)


class KeyBound(NamedTuple):
"""Stands in for ``spiral.KeyBound``: a key or a key prefix, in key order."""

values: tuple[_Literal, ...]
inclusive: bool = True


class KeyRange(NamedTuple):
"""Stands in for ``spiral.KeyRange``; an absent bound leaves that end open."""

start: KeyBound | None = None
end: KeyBound | None = None


def _in_key_range(rows: pa.Table, keys: list[str], key_range: KeyRange) -> list[bool]:
"""Return which rows lie in ``key_range`` (``key-range``).

A bound compares a key by as many leading key columns as it holds values, as
SpiralDB does: the prefix ``("a",)``, inclusive, takes every key that starts with
``"a"`` at either end.
"""
width = max((len(b.values) for b in key_range if b is not None), default=0)
columns: list[list[Any]] = []
for name, position in zip(keys, range(width)):
stored: Any = rows.column(name)
for bound in key_range:
if bound is not None and position < len(bound.values):
if stored.type != bound.values[position].type:
raise SpiralError(
"key range is unsupported: requires the key column's dtype, got "
f"{bound.values[position].type} for {stored.type}"
)
if pa.types.is_temporal(stored.type):
stored = stored.cast(
pa.int32() if pa.types.is_date32(stored.type) else pa.int64()
)
columns.append(stored.to_pylist())
wanted: list[bool] = []
for row in range(rows.num_rows):
key = tuple(column[row] for column in columns)
inside = True
if key_range.start is not None:
bound = tuple(_bound_value(v) for v in key_range.start.values)
head = key[: len(bound)]
inside = head >= bound if key_range.start.inclusive else head > bound
if inside and key_range.end is not None:
bound = tuple(_bound_value(v) for v in key_range.end.values)
head = key[: len(bound)]
inside = head <= bound if key_range.end.inclusive else head < bound
wanted.append(inside)
return wanted


def _bound_value(value: _Literal) -> Any:
"""Return a bound's value as ``_in_key_range`` compares it: temporal as a count."""
if pa.types.is_temporal(value.type) and not isinstance(value.value, int):
width = pa.int32() if pa.types.is_date32(value.type) else pa.int64()
return pa.scalar(value.value, value.type).cast(width).as_py()
return value.value


# -------------------------------------------------------------------------------- the client


Expand Down Expand Up @@ -686,9 +748,18 @@ def scan(
filter: FakePredicate | None = None,
limit: int | None = None,
batch_rows: int | None = None,
key_ranges: list[KeyRange] | None = None,
) -> FakeScan:
"""Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``)."""
"""Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``,
``key-range``)."""
rows = self._store.read(self.resource_id, self._version)
if key_ranges is not None:
# One range is all Orcapod sends; several would be replayed in turn.
parts = [
rows.filter(pa.array(_in_key_range(rows, self._table["keys"], r)))
for r in key_ranges
]
rows = pa.concat_tables(parts) if parts else rows.slice(0, 0)
for name, wanted, op in filter.terms if filter else ():
if rows.schema.field(name).type != wanted.type:
raise SpiralError(
Expand Down Expand Up @@ -727,6 +798,7 @@ def scan(
columns,
filter,
limit,
None if key_ranges is None else list(key_ranges),
)
size = (
scan_batch_rows if batch_rows is None else min(batch_rows, scan_batch_rows)
Expand Down Expand Up @@ -933,6 +1005,8 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]:
gt=gt,
gte=gte,
and_=and_,
KeyBound=KeyBound,
KeyRange=KeyRange,
drop_column=drop_column,
)

Expand Down
Loading
Loading