From e0471929870b6d71133b217f496da969c4741164 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 17:45:25 -0800 Subject: [PATCH 1/3] wip: key ranges for SpiralDB scans --- src/orcapod/databases/spiraldb_connector.py | 145 ++++++- tests/test_databases/fake_spiral_sdk.py | 80 +++- .../test_spiraldb_key_ranges.py | 394 ++++++++++++++++++ 3 files changed, 615 insertions(+), 4 deletions(-) create mode 100644 tests/test_databases/test_spiraldb_key_ranges.py diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index f3e3726a4..643cd808c 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -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 @@ -65,6 +65,8 @@ from orcapod.utils.warning_utils import outside_orcapod_stacklevel if TYPE_CHECKING: + from datetime import datetime + import spiral as sp else: from orcapod.utils.lazy_module import LazyModule @@ -437,6 +439,140 @@ 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_equality_type(arrow_type: pa.DataType) -> bool: + """Return whether an equality of a key column of ``arrow_type`` may enter a key bound. + + Strings, integers, timestamps and dates: the types whose key encoding a live + comparison of key-range and filter reads has confirmed. Other types (binary, + booleans, floats) leave the scan to the filter alone. + """ + return ( + pa.types.is_string(arrow_type) + or pa.types.is_large_string(arrow_type) + or is_range_type(arrow_type) + ) + + +def _bound_order_value(term: Term, arrow_type: pa.DataType) -> Any: + """Return a range bound as a value ordered as the column orders it.""" + if isinstance(arrow_type, pa.TimestampType): + return timestamp_count(cast("datetime", term.value), arrow_type) + return term.value + + +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, an integer, a timestamp or a date; the range column an integer, a timestamp + or a date. 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_range_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 = _bound_order_value(lower, arrow_type) + high = _bound_order_value(upper, arrow_type) + 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. @@ -548,7 +684,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: @@ -565,9 +702,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, diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index e022d4207..472d15a57 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -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 @@ -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 @@ -594,6 +595,69 @@ 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 @@ -686,9 +750,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( @@ -727,6 +800,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) @@ -933,6 +1007,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, ) diff --git a/tests/test_databases/test_spiraldb_key_ranges.py b/tests/test_databases/test_spiraldb_key_ranges.py new file mode 100644 index 000000000..9e456a5ae --- /dev/null +++ b/tests/test_databases/test_spiraldb_key_ranges.py @@ -0,0 +1,394 @@ +"""Key ranges sent to a SpiralDB scan beside its filter (ITL-1775). + +``key_range_plan`` decides, from a where clause's terms, the key range a scan reads: only +when the terms on the key columns are equalities of a key prefix, optionally followed by +a range on the next key column. Every other shape reads with the filter alone. The rows a +read returns never change: the filter still applies every term. +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.databases import SpiralDBConnector +from orcapod.databases import spiraldb_connector as connector_module +from orcapod.databases.spiraldb_connector import KeyRangePlan, key_range_plan +from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition +from orcapod.types.condition import FieldPath, Term, col +from tests.test_databases import fake_spiral_sdk as fake + +_UTC = dt.timezone.utc +_T0 = dt.datetime(2026, 1, 1, tzinfo=_UTC) +_KEYS = ["a", "b", "t"] +_TYPES: dict[str, pa.DataType] = { + "a": pa.string(), + "b": pa.int64(), + "t": pa.timestamp("us", tz="UTC"), + "d": pa.date32(), + "f": pa.float64(), + "bin": pa.binary(), + "v": pa.int64(), +} + + +def _terms(*conditions: Any, **columns: Any) -> list[Any]: + return list(Condition.of(*conditions, **columns).root.children) + + +def _plan(*conditions: Any, keys: list[str] = _KEYS, **columns: Any) -> Any: + return key_range_plan(_terms(*conditions, **columns), keys, _TYPES) + + +def _shape(plan: KeyRangePlan | None) -> Any: + """The plan as plain values: prefix ``(column, value)``s and the two bounds.""" + if plan is None: + return None + + def bound(term: Any) -> Any: + return None if term is None else (term.path.column, term.operator, term.value) + + prefix = tuple((t.path.column, t.value) for t in plan.prefix) + return prefix, bound(plan.lower), bound(plan.upper) + + +# --------------------------------------------------------------- shapes with a key range + + +def test_an_equality_of_the_first_key_column() -> None: + assert _shape(_plan(a="x")) == ((("a", "x"),), None, None) + + +def test_equalities_of_a_prefix_in_any_order_given() -> None: + expected = ((("a", "x"), ("b", 1)), None, None) + assert _shape(_plan(a="x", b=1)) == expected + assert _shape(_plan(b=1, a="x")) == expected + + +def test_the_whole_key_by_equality() -> None: + assert _shape(_plan(a="x", b=1, t=_T0)) == ( + (("a", "x"), ("b", 1), ("t", _T0)), + None, + None, + ) + + +@pytest.mark.parametrize("operator", [">", ">="]) +def test_a_prefix_and_a_lower_bound(operator: str) -> None: + condition = col("t") > _T0 if operator == ">" else col("t") >= _T0 + assert _shape(_plan(condition, a="x", b=1)) == ( + (("a", "x"), ("b", 1)), + ("t", operator, _T0), + None, + ) + + +@pytest.mark.parametrize("operator", ["<", "<="]) +def test_a_prefix_and_an_upper_bound(operator: str) -> None: + condition = col("b") < 5 if operator == "<" else col("b") <= 5 + assert _shape(_plan(condition, a="x")) == ( + (("a", "x"),), + None, + ("b", operator, 5), + ) + + +def test_a_prefix_and_both_bounds() -> None: + later = _T0 + dt.timedelta(hours=1) + plan = _plan(col("t") >= _T0, col("t") < later, a="x", b=1) + assert _shape(plan) == ( + (("a", "x"), ("b", 1)), + ("t", ">=", _T0), + ("t", "<", later), + ) + + +def test_between_is_both_bounds_included() -> None: + assert _shape(_plan(col("b").between(1, 3), a="x")) == ( + (("a", "x"),), + ("b", ">=", 1), + ("b", "<=", 3), + ) + + +def test_a_range_of_the_first_key_column() -> None: + assert _shape(_plan(col("b") >= 2, keys=["b", "a"])) == ((), ("b", ">=", 2), None) + + +def test_a_single_point_range() -> None: + assert _shape(_plan(col("b").between(2, 2), a="x")) == ( + (("a", "x"),), + ("b", ">=", 2), + ("b", "<=", 2), + ) + + +def test_terms_on_other_columns_do_not_matter() -> None: + assert _shape(_plan(col("v") > 3, a="x", f=0.5, bin=b"q")) == ( + (("a", "x"),), + None, + None, + ) + + +def test_a_date_range_after_a_prefix() -> None: + day = dt.date(2026, 1, 2) + assert _shape(_plan(col("d") < day, a="x", keys=["a", "d"])) == ( + (("a", "x"),), + None, + ("d", "<", day), + ) + + +# ------------------------------------------------------------- shapes with no key range + + +def test_no_term_on_a_key_column() -> None: + assert _plan(v=1) is None + assert key_range_plan([], _KEYS, _TYPES) is None + + +def test_a_gap_in_the_key_prefix() -> None: + assert _plan(a="x", t=_T0) is None + assert _plan(b=1) is None + + +def test_a_term_on_a_key_column_after_the_range() -> None: + assert _plan(col("b") > 1, a="x", t=_T0) is None + + +def test_an_equality_and_a_range_of_one_key_column() -> None: + assert _plan(col("b") > 0, a="x", b=1) is None + + +def test_two_equalities_of_one_key_column() -> None: + assert _plan(Condition.of(a="x"), Condition.of(a="y")) is None + + +def test_two_bounds_on_one_side() -> None: + assert _plan(col("b") > 1, col("b") >= 3, a="x") is None + assert _plan(col("b") < 1, col("b") <= 3, a="x") is None + + +@pytest.mark.parametrize( + "conditions", + [ + (col("b") > 3, col("b") < 2), + (col("b") > 2, col("b") < 2), + (col("b") >= 2, col("b") < 2), + (col("b") > 2, col("b") <= 2), + ], + ids=["inverted", "both open", "upper open", "lower open"], +) +def test_an_empty_range(conditions: tuple[Any, ...]) -> None: + assert _plan(*conditions, a="x") is None + + +def test_an_empty_timestamp_range() -> None: + later = _T0 + dt.timedelta(microseconds=1) + assert _plan(col("t") > later, col("t") < later, a="x", b=1) is None + assert _plan(col("t") > later, col("t") <= _T0, a="x", b=1) is None + + +@pytest.mark.parametrize( + ("keys", "where"), + [ + (["f", "a"], {"f": 0.5}), + (["bin", "a"], {"bin": b"q"}), + ], + ids=["float key", "binary key"], +) +def test_a_key_equality_of_an_unconfirmed_type( + keys: list[str], where: dict[str, Any] +) -> None: + assert _plan(where, a="x", keys=keys) is None + + +def test_a_range_on_a_string_key_column() -> None: + # A string range is not a restriction a source takes, and never a key range. + terms = [Term(FieldPath("a"), ">", "m")] + assert key_range_plan(terms, _KEYS, _TYPES) is None + + +# ------------------------------------------------------------------ what the scan is sent + +_ROWS_SCHEMA = pa.schema( + [ + pa.field("a", pa.large_string(), False), + pa.field("b", pa.int64(), False), + pa.field("t", pa.timestamp("us", tz="UTC"), False), + pa.field("v", pa.int64()), + ] +) + + +def _rows() -> pa.Table: + rows = [ + {"a": a, "b": b, "t": _T0 + dt.timedelta(seconds=s), "v": i} + for i, (a, b, s) in enumerate( + (a, b, s) + for a in ("", "x", "xa", "x\x00", "y") + for b in (-1, 0, 1, 2) + for s in (0, 1, 2) + ) + ] + return pa.Table.from_pylist(rows, schema=_ROWS_SCHEMA) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """``keyed``: a table keyed by ``(a, b, t)``.""" + monkeypatch.setattr(connector_module, "_warned_unrecorded", set()) + with fake.install(tmp_path / "spiral"): + made = fake.ExternalProject("p") + made.create_table( + "default.keyed", key_schema=[_ROWS_SCHEMA.field(k) for k in _KEYS] + ).write(_rows()) + fake.migrate("p", {"keyed": _ROWS_SCHEMA}) + yield made + + +def _sent(where: Condition) -> tuple[list[int], Any]: + """The ``v`` of the rows read, and the key ranges the scan was sent.""" + fake.scan_log.clear() + batches = SpiralDBConnector("p").scan_batches("keyed", where=where) + found = [v for b in batches for v in b.column("v").to_pylist()] + (scan,) = fake.scan_log + return found, scan.key_ranges + + +def _expected(where: Condition) -> list[int]: + """The rows the filter alone selects, in key order.""" + fake.scan_log.clear() + with pytest.MonkeyPatch.context() as patch: + patch.setattr(connector_module, "key_range_plan", lambda *_: None) + batches = SpiralDBConnector("p").scan_batches("keyed", where=where) + found = [v for b in batches for v in b.column("v").to_pylist()] + assert fake.scan_log[-1].key_ranges is None + return found + + +def _bounds(key_range: Any) -> Any: + def bound(b: Any) -> Any: + return None if b is None else (tuple(v.value for v in b.values), b.inclusive) + + return bound(key_range.start), bound(key_range.end) + + +_US = 1_767_225_600_000_000 # _T0 as microseconds since the epoch + + +@pytest.mark.parametrize( + ("where", "bounds"), + [ + (Condition.of(a="x"), ((("x",), True), (("x",), True))), + (Condition.of(a="", b=0), ((("", 0), True), (("", 0), True))), + ( + Condition.of(col("b") >= 1, a="x"), + ((("x", 1), True), (("x",), True)), + ), + ( + Condition.of(col("b") > 1, a="x"), + ((("x", 1), False), (("x",), True)), + ), + ( + Condition.of(col("b") < 1, a="x"), + ((("x",), True), (("x", 1), False)), + ), + ( + Condition.of(col("b") <= 1, a="x\x00"), + ((("x\x00",), True), (("x\x00", 1), True)), + ), + ( + Condition.of( + col("t") >= _T0 + dt.timedelta(seconds=1), + col("t") < _T0 + dt.timedelta(seconds=2), + a="x", + b=2, + ), + ( + (("x", 2, _US + 1_000_000), True), + (("x", 2, _US + 2_000_000), False), + ), + ), + ( + Condition.of(a="xa", b=-1, t=_T0 + dt.timedelta(seconds=2)), + ( + (("xa", -1, _US + 2_000_000), True), + (("xa", -1, _US + 2_000_000), True), + ), + ), + ( + Condition.of(col("v") > 10, a="y"), + ((("y",), True), (("y",), True)), + ), + ], + ids=[ + "prefix", + "empty string prefix", + "lower included", + "lower excluded", + "upper excluded", + "upper included", + "timestamp window", + "whole key", + "with a non-key term", + ], +) +def test_the_scan_is_sent_the_key_range_and_reads_the_same_rows( + project: Any, where: Condition, bounds: Any +) -> None: + found, sent = _sent(where) + assert sent is not None and [_bounds(r) for r in sent] == [bounds] + assert found == _expected(where) + + +@pytest.mark.parametrize( + "where", + [ + Condition.of(b=1), + Condition.of(a="x", t=_T0), + Condition.of(col("b") > 3, col("b") < 2, a="x"), + Condition.of(col("b") > 0, a="x", b=1), + Condition.of(v=3), + Condition.of(Condition.of(a="x"), Condition.of(a="y")), + ], + ids=[ + "no first column", + "gap", + "empty range", + "equality and range", + "no key column", + "two equalities", + ], +) +def test_the_scan_is_sent_no_key_range(project: Any, where: Condition) -> None: + found, sent = _sent(where) + assert sent is None + assert found == _expected(where) + + +def test_a_source_reads_the_same_rows_sync_and_async(project: Any) -> None: + later = _T0 + dt.timedelta(seconds=2) + source = SpiralDBTableSource("p", "keyed", tag_only_columns=True).where( + col("t") >= _T0, col("t") < later, a="x", b=1 + ) + fake.scan_log.clear() + table = source.as_table() + assert [_bounds(r) for r in fake.scan_log[-1].key_ranges] == [ + ((("x", 1, _US), True), (("x", 1, _US + 2_000_000), False)) + ] + assert table.column("v").to_pylist() == _expected(source.condition) + + async def rows() -> list[int]: + return [d.as_dict()["v"] async for _, d in source.async_iter_data()] + + sync = [d.as_dict()["v"] for _, d in source.iter_data()] + assert sync == table.column("v").to_pylist() + assert asyncio.run(rows()) == sync From 8638ec96d0ae672e40acf2713b5c510c48568884 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 17:53:10 -0800 Subject: [PATCH 2/3] wip: restrict key-bound types, docs, changelog --- changelog.d/ITL-1775.md | 10 +++++ docs/concepts/sources.md | 8 ++++ src/orcapod/databases/spiraldb_connector.py | 40 +++++++++++-------- tests/test_databases/fake_spiral_sdk.py | 4 +- .../test_spiraldb_key_ranges.py | 36 ++++++++++++----- 5 files changed, 68 insertions(+), 30 deletions(-) create mode 100644 changelog.d/ITL-1775.md diff --git a/changelog.d/ITL-1775.md b/changelog.d/ITL-1775.md new file mode 100644 index 000000000..4b2cb2690 --- /dev/null +++ b/changelog.d/ITL-1775.md @@ -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, integer and unzoned timestamp key columns; any other shape (a gap in the key + prefix, a condition on a key column after the range, a date or zoned timestamp key + column) reads with the filter alone, as before. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 2a54f0213..406e78078 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -702,6 +702,14 @@ 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, integer and unzoned timestamp key columns. + 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, diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 643cd808c..dc5aa4250 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -453,25 +453,35 @@ class KeyRangePlan(NamedTuple): upper: Term | None -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. +def _is_key_bound_type(arrow_type: pa.DataType) -> bool: + """Return whether a key column of ``arrow_type`` may take a value in a key bound. - Strings, integers, timestamps and dates: the types whose key encoding a live - comparison of key-range and filter reads has confirmed. Other types (binary, - booleans, floats) leave the scan to the filter alone. + Integers of every width and sign, and timestamps without a zone: the types whose + key order a live comparison of key-range and filter reads has confirmed. Dates, + zoned timestamps (spiral-sdk creates no table keyed by either, so none could be + compared), binary, booleans and floats leave the scan to the filter alone. """ + return pa.types.is_integer(arrow_type) or ( + isinstance(arrow_type, pa.TimestampType) and arrow_type.tz is None + ) + + +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_range_type(arrow_type) + or _is_key_bound_type(arrow_type) ) -def _bound_order_value(term: Term, arrow_type: pa.DataType) -> Any: - """Return a range bound as a value ordered as the column orders it.""" - if isinstance(arrow_type, pa.TimestampType): +def _bound_order_value(term: Term, arrow_type: pa.DataType) -> int: + """Return a range bound of an integer or timestamp key column as the integer the + column orders it by (``_is_key_bound_type``).""" + if pa.types.is_timestamp(arrow_type): return timestamp_count(cast("datetime", term.value), arrow_type) - return term.value + return cast("int", term.value) def key_range_plan( @@ -483,8 +493,8 @@ def key_range_plan( 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, an integer, a timestamp or a date; the range column an integer, a timestamp - or a date. Any other shape (a gap in the prefix, a key column with an equality and a + string, an integer or a timestamp without a zone; the range column an integer or a + timestamp without a zone. 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. @@ -517,7 +527,7 @@ def key_range_plan( prefix.append(equalities[0]) covered += 1 continue - if not is_range_type(arrow_type): + 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 ("<", "<=")] @@ -541,9 +551,7 @@ def key_range_plan( 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 +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, diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 472d15a57..6843e09ba 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -616,9 +616,7 @@ def _in_key_range(rows: pa.Table, keys: list[str], key_range: KeyRange) -> list[ 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 - ) + 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) diff --git a/tests/test_databases/test_spiraldb_key_ranges.py b/tests/test_databases/test_spiraldb_key_ranges.py index 9e456a5ae..b53a98fc8 100644 --- a/tests/test_databases/test_spiraldb_key_ranges.py +++ b/tests/test_databases/test_spiraldb_key_ranges.py @@ -25,13 +25,15 @@ from tests.test_databases import fake_spiral_sdk as fake _UTC = dt.timezone.utc -_T0 = dt.datetime(2026, 1, 1, tzinfo=_UTC) +_T0 = dt.datetime(2026, 1, 1) _KEYS = ["a", "b", "t"] _TYPES: dict[str, pa.DataType] = { "a": pa.string(), "b": pa.int64(), - "t": pa.timestamp("us", tz="UTC"), + "t": pa.timestamp("us"), + "tz": pa.timestamp("us", tz="UTC"), "d": pa.date32(), + "u": pa.uint64(), "f": pa.float64(), "bin": pa.binary(), "v": pa.int64(), @@ -137,12 +139,11 @@ def test_terms_on_other_columns_do_not_matter() -> None: ) -def test_a_date_range_after_a_prefix() -> None: - day = dt.date(2026, 1, 2) - assert _shape(_plan(col("d") < day, a="x", keys=["a", "d"])) == ( +def test_an_unsigned_range_after_a_prefix() -> None: + assert _shape(_plan(col("u") > 2**63, a="x", keys=["a", "u"])) == ( (("a", "x"),), + ("u", ">", 2**63), None, - ("d", "<", day), ) @@ -210,6 +211,17 @@ def test_a_key_equality_of_an_unconfirmed_type( assert _plan(where, a="x", keys=keys) is None +@pytest.mark.parametrize( + ("column", "low"), + [("d", dt.date(2026, 1, 2)), ("tz", dt.datetime(2026, 1, 1, tzinfo=_UTC))], + ids=["date", "zoned timestamp"], +) +def test_a_key_column_spiral_sdk_cannot_create(column: str, low: Any) -> None: + # No live table could confirm their key order: the filter alone. + assert _plan(col(column) >= low, a="x", keys=["a", column]) is None + assert _plan({column: low}, keys=[column, "a"]) is None + + def test_a_range_on_a_string_key_column() -> None: # A string range is not a restriction a source takes, and never a key range. terms = [Term(FieldPath("a"), ">", "m")] @@ -222,7 +234,7 @@ def test_a_range_on_a_string_key_column() -> None: [ pa.field("a", pa.large_string(), False), pa.field("b", pa.int64(), False), - pa.field("t", pa.timestamp("us", tz="UTC"), False), + pa.field("t", pa.timestamp("us"), False), pa.field("v", pa.int64()), ] ) @@ -254,7 +266,7 @@ def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): yield made -def _sent(where: Condition) -> tuple[list[int], Any]: +def _sent(where: Condition) -> tuple[list[Any], Any]: """The ``v`` of the rows read, and the key ranges the scan was sent.""" fake.scan_log.clear() batches = SpiralDBConnector("p").scan_batches("keyed", where=where) @@ -263,7 +275,7 @@ def _sent(where: Condition) -> tuple[list[int], Any]: return found, scan.key_ranges -def _expected(where: Condition) -> list[int]: +def _expected(where: Condition) -> list[Any]: """The rows the filter alone selects, in key order.""" fake.scan_log.clear() with pytest.MonkeyPatch.context() as patch: @@ -381,12 +393,14 @@ def test_a_source_reads_the_same_rows_sync_and_async(project: Any) -> None: ) fake.scan_log.clear() table = source.as_table() - assert [_bounds(r) for r in fake.scan_log[-1].key_ranges] == [ + sent = fake.scan_log[-1].key_ranges + assert sent is not None + assert [_bounds(r) for r in sent] == [ ((("x", 1, _US), True), (("x", 1, _US + 2_000_000), False)) ] assert table.column("v").to_pylist() == _expected(source.condition) - async def rows() -> list[int]: + async def rows() -> list[Any]: return [d.as_dict()["v"] async for _, d in source.async_iter_data()] sync = [d.as_dict()["v"] for _, d in source.iter_data()] From e15652e72facfd931624ba7039f07f06fbc62221 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 20:52:36 -0800 Subject: [PATCH 3/3] fix: limit key ranges to string and integer keys --- changelog.d/ITL-1775.md | 6 +- docs/concepts/sources.md | 3 +- src/orcapod/databases/spiraldb_connector.py | 31 ++------- .../test_spiraldb_key_ranges.py | 64 +++++++------------ 4 files changed, 34 insertions(+), 70 deletions(-) diff --git a/changelog.d/ITL-1775.md b/changelog.d/ITL-1775.md index 4b2cb2690..c277a8aeb 100644 --- a/changelog.d/ITL-1775.md +++ b/changelog.d/ITL-1775.md @@ -5,6 +5,6 @@ (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, integer and unzoned timestamp key columns; any other shape (a gap in the key - prefix, a condition on a key column after the range, a date or zoned timestamp key - column) reads with the filter alone, as before. + 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. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 3fca60597..393cfae80 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -715,7 +715,8 @@ key column (and name no later key column), the source also sends SpiralDB that p 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, integer and unzoned timestamp key columns. +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 diff --git a/src/orcapod/databases/spiraldb_connector.py b/src/orcapod/databases/spiraldb_connector.py index 5115e6687..ddead231d 100644 --- a/src/orcapod/databases/spiraldb_connector.py +++ b/src/orcapod/databases/spiraldb_connector.py @@ -65,8 +65,6 @@ from orcapod.utils.warning_utils import outside_orcapod_stacklevel if TYPE_CHECKING: - from datetime import datetime - import spiral as sp else: from orcapod.utils.lazy_module import LazyModule @@ -454,16 +452,8 @@ class KeyRangePlan(NamedTuple): def _is_key_bound_type(arrow_type: pa.DataType) -> bool: - """Return whether a key column of ``arrow_type`` may take a value in a key bound. - - Integers of every width and sign, and timestamps without a zone: the types whose - key order a live comparison of key-range and filter reads has confirmed. Dates, - zoned timestamps (spiral-sdk creates no table keyed by either, so none could be - compared), binary, booleans and floats leave the scan to the filter alone. - """ - return pa.types.is_integer(arrow_type) or ( - isinstance(arrow_type, pa.TimestampType) and arrow_type.tz is None - ) + """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: @@ -476,14 +466,6 @@ def _is_key_equality_type(arrow_type: pa.DataType) -> bool: ) -def _bound_order_value(term: Term, arrow_type: pa.DataType) -> int: - """Return a range bound of an integer or timestamp key column as the integer the - column orders it by (``_is_key_bound_type``).""" - if pa.types.is_timestamp(arrow_type): - return timestamp_count(cast("datetime", term.value), arrow_type) - return cast("int", term.value) - - def key_range_plan( terms: list[Term], key_columns: list[str], column_types: Mapping[str, pa.DataType] ) -> KeyRangePlan | None: @@ -493,8 +475,9 @@ def key_range_plan( 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, an integer or a timestamp without a zone; the range column an integer or a - timestamp without a zone. Any other shape (a gap in the prefix, a key column with an equality and 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. @@ -536,8 +519,8 @@ def key_range_plan( 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 = _bound_order_value(lower, arrow_type) - high = _bound_order_value(upper, arrow_type) + low = cast("int", lower.value) + high = cast("int", upper.value) if low > high or ( low == high and (lower.operator == ">" or upper.operator == "<") ): diff --git a/tests/test_databases/test_spiraldb_key_ranges.py b/tests/test_databases/test_spiraldb_key_ranges.py index b53a98fc8..cde544346 100644 --- a/tests/test_databases/test_spiraldb_key_ranges.py +++ b/tests/test_databases/test_spiraldb_key_ranges.py @@ -74,8 +74,8 @@ def test_equalities_of_a_prefix_in_any_order_given() -> None: def test_the_whole_key_by_equality() -> None: - assert _shape(_plan(a="x", b=1, t=_T0)) == ( - (("a", "x"), ("b", 1), ("t", _T0)), + assert _shape(_plan(a="x", b=1, keys=["a", "b"])) == ( + (("a", "x"), ("b", 1)), None, None, ) @@ -83,10 +83,10 @@ def test_the_whole_key_by_equality() -> None: @pytest.mark.parametrize("operator", [">", ">="]) def test_a_prefix_and_a_lower_bound(operator: str) -> None: - condition = col("t") > _T0 if operator == ">" else col("t") >= _T0 - assert _shape(_plan(condition, a="x", b=1)) == ( - (("a", "x"), ("b", 1)), - ("t", operator, _T0), + condition = col("b") > 5 if operator == ">" else col("b") >= 5 + assert _shape(_plan(condition, a="x")) == ( + (("a", "x"),), + ("b", operator, 5), None, ) @@ -102,12 +102,11 @@ def test_a_prefix_and_an_upper_bound(operator: str) -> None: def test_a_prefix_and_both_bounds() -> None: - later = _T0 + dt.timedelta(hours=1) - plan = _plan(col("t") >= _T0, col("t") < later, a="x", b=1) + plan = _plan(col("b") >= 1, col("b") < 5, a="x") assert _shape(plan) == ( - (("a", "x"), ("b", 1)), - ("t", ">=", _T0), - ("t", "<", later), + (("a", "x"),), + ("b", ">=", 1), + ("b", "<", 5), ) @@ -213,8 +212,8 @@ def test_a_key_equality_of_an_unconfirmed_type( @pytest.mark.parametrize( ("column", "low"), - [("d", dt.date(2026, 1, 2)), ("tz", dt.datetime(2026, 1, 1, tzinfo=_UTC))], - ids=["date", "zoned timestamp"], + [("d", dt.date(2026, 1, 2)), ("t", _T0), ("tz", _T0.replace(tzinfo=_UTC))], + ids=["date", "unzoned timestamp", "zoned timestamp"], ) def test_a_key_column_spiral_sdk_cannot_create(column: str, low: Any) -> None: # No live table could confirm their key order: the filter alone. @@ -293,9 +292,6 @@ def bound(b: Any) -> Any: return bound(key_range.start), bound(key_range.end) -_US = 1_767_225_600_000_000 # _T0 as microseconds since the epoch - - @pytest.mark.parametrize( ("where", "bounds"), [ @@ -317,25 +313,6 @@ def bound(b: Any) -> Any: Condition.of(col("b") <= 1, a="x\x00"), ((("x\x00",), True), (("x\x00", 1), True)), ), - ( - Condition.of( - col("t") >= _T0 + dt.timedelta(seconds=1), - col("t") < _T0 + dt.timedelta(seconds=2), - a="x", - b=2, - ), - ( - (("x", 2, _US + 1_000_000), True), - (("x", 2, _US + 2_000_000), False), - ), - ), - ( - Condition.of(a="xa", b=-1, t=_T0 + dt.timedelta(seconds=2)), - ( - (("xa", -1, _US + 2_000_000), True), - (("xa", -1, _US + 2_000_000), True), - ), - ), ( Condition.of(col("v") > 10, a="y"), ((("y",), True), (("y",), True)), @@ -348,8 +325,6 @@ def bound(b: Any) -> Any: "lower excluded", "upper excluded", "upper included", - "timestamp window", - "whole key", "with a non-key term", ], ) @@ -370,6 +345,13 @@ def test_the_scan_is_sent_the_key_range_and_reads_the_same_rows( Condition.of(col("b") > 0, a="x", b=1), Condition.of(v=3), Condition.of(Condition.of(a="x"), Condition.of(a="y")), + Condition.of( + col("t") >= _T0 + dt.timedelta(seconds=1), + col("t") < _T0 + dt.timedelta(seconds=2), + a="x", + b=2, + ), + Condition.of(a="xa", b=-1, t=_T0 + dt.timedelta(seconds=2)), ], ids=[ "no first column", @@ -378,6 +360,8 @@ def test_the_scan_is_sent_the_key_range_and_reads_the_same_rows( "equality and range", "no key column", "two equalities", + "timestamp window", + "timestamp equality", ], ) def test_the_scan_is_sent_no_key_range(project: Any, where: Condition) -> None: @@ -393,11 +377,7 @@ def test_a_source_reads_the_same_rows_sync_and_async(project: Any) -> None: ) fake.scan_log.clear() table = source.as_table() - sent = fake.scan_log[-1].key_ranges - assert sent is not None - assert [_bounds(r) for r in sent] == [ - ((("x", 1, _US), True), (("x", 1, _US + 2_000_000), False)) - ] + assert fake.scan_log[-1].key_ranges is None assert table.column("v").to_pylist() == _expected(source.condition) async def rows() -> list[Any]: