From b1d4f27e0da79cd1c83401f916cd88604b5256ae Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 14:59:09 -0800 Subject: [PATCH 01/12] feat(spiraldb): push down keyed source membership --- changelog.d/ITL-1986.md | 3 + docs/concepts/sources.md | 32 +++-- .../core/sources/spiraldb_table_source.py | 65 ++++++--- .../databases/spiraldb_keyed/connector.py | 123 +++++++++++++++--- src/orcapod/types/condition.py | 107 +++++++++------ ..._spiraldb_table_source_float_equalities.py | 9 ++ .../test_spiraldb_table_source_live.py | 27 +++- .../test_spiraldb_table_source_where.py | 122 ++++++++++++++++- tests/test_databases/fake_spiral_sdk.py | 77 ++++++----- 9 files changed, 441 insertions(+), 124 deletions(-) create mode 100644 changelog.d/ITL-1986.md diff --git a/changelog.d/ITL-1986.md b/changelog.d/ITL-1986.md new file mode 100644 index 000000000..7ca8bf8fd --- /dev/null +++ b/changelog.d/ITL-1986.md @@ -0,0 +1,3 @@ +### Added + +- Restrict a keyed SpiralDB source to a set of values with `where(col(column).is_in(values))`. The restriction preserves source, pipeline and record identities. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 08d08b8d2..9707b7c94 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -741,9 +741,8 @@ rows in which every named column equals its value. Several conditions can be giv call, as keywords or as a mapping, or across chained calls: `readings.where(sensor_id=106, site_id=2)` and `readings.where(sensor_id=106).where(site_id=2)` are the same restriction, reading the -same rows. The conditions are a `Condition` (`orcapod.types`): `where(...)` builds one with -`Condition.of(...)`, which takes the same arguments, and a `Condition` built beforehand can be -given instead (`readings.where(Condition.of(sensor_id=106, site_id=2))`). A source +same rows. `where(...)` builds a `Condition` (`orcapod.types`) or accepts one built +beforehand (`readings.where(Condition.of(sensor_id=106, site_id=2))`). A source restricted by a condition, a `limit=`, or both is **restricted**. Every source states its restriction through two read-only properties: `condition` (the empty `Condition` when it reads every row) and `row_limit` (`None` without a limit). @@ -767,7 +766,7 @@ second_hour = readings.where(col("timestamp") >= hour, col("timestamp") < 2 * ho one_sensor = first_hour.where(sensor_id=106) # a range and an equality ``` -Ranges and equalities all must hold, on one column or several, given in one call or across +Ranges, equalities and memberships all must hold, on one column or several, given in one call or across chained calls in any order: the order never changes the rows, the condition or how it is saved. Ranges that cannot all hold are kept and read no row. A null meets no range. SpiralDB applies a range in the scan, so only the window's rows are transferred, and the row cap @@ -775,8 +774,8 @@ counts them. A bound is checked as an equality value is: exactly of the column's (`int`, `datetime`, `date`), held exactly by its Arrow type (`-1` is refused for an unsigned column, a microsecond for `timestamp[s]`, a naive `datetime` for a zoned column), never converted, rounded or clamped. Ranges of strings, binary values, booleans and other -unsupported types are refused, as are conditions such as `is_in`, null tests, `!=`, -comparisons between columns, `|`, and `~`. +unsupported types are refused. The source also refuses null tests, `!=`, comparisons +between columns, `|` and negation of a comparison. 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 @@ -829,8 +828,8 @@ explore = readings.where(sensor_id=106, site_id=2) # The pipeline: the same selection as a step, part of every downstream identity. kept = readings.filter(sensor_id=106, site_id=2) -# Use a filter for conditions such as is_in that where cannot apply. -late = readings.filter(col("timestamp") >= 1_000_000, col("sensor_id").is_in([106, 107])) +# Restrict the read to several sensors and a time window. +late = readings.where(col("sensor_id").is_in([106, 107]), col("timestamp") >= 1_000_000) ``` A filter directly over a source reads every row the source reads (the whole table, or what @@ -914,6 +913,19 @@ print(Condition.of(day=day, started=started, recorded=recorded)) `where()` with no condition. Everything else of the source is carried over: the pinned table version, `limit`, `max_rows`, the tags and data-tags, `tags_as_data`, the key columns, the source id and the label. The original source is not changed. +- **Set membership.** Use `where(col("sensor_id").is_in([106, 107]))` to read rows + with any of the named values. You can combine membership with equalities, ranges or + other memberships. Mapping and keyword values can also be lists, tuples, sets or + frozensets, such as `where(sensor_id=[106, 107])`. The collection must contain at least one value and cannot contain + `None`. The equality type and exactness rules apply to every member. Duplicate values + and value order have no effect on the selected rows or saved condition. The SDK + has no `IN` predicate, so Orcapod sends a balanced OR of equalities in one scan, + with a shared budget of up to 512 membership equalities. For larger memberships + or literals the SDK cannot represent, such as `float16` values, Orcapod checks + membership locally before applying the limit. On an integer, timestamp or date + key, it also pushes the range from the least to greatest member into the scan. + A wide range or a membership with no supported range can transfer many rows that + the source does not return. - **Exact values.** An integer column takes a Python `int`, a float column takes a Python `float`, a date column takes a `datetime.date`, and a timestamp column takes a `datetime.datetime`. A float column without a logical type also takes a Python `int`. @@ -923,8 +935,8 @@ print(Condition.of(day=day, started=started, recorded=recorded)) call if the column's Arrow type cannot hold the value exactly. For example, on a `float32` column, `where(x=0.5)` is valid and `where(x=0.1)` raises. ITL-1480 tracks revisiting this refusal. Lists and structs take no condition. -- **The table system's equality.** Each condition is sent to SpiralDB as `column == value`, - and which rows it selects is SpiralDB's own equality, not Orcapod's. For a float column, +- **The table system's equality.** Each equality or membership value uses SpiralDB's + own equality. For a float column, `0.0` does not select the `-0.0` rows (seen on the service, not documented by it). An equality to `-0.0` or a NaN raises `TypeError` for now and points to `filter`. SpiralDB matches them by their bits, while Orcapod counts `-0.0` equal to `0.0` and NaN equal to NaN, so diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 848435214..f80ad8f40 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -92,7 +92,7 @@ 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.types.condition import check_float_equalities, check_restriction, col from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -207,6 +207,30 @@ def spiraldb_table_address( return address +def _where_condition( + *conditions: Mapping[str, object] | Condition | ColumnRef | None, + **columns: object, +) -> Condition: + """Translate collection-valued source arguments to membership terms.""" + terms: list[Mapping[str, object] | Condition | ColumnRef | None] = [] + + def equalities(mapping: Mapping[str, object]) -> dict[str, object]: + scalar: dict[str, object] = {} + for column, value in mapping.items(): + if isinstance(value, (list, tuple, set, frozenset)): + terms.append(col(column).is_in(value)) + else: + scalar[column] = value + return scalar + + for argument in conditions: + terms.append( + equalities(argument) if isinstance(argument, Mapping) else argument + ) + keywords = equalities(columns) + return Condition.of(*terms, **keywords) + + class SpiralDBTableSource(RootSource): """A read-only Source over a table in a SpiralDB dataset, read in batches. @@ -264,9 +288,8 @@ class SpiralDBTableSource(RootSource): single column name. If ``None`` (default), the table's primary-key (key-schema) columns are used. where: Column name to value, or a ``Condition`` (``orcapod.types``) of - equalities and ranges. Only the rows that meet it are read; SpiralDB - applies it before any row is transferred. Values follow the same type - and exactness rules as ``where()``. + equalities, set memberships and ranges. Only matching rows are returned. + Values follow the same type and exactness rules as ``where()``. limit: Read at most this many rows: the first in key order (after ``where``). asof: Read the table as of this version (microseconds, as SpiralDB's transaction timestamps). If ``None`` (default), the version the table has @@ -363,7 +386,7 @@ def __init__( if isinstance(where, Condition): requested = where else: - requested = Condition.of(where) if where else Condition() + requested = _where_condition(where) if where else Condition() if not _is_positive_int(batch_rows): raise ValueError( f"batch_rows must be a positive integer, got {batch_rows!r}" @@ -571,24 +594,34 @@ def where( row this source reads, record id included; it adds no step to a pipeline. A pipeline that must select rows as part of what it computes uses an operator (``SemiJoin``, ``Filter``) instead. SpiralDB applies the conditions in - the scan, as for the ``where=`` argument: the two are one mechanism, and the - conditions are added to any the source already has. Everything else is carried + the scan where possible. Both ``where()`` and the ``where=`` argument add + conditions to any the source already has. Everything else is carried over (the pinned table version, ``limit``, ``max_rows``, tags, data-tags, ``tags_as_data``, key columns, source id, label, data context). With a ``limit``, the new source reads the first ``limit`` rows that match. - Two kinds of condition are taken, all of which must hold: a column equal to a + All conditions must hold. A column can be equal to a value (a keyword, a mapping, ``col(c) == v``; a bare ``col(c)`` of a boolean column is ``col(c) == True`` and ``~col(c)`` is ``col(c) == False``, sent to - SpiralDB as those equalities, so a null row is read by neither), and a range - of an integer, + SpiralDB as those equalities, so a null row is read by neither), a member of a + nonempty set (``col(c).is_in(values)``), or in a range of an integer, timestamp or date column (``col("t") >= start``, ``col("t") < stop``, ``col("t").between(a, b)``, which includes both ends). Write a window half-open, ``>= start`` and ``< stop``: adjacent windows then neither overlap nor leave a gap. Ranges of one column add up, and may select no row; a null meets no condition. Float ranges are refused for now (ITL-1477). Use ``filter`` for ranges of unsupported types such as floats and strings. Anything else - (``is_in``, a null test, ``!=``, two columns, ``|``, ``~``) is refused too. + (``is_null()``, ``!=``, two columns, ``|``, or negation of a comparison) is refused. + + Membership uses the equality rules for each value. None and empty sets are + refused. Order and duplicates have no effect. SpiralDB's SDK has no IN + predicate, so Orcapod sends a balanced OR of equalities to the scan when the + SDK supports the literals and the expression has room. The scan has a shared + budget of up to 512 membership equalities. For larger memberships or + unsupported literals (for example, ``float16``), Orcapod checks membership + locally before applying ``limit``. An integer, timestamp or date key also gets + a scan range from its least to greatest member. The scan can transfer + extra rows, especially when the member values are far apart. For now, ``where()`` refuses float equality values that the column's Arrow type cannot hold exactly. For example, a plain float32 column accepts @@ -600,8 +633,8 @@ def where( depend on which of two equal values a condition kept. ITL-1480 tracks revisiting the float refusals. Use ``filter`` to compare these values by Orcapod's rules. - A convenience: the arguments are given to ``Condition.of``, which builds the - ``Condition`` (``orcapod.types``); the source checks it against its table and + A list, tuple, set or frozenset in a mapping or keyword also means membership. + The source builds a ``Condition`` (``orcapod.types``), checks it against its table and adds it to the condition it has (``Condition.combined``). A ``Condition`` built beforehand is accepted as it is. The source's ``limit`` is its own and is not changed. @@ -638,7 +671,7 @@ def where( check_float_equalities(*conditions, **columns) except TypeError as exc: raise TypeError(f"SpiralDB table {self._qualified!r}: {exc}") from exc - condition = Condition.of(*conditions, **columns) + condition = _where_condition(*conditions, **columns) restricted = self._copy() try: restricted._apply_restriction(condition) @@ -696,7 +729,7 @@ def _apply_restriction(self, condition: Condition) -> None: Raises: ValueError: If a column is not in the table, or a column must equal two different values. - TypeError: If the condition holds anything but equalities and ranges, a + TypeError: If the condition holds anything but equalities, memberships and ranges, a range names a column of another type, or a value is not of its column's type or does not fit it. """ @@ -968,7 +1001,7 @@ def _too_large(self, found: str) -> SourceTooLargeError: return SourceTooLargeError( f"SpiralDB table {self._qualified!r}: {found}, more than " f"max_rows={self._max_rows}{self._under_condition()}. Read fewer rows " - "with limit= or a narrower where= or where(...) (equalities, and ranges " + "with limit= or a narrower where= or where(...) (equalities, memberships, and ranges " "such as col(c) >= start, col(c) < stop), or raise max_rows " "(max_rows=None removes the cap; a pipeline job keeps every row in memory)." ) diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 45e444858..eb6f6d589 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -24,7 +24,7 @@ import urllib.parse import urllib.request import warnings -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Callable, Iterator, Mapping, Sequence from contextlib import contextmanager from copy import copy from threading import Lock, local @@ -72,6 +72,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 @@ -82,6 +84,9 @@ # The largest batch a scan hands out. SpiralDB's default is 1,024 rows. _SCAN_BATCH_ROWS = 8_192 +# ScanDAL accepts up to 4,096 expression nodes. One equality leaf and its OR +# consume five nodes. Reserve additional space for regular and fallback predicates. +_MAX_MEMBERSHIP_EQUALITIES = 512 _LIST_TIMEOUT_S = 60 _NO_WRITES = ( "a plain SpiralDBKeyedConnector only reads SpiralDB tables; nothing was written. A job " @@ -661,8 +666,8 @@ def _scan_terms(where: Condition | None) -> list[Term]: """Return the requirements of a scan's condition, refusing what a scan cannot apply. Raises: - ValueError: If a requirement is not a plain column equal to, or ordered against, - a value (``check_restriction`` refuses these before a source reads). + ValueError: If a requirement is not equality, membership or a range of a + plain column (``check_restriction`` refuses these before a source reads). """ terms: list[Term] = [] for node in () if where is None else where.root.children: @@ -670,15 +675,53 @@ def _scan_terms(where: Condition | None) -> list[Term]: isinstance(node, Term) and not node.path.fields and not isinstance(node.value, ColumnOperand) - and (node.operator == EQUALS or node.operator in _COMPARE) + and (node.operator in (EQUALS, "is_in") or node.operator in _COMPARE) ): raise ValueError( - f"a scan applies equalities and ranges of a column only; got {where}" + f"a scan applies equalities, memberships and ranges of a column only; got {where}" ) terms.append(node) return terms +def _balanced_predicate( + predicates: list[Any], combine: Callable[[Any, Any], Any] +) -> Any: + """Combine scan predicates in a tree of logarithmic depth.""" + while len(predicates) > 1: + combined = [ + combine(predicates[i], predicates[i + 1]) + for i in range(0, len(predicates) - 1, 2) + ] + if len(predicates) % 2: + combined.append(predicates[-1]) + predicates = combined + return predicates[0] if predicates else None + + +def _membership_mask(array: Any, values: pa.Array[Any]) -> Any: + """Compare membership locally, using the same signed-zero rule as SpiralDB.""" + compute: Any = pc + if pa.types.is_floating(array.type): + array = array.cast(pa.float64()).view(pa.uint64()) + return compute.is_in(array, value_set=values) + + +def _membership_values( + values: tuple[object, ...], arrow_type: pa.DataType +) -> pa.Array[Any]: + """Build a local membership lookup using floating-point bits when needed.""" + if pa.types.is_floating(arrow_type): + floats = [float(value) if isinstance(value, int) else value for value in values] + return pa.array(floats, type=pa.float64()).view(pa.uint64()) + if isinstance(arrow_type, pa.TimestampType): + counts = [ + timestamp_count(cast("datetime", value), arrow_type) for value in values + ] + return pa.array(counts, type=arrow_type) + return pa.array(values, type=arrow_type) + + 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. @@ -839,7 +882,7 @@ def scan_batches( """Yield prepared Arrow batches from this resolved table in key order. Args: - where: Equalities and ranges of columns, all of which must hold + where: Equalities, memberships and ranges of columns, all of which must hold (``SpiralDBKeyedConnector.scan_batches``). limit: Read at most this many matching rows. asof: Read this version. @@ -856,20 +899,53 @@ def scan_batches( reading = self._reading(table) wanted: list[str] | None = None scanned: list[str] | None = None + terms = _scan_terms(where) if columns is not None: - needed = set(columns) | {t.path.column for t in _scan_terms(where)} + needed = set(columns) | {t.path.column for t in terms} wanted = [n for n in reading.found.names if n in set(columns)] scanned = [n for n in reading.found.names if n in needed] reading = reading.projected(scanned) - predicate = None + predicates: list[Any] = [] + membership_budget = max(0, _MAX_MEMBERSHIP_EQUALITIES - 2 * len(terms)) + key_columns = self.key_columns # 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): + local_memberships: list[tuple[str, pa.Array[Any]]] = [] + for term in terms: column, value = term.path.column, term.value column_type = reading.found.field(column).type + if term.operator == "is_in": + assert isinstance(value, tuple) and value + if len(value) <= membership_budget: + literals = [_literal(member, column_type) for member in value] + if all(literal is not None for literal in literals): + field = sp.column(column) + predicates.append( + _balanced_predicate( + [sp.eq(field, literal) for literal in literals], sp.or_ + ) + ) + membership_budget -= len(value) + continue + local_memberships.append( + ( + column, + _membership_values(value, reading.schema.field(column).type), + ) + ) + if column in key_columns and is_range_type(column_type): + ordered = cast("tuple[Any, ...]", value) + predicates.extend( + ( + _range_predicate(column, ">=", min(ordered), column_type), + _range_predicate(column, "<=", max(ordered), column_type), + ) + ) + continue if term.operator != EQUALS: - bound = _range_predicate(column, term.operator, value, column_type) - predicate = bound if predicate is None else sp.and_(predicate, bound) + predicates.append( + _range_predicate(column, term.operator, value, column_type) + ) continue literal = _literal(value, column_type) if literal is None and pa.types.is_float32(column_type): @@ -879,14 +955,15 @@ def scan_batches( if literal is None: local.append((column, value)) continue - equals = sp.eq(sp.column(column), literal) - predicate = equals if predicate is None else sp.and_(predicate, equals) + predicates.append(sp.eq(sp.column(column), literal)) + predicate = _balanced_predicate(predicates, sp.and_) + has_local = bool(local or local_memberships) with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle reader = table.scan( scanned, filter=predicate, # The limit counts rows that match every condition. - limit=None if local else limit, + limit=None if has_local else limit, batch_rows=_SCAN_BATCH_ROWS, ).to_reader() left = limit @@ -899,12 +976,14 @@ def scan_batches( batch = reading.prepare(batch) for column, value in local: batch = batch.filter(_equals(batch.column(column), value)) - if local and left is not None: + for column, values in local_memberships: + batch = batch.filter(_membership_mask(batch.column(column), values)) + if has_local and left is not None: batch = batch.slice(0, left) left -= batch.num_rows if wanted is not None and wanted != scanned: batch = batch.select(wanted) - if batch.num_rows or not local: + if batch.num_rows or not has_local: yield batch finally: reader.close() @@ -1455,15 +1534,17 @@ def scan_batches( """Scan a table, optionally restricted, and yield prepared Arrow batches. The restrictions are applied by SpiralDB, before any row reaches this - process, except a condition on a column its literals do not cover (``float16``): - that one is applied here, to the rows the other conditions select, and ``limit`` - after it, so rows are transferred that are not returned. Batches arrive in key order; their sizes are SpiralDB's. Each batch has - the types, metadata and nullability ``iter_batches`` documents. + process, except memberships too large for one expression and conditions + on columns its literals do not cover (``float16``): + those are applied here before ``limit``, so a scan may transfer additional rows. + For large memberships on integer, timestamp or date key columns, SpiralDB also + applies a range spanning the membership values. Batches arrive in key order + with the types, metadata and nullability ``iter_batches`` documents. Args: table_name: Plain table name (no dataset prefix). where: PROVISIONAL. Takes a ``Condition`` accepted by ``check_restriction``. - A row is read only if all equalities and ranges hold. SpiralDB applies + A row is read only if all equalities, memberships and ranges hold. SpiralDB applies ranges of integer, timestamp or date columns. limit: Read at most this many rows, the first in key order. asof: Read the table as of this version (a ``get_table_version`` value). diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index 534ed7b0d..a27f7b249 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -28,7 +28,7 @@ from collections.abc import Callable, Iterable, Iterator, Mapping from datetime import date, datetime, timedelta, timezone from types import MappingProxyType -from typing import Literal, NamedTuple, Never, TypeAlias, TypeVar +from typing import Any, Literal, NamedTuple, Never, TypeAlias, TypeVar import pyarrow as pa from typing_extensions import override @@ -400,7 +400,7 @@ def is_ordered_type(arrow_type: pa.DataType) -> bool: _MICROSECONDS_PER_COUNT = {"s": 1_000_000, "ms": 1_000, "us": 1} -def timestamp_count(value: datetime, arrow_type: pa.TimestampType) -> int: +def timestamp_count(value: datetime, arrow_type: pa.TimestampType[Any, Any]) -> int: """Return the count of ``arrow_type``'s unit since the epoch that is ``value``. Computed from the value's instant (an aware value) or wall time (a naive one) in @@ -803,7 +803,8 @@ def is_range_type(arrow_type: pa.DataType) -> bool: _RESTRICTION_FORMS = ( - "where takes equalities (column=value) and ranges (col(c) >= a, col(c) < b, " + "where takes equalities (column=value), membership (col(c).is_in(values)), " + "and ranges (col(c) >= a, col(c) < b, " "col(c).between(a, b)), all of which must hold" ) _TO_FILTER = ( @@ -816,7 +817,7 @@ def check_restriction(condition: Condition, schema: pa.Schema) -> None: """Check a source's restriction against its table's columns; convert nothing. A restriction is applied by the table system, so it takes only what the table - system tests as Orcapod would: a column equal to a value, and a range (``<``, + system tests as Orcapod would: equality, membership and a range (``<``, ``<=``, ``>``, ``>=``; ``between`` is two of them) of an integer, timestamp or date column (``is_range_type``). All must hold. A column equals one value; ranges add up and may select no row. Every value passes ``check_value_for_column``: exactly @@ -840,7 +841,9 @@ def check_restriction(condition: Condition, schema: pa.Schema) -> None: isinstance(node, Term) and not node.path.fields and not isinstance(node.value, ColumnOperand) - and (node.operator == EQUALS or node.operator in ORDER_COMPARISONS) + and ( + node.operator in (EQUALS, "is_in") or node.operator in ORDER_COMPARISONS + ) ): raise TypeError( f"{_RESTRICTION_FORMS}; {condition} has others. {_TO_FILTER}" @@ -858,18 +861,23 @@ def check_restriction(condition: Condition, schema: pa.Schema) -> None: for term in terms: column, value = term.path.column, term.value field = schema.field(column) - if term.operator != EQUALS and not is_range_type(field.type): + if term.operator in ORDER_COMPARISONS and not is_range_type(field.type): raise TypeError( f"column {column!r} holds {field.type}; where takes a range of an " f"integer, timestamp or date column only. {_TO_FILTER}" ) - try: - check_value_for_column(value, field, require_exact=True) - except TypeError as exc: - raise TypeError(f"column {column!r} {exc}") from exc + members = ( + value if term.operator == "is_in" and isinstance(value, tuple) else (value,) + ) + for member in members: + try: + check_value_for_column(member, field, require_exact=True) + except TypeError as exc: + raise TypeError(f"column {column!r} {exc}") from exc + if term.operator in (EQUALS, "is_in"): + _check_float_equality(column, member) if term.operator != EQUALS: continue - check_float_equalities({column: value}) held = equal_to.setdefault(column, value) if not _same_condition_value(held, value): raise ValueError( @@ -918,13 +926,18 @@ def check_float_equalities( elif isinstance(argument, Mapping): given.extend(argument.items()) for column, value in given: - if _matched_by_bits(value): - raise TypeError( - f"column {column!r}: where takes no equality to {value!r}. SpiralDB " - "matches -0.0 and NaN by their bits, while Orcapod counts -0.0 equal " - "to 0.0 and NaN equal to NaN, so which rows are read would depend on " - f"which of two equal values was kept (ITL-1480). {_TO_FILTER}" - ) + _check_float_equality(column, value) + + +def _check_float_equality(column: object, value: object) -> None: + """Refuse a literal for which deduplication could change the scan's matches.""" + if _matched_by_bits(value): + raise TypeError( + f"column {column!r}: where takes no equality to {value!r}. SpiralDB " + "matches -0.0 and NaN by their bits, while Orcapod counts -0.0 equal " + "to 0.0 and NaN equal to NaN, so which rows are read would depend on " + f"which of two equal values was kept (ITL-1480). {_TO_FILTER}" + ) # ----------------------------------------------------------------------------- @@ -1025,29 +1038,30 @@ def is_in(self, values: Iterable[object]) -> Condition: f"column {name!r}: is_in takes a collection of values, such as " f"[3, 7], not {values!r}" ) - unique: list[object] = [] - seen: set[object] = set() # hash keys consistent with _same_condition_value + unique: dict[object, object] = {} # keys consistent with _same_condition_value + member_type = None for given in values: value = _checked_value(name, given) - if unique and type(value) is not type(unique[0]): + member_type = member_type or type(value) + if type(value) is not member_type: + first = next(iter(unique.values())) raise TypeError( f"column {name!r}: is_in values are of one type; got " - f"{unique[0]!r} ({type(unique[0]).__name__}) and {value!r} " + f"{first!r} ({member_type.__name__}) and {value!r} " f"({type(value).__name__})" ) key = _condition_hash_key(value) - if key not in seen: - seen.add(key) - # One zero whatever was given first: -0.0 and 0.0 are one member, and - # the member kept (shown, saved) is 0.0, as the canonical form encodes it. - unique.append(0.0 if type(value) is float and value == 0.0 else value) + # A source must be able to refuse -0.0 even when 0.0 was given first. + # Equality, hashing, display and config still treat both zeros alike. + if key not in unique or (value == 0.0 and _matched_by_bits(value)): + unique[key] = value if not unique: raise ValueError( f"column {name!r}: is_in needs at least one value (no value matches " "no row)" ) return Condition._of_children( # pyright: ignore[reportPrivateUsage] # one module - (Term(self._path, "is_in", tuple(unique)),) + (Term(self._path, "is_in", tuple(unique.values())),) ) def between(self, low: object, high: object) -> Condition: @@ -1266,7 +1280,7 @@ class Condition: not. ``Condition.of`` builds the equalities ``where()`` takes; ``col(name)`` builds the rest; ``&``, ``|`` and ``~`` combine conditions. It knows nothing of a source, a limit or an identity. A source uses one to choose which of its rows are read - (``SpiralDBTableSource.where``: equalities and ranges), a restriction in no hash; + (``SpiralDBTableSource.where``: equalities, memberships and ranges), a restriction in no hash; the ``Filter`` operator takes one as a step of the pipeline, its identity the condition's ``canonical_form()`` (ITL-1374). @@ -1519,14 +1533,18 @@ def combined(self, other: Condition) -> Condition: children = list(self._root.children) # Kept nodes by their hash key (consistent with ``same_node``), so each new node # is compared only with the kept nodes of its key, not with every kept node. - kept_by_key: dict[object, list[Node]] = {} - for kept in children: - kept_by_key.setdefault(_node_hash_key(kept), []).append(kept) + kept_by_key: dict[object, list[int]] = {} + for index, kept in enumerate(children): + kept_by_key.setdefault(_node_hash_key(kept), []).append(index) for node in other._root.children: bucket = kept_by_key.setdefault(_node_hash_key(node), []) - if any(same_node(node, kept) for kept in bucket): + duplicate = next((i for i in bucket if same_node(node, children[i])), None) + if duplicate is not None: + # Keep a signed-zero membership available for source validation. + if _membership_has_negative_zero(node): + children[duplicate] = node continue - bucket.append(node) + bucket.append(len(children)) children.append(node) return Condition._of_children(tuple(children)) @@ -1773,6 +1791,16 @@ def _same_term(a: Term, b: Term) -> bool: return _same_condition_value(a.value, b.value) +def _membership_has_negative_zero(node: Node) -> bool: + """Return whether the membership includes a negative zero supplied by the caller.""" + return ( + isinstance(node, Term) + and node.operator == "is_in" + and isinstance(node.value, tuple) + and any(v == 0.0 and _matched_by_bits(v) for v in node.value) + ) + + def _terms_of(node: Node) -> Iterator[Term]: """Yield the terms of ``node``, depth first, in the order given.""" if isinstance(node, Term): @@ -1895,13 +1923,10 @@ def _node_text(node: Node, canonical: bool = False) -> str: return f"{path} {node.operator} {value.path.text()}" if node.operator == "is_in" and isinstance(value, tuple): if canonical: - value = tuple( - _canonical_display(v) - for v in sorted( - value, key=lambda v: json.dumps(_canonical_value(v)) - ) - ) - return f"{path} in [{', '.join(repr(v) for v in value)}]" + value = sorted(value, key=lambda v: json.dumps(_canonical_value(v))) + return ( + f"{path} in [{', '.join(repr(_canonical_display(v)) for v in value)}]" + ) if canonical: value = _canonical_display(value) if node.operator == EQUALS: diff --git a/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py index 800e88e9e..e1b967832 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py +++ b/tests/test_core/sources/test_spiraldb_table_source_float_equalities.py @@ -343,3 +343,12 @@ def test_fake_nan_equality_requires_matching_bits( fake_spiral_sdk.column("v"), fake_spiral_sdk.literal(value, arrow_type) ) assert table.scan(filter=predicate).to_table()["id"].to_pylist() == [row] + + +def test_half_float_membership_filters_before_limit_with_spiraldb_equality(project): + source = _source(limit=2).where(col("h").is_in([0.0, 0.5, 1.5]), col("id") >= 0) + + assert _ids(source) == [1, 3] + (scan,) = fake_spiral_sdk.scan_log + assert scan.limit is None + assert scan.filter.terms[0][0] == "id" diff --git a/tests/test_core/sources/test_spiraldb_table_source_live.py b/tests/test_core/sources/test_spiraldb_table_source_live.py index f348b5c40..182dd101e 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_live.py +++ b/tests/test_core/sources/test_spiraldb_table_source_live.py @@ -186,7 +186,8 @@ def _first_prefix() -> tuple[SpiralDBTableSource, list[Any]]: first = _live_source(limit=1) row = first.as_table().to_pylist()[0] prefix_key = {c: row[c] for c in first.keys()[0] if c != _TIME_COLUMN} - prefix = _live_source(max_rows=None).where(prefix_key) + source = _live_source(max_rows=None) + prefix = source.where(prefix_key) if prefix_key else source times: list[Any] = sorted( t for t in prefix.as_table().column(_TIME_COLUMN).to_pylist() if t is not None ) @@ -246,3 +247,27 @@ def test_an_empty_window_reads_no_row_with_the_full_schema(): table = empty.as_table(all_info=True) assert table.num_rows == 0 assert table.schema == prefix.as_table(all_info=True).schema + + +def test_membership_reads_the_same_rows_in_either_value_order(): + prefix, times = _first_prefix() + members = [times[2], times[4], times[6]] + whole = prefix.as_table(all_info=True) + kind = whole.schema.field(_TIME_COLUMN).type + expected = whole.filter( + pc.is_in(whole[_TIME_COLUMN], value_set=pa.array(members, type=kind)) + ) + first, second = [ + prefix.where(col(_TIME_COLUMN).is_in(values)) + for values in (members, list(reversed(members))) + ] + + assert expected.num_rows >= len(members) + assert first.condition == second.condition + assert hash(first.condition) == hash(second.condition) + assert first.to_config()["where"] == second.to_config()["where"] + for source in (first, second): + assert source.as_table(all_info=True).equals(expected) + assert source.content_hash() == prefix.content_hash() + assert source.pipeline_hash() == prefix.pipeline_hash() + assert source.source_id == prefix.source_id diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index cabf33754..141bef6df 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -22,7 +22,7 @@ import pytest from orcapod import PipelineJob, function_pod -from orcapod.databases import DeltaTableDatabase +from orcapod.databases import DeltaTableDatabase, SpiralDBKeyedConnector from orcapod.errors import InconsistentSourceError, RestrictedAggregationWarning from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.restrictions import restrictions_in_force @@ -2641,14 +2641,13 @@ def test_a_direct_label_with_no_collision_is_not_numbered(self, project): assert set(restrictions_in_force([second, first])) == {"a", "b"} -class TestWhereTakesEqualitiesAndRanges: - """``where`` refuses every condition but equalities and ranges, pointing to +class TestWhereRefusesUnsupportedConditions: + """``where`` refuses conditions it cannot apply, pointing to ``filter`` (ITL-1374, ITL-998).""" @pytest.mark.parametrize( "build", [ - lambda: col("subject_id").is_in(["m1", "m2"]), lambda: col("note").is_null(), lambda: (col("subject_id") == "m1") | (col("subject_id") == "m2"), lambda: ~(col("subject_id") == "m1"), @@ -2659,7 +2658,6 @@ class TestWhereTakesEqualitiesAndRanges: lambda: (col("timestamp") >= 3) & ~(col("timestamp") < 5), ], ids=[ - "is_in", "null test", "or", "not", @@ -2695,4 +2693,116 @@ def test_an_equality_built_with_col_is_taken(self, project): def test_the_constructor_refuses_it_too(self, project): with pytest.raises(TypeError, match=r"equalities .* and ranges"): - _source(where=col("timestamp").is_in([3])) + _source(where=col("note").is_null()) + + +class TestMembership: + def test_scan_pushes_membership_with_equality_range_and_limit(self, project): + source = _source(limit=2) + first = col("timestamp").is_in([5, 4, 2, 1]) + second = col("timestamp").is_in([1, 2, 4, 5, 4]) + restricted = [ + source.where(condition, col("timestamp") > 1, subject_id="m2") + for condition in (first, second) + ] + whole = _rows_by_key(_source()) + fake_spiral_sdk.scan_log.clear() + + for member_source in restricted: + assert _rows_by_key(member_source) == {t: whole[t] for t in (4, 5)} + assert member_source.content_hash() == source.content_hash() + assert member_source.pipeline_hash() == source.pipeline_hash() + assert member_source.source_id == source.source_id + assert first == second + assert hash(first) == hash(second) + assert "timestamp in [" in first.text() + assert restricted[0].to_config()["where"] == restricted[1].to_config()["where"] + assert len(fake_spiral_sdk.scan_log) == 2 + for scan in fake_spiral_sdk.scan_log: + assert scan.limit == 2 + assert scan.filter.disjunctions + assert scan.filter.equalities == [("subject_id", "m2")] + + def test_constructor_and_run_summary_keep_membership(self, project, tmp_path): + condition = col("subject_id").is_in(["m2", "m1"]) + source = _source(where=condition, source_id="events", tag_only_columns=True) + job = TestRunsAndSavedJobs._job(tmp_path / "membership", source, []) + assert job.run().conditions == {"events": condition} + config = source.to_config() + assert Condition.from_config(config["where"]) == condition + + @pytest.mark.parametrize( + ("column", "values", "error", "message"), + [ + ("timestamp", [1, -1], TypeError, "unsigned"), + ("timestamp", [True], TypeError, "int"), + ("timestamp", [], ValueError, "at least one"), + ("timestamp", [1, None], ValueError, "None is refused"), + ("amplitude", [0.5, 0.1], TypeError, "exactly"), + ("amplitude", [0.0, -0.0], TypeError, "ITL-1480"), + ("amplitude", [-0.0, 0.0], TypeError, "ITL-1480"), + ("amplitude", [0.5, math.nan], TypeError, "ITL-1480"), + ], + ) + def test_every_member_obeys_equality_rules( + self, project, column, values, error, message + ): + source = _source() + with pytest.raises(error, match=message): + source.where(col(column).is_in(values)) + assert fake_spiral_sdk.scan_log == [] + + def test_combining_equal_memberships_cannot_hide_negative_zero(self, project): + positive = col("amplitude").is_in([0.0, 1.5]) + negative = col("amplitude").is_in([1.5, -0.0]) + with pytest.raises(TypeError, match="ITL-1480"): + _source(where=positive & negative) + + @pytest.mark.parametrize("collection", [list, tuple, set, frozenset]) + def test_mapping_and_keyword_collections_use_membership(self, project, collection): + source = _source() + values = collection([4, 2]) + from_mapping = _source(where={"timestamp": values}) + from_keywords = source.where(timestamp=values) + explicit = source.where(col("timestamp").is_in([2, 4])) + + for restricted in (from_mapping, from_keywords): + assert _timestamps(restricted) == [2, 4] + assert restricted.condition == explicit.condition + assert restricted.to_config()["where"] == explicit.to_config()["where"] + + def test_large_membership_bounds_the_scan_and_filters_before_limit(self, project): + source = _source(limit=2) + values = [1, 4, 5, *range(10, 1007)] + first, second = [ + source.where(col("timestamp").is_in(members), col("timestamp") > 1) + for members in (values, list(reversed(values))) + ] + + assert first.to_config()["where"] == second.to_config()["where"] + for restricted in (first, second): + assert _timestamps(restricted) == [4, 5] + assert len(fake_spiral_sdk.scan_log) == 2 + for scan in fake_spiral_sdk.scan_log: + assert scan.limit is None + assert not scan.filter.disjunctions + assert [ + (name, literal.value, op) for name, literal, op in scan.filter.terms + ] == [ + ("timestamp", 1, ">="), + ("timestamp", 1006, "<="), + ("timestamp", 1, ">"), + ] + + def test_large_membership_filters_an_unprojected_data_column(self, project): + values = ["n4", *(f"missing{i}" for i in range(999))] + condition = col("note").is_in(values) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + table = connector.lookup_table("event") + (batch,) = list( + table.scan_batches(where=condition, columns=["timestamp"], limit=1) + ) + + assert batch.column("timestamp").to_pylist() == [4] + assert batch.schema.names == ["timestamp"] + assert set(fake_spiral_sdk.count_log[-1].columns or ()) == {"timestamp", "note"} diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 1d8c56b7e..d0e256694 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -784,6 +784,7 @@ class FakePredicate: """Comparisons a row must all match: ``(column, literal, operator)``.""" terms: tuple[tuple[str, _Literal, str], ...] + disjunctions: tuple[tuple[FakePredicate, FakePredicate], ...] = () @property def equalities(self) -> list[tuple[str, Any]]: @@ -846,7 +847,50 @@ def gte(left: _Column, right: _Literal) -> FakePredicate: def and_(left: FakePredicate, right: FakePredicate) -> FakePredicate: """Stand in for ``spiral.and_``.""" - return FakePredicate(left.terms + right.terms) + return FakePredicate( + left.terms + right.terms, left.disjunctions + right.disjunctions + ) + + +def or_(left: FakePredicate, right: FakePredicate) -> FakePredicate: + """Stand in for the SDK's disjunction.""" + return FakePredicate((), ((left, right),)) + + +def _predicate_mask(rows: pa.Table, predicate: FakePredicate) -> pa.BooleanArray: + """Evaluate the fake scan expression against the unprojected table.""" + mask = pa.array([True] * rows.num_rows, pa.bool_()) + for name, wanted, op in predicate.terms: + if rows.schema.field(name).type != wanted.type: + raise SpiralError( + "scan filter is unsupported: Comparison requires equal dtypes, got " + f"{rows.schema.field(name).type} and {wanted.type}" + ) + # Temporal values as their counts: a date64 may be off midnight. + stored: Any = rows.column(name) + given: Any = pa.array([wanted.value], wanted.type) + if pa.types.is_temporal(wanted.type): + width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() + stored, given = stored.cast(width), given.cast(width) + elif op == "==" and pa.types.is_floating(wanted.type): + # Read raw bits before to_pylist() can quiet a signaling NaN. + bits = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[ + wanted.type.bit_width + ] + stored = pa.chunked_array( + [chunk.view(bits) for chunk in stored.chunks], bits + ) + given = given.view(bits) + values, (value,) = stored.to_pylist(), given.to_pylist() + matches = pa.array( + [v is not None and _compares(v, op, value) for v in values], pa.bool_() + ) + mask = pc.and_(mask, matches) + for left, right in predicate.disjunctions: + mask = pc.and_( + mask, pc.or_(_predicate_mask(rows, left), _predicate_mask(rows, right)) + ) + return mask # -------------------------------------------------------------------------------- the client @@ -952,34 +996,8 @@ def scan( ) -> FakeScan: """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``).""" rows = self._store.read(self.resource_id, self._version) - for name, wanted, op in filter.terms if filter else (): - if rows.schema.field(name).type != wanted.type: - raise SpiralError( - "scan filter is unsupported: Comparison requires equal dtypes, got " - f"{rows.schema.field(name).type} and {wanted.type}" - ) - # Temporal values as their counts: a date64 may be off midnight. - stored: Any = rows.column(name) - given: Any = pa.array([wanted.value], wanted.type) - if pa.types.is_temporal(wanted.type): - width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() - stored, given = stored.cast(width), given.cast(width) - elif op == "==" and pa.types.is_floating(wanted.type): - # Read raw bits before to_pylist() can quiet a signaling NaN. - bits = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[ - wanted.type.bit_width - ] - stored = pa.chunked_array( - [chunk.view(bits) for chunk in stored.chunks], bits - ) - given = given.view(bits) - values, (value,) = stored.to_pylist(), given.to_pylist() - rows = rows.filter( - pa.array( - [v is not None and _compares(v, op, value) for v in values], - pa.bool_(), - ) - ) + if filter is not None: + rows = rows.filter(_predicate_mask(rows, filter)) if columns is not None: rows = rows.select(columns) if limit is not None: @@ -1189,6 +1207,7 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: gt=gt, gte=gte, and_=and_, + or_=or_, ) From cf634607cf5cecacda28ec4419cac12da30d5db6 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 15:17:40 -0800 Subject: [PATCH 02/12] fix(spiraldb): harden source membership restrictions --- changelog.d/ITL-1986.md | 4 + docs/concepts/sources.md | 20 +++-- .../core/sources/spiraldb_table_source.py | 6 +- .../databases/spiraldb_keyed/connector.py | 35 +++++--- src/orcapod/types/condition.py | 33 +++---- .../test_spiraldb_table_source_where.py | 85 ++++++++++++++++++- tests/test_types_condition_tree.py | 6 +- 7 files changed, 148 insertions(+), 41 deletions(-) diff --git a/changelog.d/ITL-1986.md b/changelog.d/ITL-1986.md index 7ca8bf8fd..551a957e0 100644 --- a/changelog.d/ITL-1986.md +++ b/changelog.d/ITL-1986.md @@ -1,3 +1,7 @@ ### Added - Restrict a keyed SpiralDB source to a set of values with `where(col(column).is_in(values))`. The restriction preserves source, pipeline and record identities. + +### Known limitations + +- Large, sparse memberships can scan a wide key range and transfer many nonmatching rows for local filtering. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 9707b7c94..135deff4a 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -834,8 +834,10 @@ late = readings.where(col("sensor_id").is_in([106, 107]), col("timestamp") >= 1_ A filter directly over a source reads every row the source reads (the whole table, or what the source's own `where` and `limit` select) and then filters them; its condition is never -pushed into the source. `where` reads only the matching rows. On a large table, keep `where` on the source for speed and put the same -`filter` in the pipeline for its identity: the rows are the same, and the restriction rules +pushed into the source. `where` returns only matching rows. A pushed predicate can +reduce transfer, while a locally checked membership can transfer nonmatching rows. +For an equality that SpiralDB can push down on a large table, use `where` at the source and +the same `filter` in the pipeline for its identity: the rows are the same, and the restriction rules above apply to the source. This holds for equalities on integer, string, bytes, bool, date and timestamp columns, on a source without a `limit`. With a `limit` it does not: the source reads the first rows that match the `where`, so the `filter` sees other rows than it would @@ -916,16 +918,18 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **Set membership.** Use `where(col("sensor_id").is_in([106, 107]))` to read rows with any of the named values. You can combine membership with equalities, ranges or other memberships. Mapping and keyword values can also be lists, tuples, sets or - frozensets, such as `where(sensor_id=[106, 107])`. The collection must contain at least one value and cannot contain - `None`. The equality type and exactness rules apply to every member. Duplicate values - and value order have no effect on the selected rows or saved condition. The SDK + frozensets, such as `where(sensor_id=[106, 107])`. The collection must contain at least + one value and cannot contain `None`. The equality type and exactness rules apply to every + member. Duplicate values and value order have no effect on the selected rows or how + the membership is displayed or saved. The SDK has no `IN` predicate, so Orcapod sends a balanced OR of equalities in one scan, with a shared budget of up to 512 membership equalities. For larger memberships or literals the SDK cannot represent, such as `float16` values, Orcapod checks membership locally before applying the limit. On an integer, timestamp or date - key, it also pushes the range from the least to greatest member into the scan. - A wide range or a membership with no supported range can transfer many rows that - the source does not return. + key, it can also push the range from the least to greatest member into the scan. + A wide range can transfer many nonmatching rows. When a locally checked membership + has no usable range or other pushed predicate, the source may scan the entire table. + `max_rows` caps matching output rows. It does not cap the rows SpiralDB transfers. - **Exact values.** An integer column takes a Python `int`, a float column takes a Python `float`, a date column takes a `datetime.date`, and a timestamp column takes a `datetime.datetime`. A float column without a logical type also takes a Python `int`. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index f80ad8f40..0c1108140 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -619,9 +619,9 @@ def where( SDK supports the literals and the expression has room. The scan has a shared budget of up to 512 membership equalities. For larger memberships or unsupported literals (for example, ``float16``), Orcapod checks membership - locally before applying ``limit``. An integer, timestamp or date key also gets - a scan range from its least to greatest member. The scan can transfer - extra rows, especially when the member values are far apart. + locally before applying ``limit``. An integer, timestamp or date key can also + use a scan range from its least to greatest member. When no predicate can push + down, the scan may transfer the entire table. ``max_rows`` caps matching output. For now, ``where()`` refuses float equality values that the column's Arrow type cannot hold exactly. For example, a plain float32 column accepts diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index eb6f6d589..3d24028e5 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -86,7 +86,7 @@ _SCAN_BATCH_ROWS = 8_192 # ScanDAL accepts up to 4,096 expression nodes. One equality leaf and its OR # consume five nodes. Reserve additional space for regular and fallback predicates. -_MAX_MEMBERSHIP_EQUALITIES = 512 +_MAX_SCAN_COMPARISONS = 512 _LIST_TIMEOUT_S = 60 _NO_WRITES = ( "a plain SpiralDBKeyedConnector only reads SpiralDB tables; nothing was written. A job " @@ -906,7 +906,9 @@ def scan_batches( scanned = [n for n in reading.found.names if n in needed] reading = reading.projected(scanned) predicates: list[Any] = [] - membership_budget = max(0, _MAX_MEMBERSHIP_EQUALITIES - 2 * len(terms)) + membership_budget = max(0, _MAX_SCAN_COMPARISONS - 2 * len(terms)) + pushed_comparisons = sum(term.operator != "is_in" for term in terms) + fallback_bounds: dict[str, tuple[Any, Any]] = {} key_columns = self.key_columns # Every equality compared here, in the order given: two of one column both hold. local: list[tuple[str, object]] = [] @@ -926,6 +928,7 @@ def scan_batches( ) ) membership_budget -= len(value) + pushed_comparisons += len(value) continue local_memberships.append( ( @@ -935,12 +938,11 @@ def scan_batches( ) if column in key_columns and is_range_type(column_type): ordered = cast("tuple[Any, ...]", value) - predicates.extend( - ( - _range_predicate(column, ">=", min(ordered), column_type), - _range_predicate(column, "<=", max(ordered), column_type), - ) - ) + low, high = min(ordered), max(ordered) + if column in fallback_bounds: + previous_low, previous_high = fallback_bounds[column] + low, high = max(low, previous_low), min(high, previous_high) + fallback_bounds[column] = low, high continue if term.operator != EQUALS: predicates.append( @@ -956,6 +958,19 @@ def scan_batches( local.append((column, value)) continue predicates.append(sp.eq(sp.column(column), literal)) + # The bounds only narrow the candidate scan. Skip them if the required + # comparisons already use the budget, and still check every membership locally. + for column, (low, high) in fallback_bounds.items(): + if pushed_comparisons + 2 > _MAX_SCAN_COMPARISONS: + break + column_type = reading.found.field(column).type + predicates.extend( + ( + _range_predicate(column, ">=", low, column_type), + _range_predicate(column, "<=", high, column_type), + ) + ) + pushed_comparisons += 2 predicate = _balanced_predicate(predicates, sp.and_) has_local = bool(local or local_memberships) with connector._service_call("read", self._table_name): # pyright: ignore[reportPrivateUsage] # owns the handle @@ -1537,8 +1552,8 @@ def scan_batches( process, except memberships too large for one expression and conditions on columns its literals do not cover (``float16``): those are applied here before ``limit``, so a scan may transfer additional rows. - For large memberships on integer, timestamp or date key columns, SpiralDB also - applies a range spanning the membership values. Batches arrive in key order + For large memberships on integer, timestamp or date key columns, SpiralDB can + also apply a range spanning the membership values. Batches arrive in key order with the types, metadata and nullability ``iter_batches`` documents. Args: diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index a27f7b249..207ff9245 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -112,8 +112,8 @@ class Term(NamedTuple): """One requirement: a column (or field), an operator and a value. The value is a condition value (``==``, ``!=`` and the order comparisons), a - ``ColumnOperand`` (a comparison of two columns), a tuple of condition values, all of - one type, unique, in the order first given (``is_in``), or ``None`` (the null tests). + ``ColumnOperand`` (a comparison of two columns), a tuple of unique condition values in + the order first given (``is_in``), or ``None`` (the null tests). ``between(lo, hi)`` is the two terms ``>= lo`` and ``<= hi``. Compare terms with ``same_node``, never ``==``: ``0.0`` and ``-0.0`` are one value, @@ -1022,7 +1022,8 @@ def is_in(self, values: Iterable[object]) -> Condition: not taken as a collection of characters. Args: - values: One or more condition values, all of one type. + values: One or more values of one type, or a mixture of integers and floats. + The consumer checks each literal against the column type. Returns: The membership condition. @@ -1030,7 +1031,7 @@ def is_in(self, values: Iterable[object]) -> Condition: Raises: ValueError: If ``values`` is empty or holds ``None``. TypeError: If ``values`` is a string or bytes, or a value is not exactly of - a supported type, or the values are of several types. + a supported type, or the values mix types other than integers and floats. """ name = self._path.text() if isinstance(values, (str, bytes)) or not isinstance(values, Iterable): @@ -1043,10 +1044,12 @@ def is_in(self, values: Iterable[object]) -> Condition: for given in values: value = _checked_value(name, given) member_type = member_type or type(value) - if type(value) is not member_type: + if type(value) is not member_type and not ( + member_type in (int, float) and type(value) in (int, float) + ): first = next(iter(unique.values())) raise TypeError( - f"column {name!r}: is_in values are of one type; got " + f"column {name!r}: is_in values must be of one type or a mix of int and float; got " f"{first!r} ({member_type.__name__}) and {value!r} " f"({type(value).__name__})" ) @@ -1574,7 +1577,9 @@ def __or__(self, other: Condition | ColumnRef) -> Condition: if not any(same_node(option, kept) for kept in options): options.append(option) if len(options) == 1: - return self # a | a is a: one alternative is no disjunction + # Preserve signed-zero membership evidence when equivalent operands + # simplify to one condition, just as when AND deduplicates them. + return self.combined(other) return Condition._of_children((AnyOf(tuple(options)),)) def __invert__(self) -> Condition: @@ -1616,7 +1621,7 @@ def text(self) -> str: Equalities read ``column=value``; other terms ``t >= 1.0``, ``unit in [3, 7]``, ``rate is null``; ``|`` and ``~`` read ``(a or b)`` and - ``not (a)``. In the order given; display only. + ``not (a)``. Terms keep their given order and membership values appear in canonical order. """ if self.is_empty: return "no condition" @@ -1628,8 +1633,8 @@ def canonical_text(self) -> str: The children of every ``all`` and ``any`` and the values of every ``is_in`` are in the order ``canonical_form`` sorts them, so ``a & b`` and ``b & a``, or ``is_in([3, 7])`` and ``is_in([7, 3])``, read identically. For a display that - must not follow how the condition was written (``explain()``); ``text()`` - keeps the order given. + must not follow how the terms were written (``explain()``); ``text()`` + keeps the order of distinct terms. """ if self.is_empty: return "no condition" @@ -1912,8 +1917,7 @@ def _canonical_display(value: object) -> object: def _node_text(node: Node, canonical: bool = False) -> str: - """Return ``node`` as words (display only); ``canonical`` sorts children and - ``is_in`` values as ``canonical_form`` does.""" + """Return ``node`` as words with sorted membership values and optional term sorting.""" if isinstance(node, Term): path = node.path.text() value = node.value @@ -1922,10 +1926,9 @@ def _node_text(node: Node, canonical: bool = False) -> str: if isinstance(value, ColumnOperand): return f"{path} {node.operator} {value.path.text()}" if node.operator == "is_in" and isinstance(value, tuple): - if canonical: - value = sorted(value, key=lambda v: json.dumps(_canonical_value(v))) + members = sorted(value, key=lambda v: json.dumps(_canonical_value(v))) return ( - f"{path} in [{', '.join(repr(_canonical_display(v)) for v in value)}]" + f"{path} in [{', '.join(repr(_canonical_display(v)) for v in members)}]" ) if canonical: value = _canonical_display(value) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 141bef6df..3cb82d459 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -16,6 +16,7 @@ from collections.abc import Callable from pathlib import Path from typing import Any, cast +from unittest.mock import Mock import numpy as np import pyarrow as pa @@ -23,7 +24,12 @@ from orcapod import PipelineJob, function_pod from orcapod.databases import DeltaTableDatabase, SpiralDBKeyedConnector -from orcapod.errors import InconsistentSourceError, RestrictedAggregationWarning +from orcapod.errors import ( + InconsistentSourceError, + InputValidationError, + RestrictedAggregationWarning, + SourceTooLargeError, +) from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.restrictions import restrictions_in_force from orcapod.core.sources.base import RootSource @@ -2789,9 +2795,9 @@ def test_large_membership_bounds_the_scan_and_filters_before_limit(self, project assert [ (name, literal.value, op) for name, literal, op in scan.filter.terms ] == [ + ("timestamp", 1, ">"), ("timestamp", 1, ">="), ("timestamp", 1006, "<="), - ("timestamp", 1, ">"), ] def test_large_membership_filters_an_unprojected_data_column(self, project): @@ -2806,3 +2812,78 @@ def test_large_membership_filters_an_unprojected_data_column(self, project): assert batch.column("timestamp").to_pylist() == [4] assert batch.schema.names == ["timestamp"] assert set(fake_spiral_sdk.count_log[-1].columns or ()) == {"timestamp", "note"} + + +def test_membership_order_does_not_change_display(project, tmp_path): + root = _source(source_id="events", tag_only_columns=True) + a = root.where(timestamp=[4, 2, 4]) + b = root.where(timestamp=[2, 4]) + summaries = [ + TestRunsAndSavedJobs._job(tmp_path / f"store{i}", source, []).run() + for i, source in enumerate((a, b)) + ] + lines = [ + next( + line for line in repr(summary).splitlines() if "restricted sources:" in line + ) + for summary in summaries + ] + assert (a.condition.text(), lines[0]) == (b.condition.text(), lines[1]) + assert a.condition.text() == "timestamp in [2, 4]" + + +def test_membership_accepts_each_exact_float_column_literal(project): + source = _source() + assert _timestamps(source.where(amplitude=1)) == [] + assert _timestamps(source.where(amplitude=1.5)) == [1] + explicit = source.where(col("amplitude").is_in([1.5, 1])) + shorthand = source.where(amplitude=[1, 1.5]) + assert _timestamps(shorthand) == _timestamps(explicit) == [1] + assert shorthand.condition == explicit.condition + assert hash(shorthand.condition) == hash(explicit.condition) + assert ( + shorthand.condition.canonical_form() + != col("amplitude").is_in([1.0, 1.5]).canonical_form() + ) + with pytest.raises(InputValidationError, match="int"): + source.filter(explicit.condition) + assert Condition.from_config(shorthand.condition.to_config()) == explicit.condition + with pytest.raises(TypeError, match="int"): + source.where(timestamp=[1, 1.5]) + + +def test_equivalent_or_memberships_cannot_hide_negative_zero(project): + positive = col("amplitude").is_in([0.0, 1.5]) + negative = col("amplitude").is_in([-0.0, 1.5]) + source = _source() + bound = col("timestamp") > 0 + for condition in ( + positive | negative, + negative | positive, + (positive & bound) | (negative & bound), + (negative & bound) | (positive & bound), + ): + with pytest.raises(TypeError, match="ITL-1480"): + source.where(condition) + + +def test_fallback_ranges_respect_expression_cap(project, monkeypatch): + calls = [] + for name in ("gte", "lte", "and_"): + instrumented = Mock(wraps=getattr(fake_spiral_sdk.fake_module, name)) + monkeypatch.setattr(fake_spiral_sdk.fake_module, name, instrumented) + calls.append(instrumented) + source = _source().where(*(col("timestamp").is_in([4, i]) for i in range(10, 1060))) + assert _timestamps(source) == [4] + assert sum(mock.call_count for mock in calls) <= 4096 + assert [mock.call_count for mock in calls] == [1, 1, 1] + + +def test_non_range_membership_cap_counts_matching_rows(project): + misses = [f"missing{i}" for i in range(513)] + source = _source(max_rows=1).where(note=["n4", *misses]) + assert _timestamps(source) == [4] + scan = fake_spiral_sdk.scan_log[-1] + assert scan.filter is None and scan.limit is None + with pytest.raises(SourceTooLargeError): + _timestamps(_source(max_rows=1).where(note=["n4", "n5", *misses])) diff --git a/tests/test_types_condition_tree.py b/tests/test_types_condition_tree.py index 976c36ba8..5096a05c9 100644 --- a/tests/test_types_condition_tree.py +++ b/tests/test_types_condition_tree.py @@ -127,7 +127,7 @@ class TestRefusedWhenBuilt: (lambda: Condition.of(u=[3, 7]), TypeError, r"is_in"), (lambda: col("u").is_in([]), ValueError, "at least one"), (lambda: col("u").is_in([3, None]), ValueError, "None"), - (lambda: col("u").is_in([3, 7.0]), TypeError, "one type"), + (lambda: col("u").is_in([3, True]), TypeError, "one type"), (lambda: col("u").is_in("ab"), TypeError, "collection"), (lambda: col("u").is_in(3), TypeError, "collection"), # pyright: ignore[reportArgumentType] # the refusal under test (lambda: col("t").between(1, 2.0), TypeError, "one type"), @@ -772,7 +772,7 @@ def test_two_values_for_one_column_load_as_saved(self, children): "column": "k", "fields": [], "op": "is_in", - "values": [1, {"float": "nan"}], + "values": [1, True], }, TypeError, ), @@ -1005,7 +1005,7 @@ def test_two_orders_read_the_same(self, first, second): def test_the_words_are_those_of_text(self): condition = col("u").is_in([3, 7]) & (col("t") >= 1.0) assert condition.canonical_text() == "t >= 1.0, u in [3, 7]" - assert condition.text() == "u in [3, 7], t >= 1.0" # text keeps the order given + assert condition.text() == "u in [3, 7], t >= 1.0" # text keeps the term order assert Condition().canonical_text() == "no condition" From 5953fe9318133374139214b3276e680d980fab82 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 15:31:03 -0800 Subject: [PATCH 03/12] fix(spiraldb): validate nullability after local membership --- .../databases/spiraldb_keyed/connector.py | 19 ++++++++++---- tests/test_databases/test_spiraldb_reading.py | 25 ++++++++++++++++++- 2 files changed, 38 insertions(+), 6 deletions(-) diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 3d24028e5..0335c01b9 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -988,11 +988,9 @@ def scan_batches( batch = next(reader, None) if batch is None: return - batch = reading.prepare(batch) + batch = reading.prepare(batch, memberships=local_memberships) for column, value in local: batch = batch.filter(_equals(batch.column(column), value)) - for column, values in local_memberships: - batch = batch.filter(_membership_mask(batch.column(column), values)) if has_local and left is not None: batch = batch.slice(0, left) left -= batch.num_rows @@ -1101,8 +1099,17 @@ def projected(self, names: Sequence[str]) -> _Reading: duplicate._accepted = duplicate.found return duplicate - def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: - """Return a scanned batch under ``schema``, its non-null columns checked. + def prepare( + self, + batch: pa.RecordBatch, + *, + memberships: Sequence[tuple[str, pa.Array[Any]]] = (), + ) -> pa.RecordBatch: + """Filter a scanned batch, validate the kept rows and return them under ``schema``. + + Args: + batch: A batch as returned by the SDK. + memberships: Local membership conditions and their Arrow value sets. Raises: TableSchemaError: If the batch's columns are not the snapshot's. @@ -1119,6 +1126,8 @@ def prepare(self, batch: pa.RecordBatch) -> pa.RecordBatch: table=self._table, ) self._accepted = batch.schema + for column, values in memberships: + batch = batch.filter(_membership_mask(batch.column(column), values)) with _about_table(self._table): check_no_nulls(batch, self._paths) if batch.schema.equals(self.schema, check_metadata=True): diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 2e659af5b..81b7ab0f3 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -36,7 +36,7 @@ ) from orcapod.nodes import FunctionJobNode from orcapod.sources import DictSource, SpiralDBTableSource -from orcapod.types import ColumnInfo, Condition +from orcapod.types import ColumnInfo, Condition, col from tests.test_databases import fake_spiral_sdk as fake _ITEM = pa.field("item", pa.float32(), False) @@ -162,6 +162,29 @@ def test_a_null_in_a_recorded_column_is_refused(project: Any) -> None: list(SpiralDBKeyedConnector("p").scan_batches("units")) +def test_local_membership_checks_nullability_only_on_matching_rows( + project: Any, +) -> None: + nulls = _rows().slice(0, 1) + nulls = nulls.set_column( + nulls.schema.get_field_index("z"), + pa.field("z", pa.float64()), + pa.array([None], pa.float64()), + ) + project.table("default.units").write(nulls) + fake.migrate("p", {"units": _WRITTEN}) + misses = [f"absent{i}" for i in range(513)] + with SpiralDBKeyedConnector("p") as connector: + rows = pa.Table.from_batches( + connector.scan_batches("units", where=col("k1").is_in(["b", *misses])) + ) + assert rows["k1"].to_pylist() == ["b"] + assert rows.schema.field("z").nullable is False + + with pytest.raises(NullInNonNullableColumnError, match="units.*z|z.*units"): + list(connector.scan_batches("units", where=col("k1").is_in(["a", *misses]))) + + # ------------------------------------------------------------ a table that is not recorded From e66f913bb2bbb935416584679a64f6e54a7d27ea Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 16:21:15 -0800 Subject: [PATCH 04/12] fix(spiraldb): enforce membership limit and float refusals --- docs/concepts/sources.md | 3 +- .../core/sources/spiraldb_table_source.py | 20 +++---- .../databases/spiraldb_keyed/connector.py | 29 ++++++++--- src/orcapod/types/condition.py | 23 ++++---- .../test_spiraldb_table_source_where.py | 52 +++++++++++++++++++ tests/test_databases/test_spiraldb_reading.py | 24 +++++++++ 6 files changed, 125 insertions(+), 26 deletions(-) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 135deff4a..b02dada42 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -942,7 +942,8 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **The table system's equality.** Each equality or membership value uses SpiralDB's own equality. For a float column, `0.0` does not select the `-0.0` rows (seen on the service, not documented by it). An - equality to `-0.0` or a NaN raises `TypeError` for now and points to `filter`. SpiralDB matches + equality or membership containing `-0.0` or a NaN raises `TypeError` and points to + `filter`. SpiralDB matches them by their bits, while Orcapod counts `-0.0` equal to `0.0` and NaN equal to NaN, so the rows read would depend on which of two equal values a condition kept. ITL-1480 tracks revisiting the float refusals. SpiralDB cannot compare a `float16` column, so Orcapod reads the rows the diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 0c1108140..2e547c203 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -382,7 +382,12 @@ def __init__( raise ValueError( f"{name} must be a positive integer or None, got {value!r}" ) - # What needs no table (the values' types, None) is checked before connecting. + location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" + # Check the original literals before merging or connecting to the table. + try: + check_float_equalities(where) + except TypeError as exc: + raise TypeError(f"{location}, table {table_name!r}: {exc}") from exc if isinstance(where, Condition): requested = where else: @@ -413,8 +418,6 @@ def __init__( self._tags_as_data: dict[str, str] = dict(tags_as_data) if tags_as_data else {} if self._tags_as_data: warn_provisional_tags_as_data("SpiralDBTableSource") - location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" - try: try: table = self._connector().lookup_table(table_name) @@ -627,8 +630,8 @@ def where( type cannot hold exactly. For example, a plain float32 column accepts ``0.5`` and ``1`` and raises ``TypeError`` for ``0.1`` at the call. An equality sent to SpiralDB uses the service's own comparison. For a float column, - ``0.0`` does not select the ``-0.0`` rows. An equality to ``-0.0`` or a NaN is - refused for now (``TypeError``). SpiralDB matches them by their bits, while Orcapod + ``0.0`` does not select the ``-0.0`` rows. Equalities and memberships containing + ``-0.0`` or a NaN raise ``TypeError``. SpiralDB matches them by their bits, while Orcapod counts ``-0.0`` equal to ``0.0`` and NaN equal to NaN, so the rows read would depend on which of two equal values a condition kept. ITL-1480 tracks revisiting the float refusals. Use ``filter`` to compare these values by Orcapod's rules. @@ -660,14 +663,13 @@ def where( scalar or a date given as a string) or cannot be held exactly by the column's Arrow type (for example, ``-1`` for an unsigned column). Values are never converted, rounded or clamped. This error also - applies to unsupported conditions. For now, float equalities with - ``-0.0``, NaN, or values the column cannot hold exactly raise this + applies to unsupported conditions. For now, float equalities and + memberships with ``-0.0``, NaN, or inexact values raise this error (ITL-1480). Use ``filter`` for unsupported conditions. """ try: - # As given, before merging: merging may keep 0.0 of 0.0 and -0.0, or - # refuse -0.0 beside another value as two values (ITL-1480). + # Check the original equality and membership values before merging. check_float_equalities(*conditions, **columns) except TypeError as exc: raise TypeError(f"SpiralDB table {self._qualified!r}: {exc}") from exc diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 0335c01b9..322e635c2 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -65,6 +65,7 @@ ColumnOperand, Condition, Term, + check_float_equality, is_range_type, timestamp_count, ) @@ -668,6 +669,7 @@ def _scan_terms(where: Condition | None) -> list[Term]: Raises: ValueError: If a requirement is not equality, membership or a range of a plain column (``check_restriction`` refuses these before a source reads). + TypeError: If a membership contains NaN or negative zero. """ terms: list[Term] = [] for node in () if where is None else where.root.children: @@ -680,6 +682,10 @@ def _scan_terms(where: Condition | None) -> list[Term]: raise ValueError( f"a scan applies equalities, memberships and ranges of a column only; got {where}" ) + if node.operator == "is_in": + assert isinstance(node.value, tuple) and node.value + for member in node.value: + check_float_equality(node.path.column, member) terms.append(node) return terms @@ -893,13 +899,14 @@ def scan_batches( Raises: ValueError: If ``where`` holds anything else, or a range of a column whose type takes none. + TypeError: If a membership contains NaN or negative zero. """ + terms = _scan_terms(where) connector = self._connector table = self._at(asof) reading = self._reading(table) wanted: list[str] | None = None scanned: list[str] | None = None - terms = _scan_terms(where) if columns is not None: needed = set(columns) | {t.path.column for t in terms} wanted = [n for n in reading.found.names if n in set(columns)] @@ -988,11 +995,13 @@ def scan_batches( batch = next(reader, None) if batch is None: return - batch = reading.prepare(batch, memberships=local_memberships) - for column, value in local: - batch = batch.filter(_equals(batch.column(column), value)) + batch = reading.prepare( + batch, + memberships=local_memberships, + equalities=local, + limit=left if has_local else None, + ) if has_local and left is not None: - batch = batch.slice(0, left) left -= batch.num_rows if wanted is not None and wanted != scanned: batch = batch.select(wanted) @@ -1104,12 +1113,16 @@ def prepare( batch: pa.RecordBatch, *, memberships: Sequence[tuple[str, pa.Array[Any]]] = (), + equalities: Sequence[tuple[str, object]] = (), + limit: int | None = None, ) -> pa.RecordBatch: - """Filter a scanned batch, validate the kept rows and return them under ``schema``. + """Check layout, filter and limit the batch, then validate the returned rows. Args: batch: A batch as returned by the SDK. memberships: Local membership conditions and their Arrow value sets. + equalities: Local equality conditions and their literals. + limit: The remaining number of matching rows to return. Raises: TableSchemaError: If the batch's columns are not the snapshot's. @@ -1128,6 +1141,10 @@ def prepare( self._accepted = batch.schema for column, values in memberships: batch = batch.filter(_membership_mask(batch.column(column), values)) + for column, value in equalities: + batch = batch.filter(_equals(batch.column(column), value)) + if limit is not None: + batch = batch.slice(0, limit) with _about_table(self._table): check_no_nulls(batch, self._paths) if batch.schema.equals(self.schema, check_metadata=True): diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index 207ff9245..6f3063b79 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -875,7 +875,7 @@ def check_restriction(condition: Condition, schema: pa.Schema) -> None: except TypeError as exc: raise TypeError(f"column {column!r} {exc}") from exc if term.operator in (EQUALS, "is_in"): - _check_float_equality(column, member) + check_float_equality(column, member) if term.operator != EQUALS: continue held = equal_to.setdefault(column, value) @@ -897,23 +897,22 @@ def _matched_by_bits(value: object) -> bool: def check_float_equalities( *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object ) -> None: - """For now, refuse equality to ``-0.0`` or NaN before merging (ITL-1480). + """Refuse equality or membership with ``-0.0`` or NaN before merging (ITL-1480). Orcapod counts ``-0.0`` equal to ``0.0`` and NaN equal to NaN, so ``Condition.of`` and ``combined`` keep one of two such values; SpiralDB matches a float by its bits (``-0.0`` only ``-0.0``, a NaN only its own bit pattern). The rows read would then depend on which of two equal values was kept, so neither is taken. Checked on the - arguments as given (each mapping, each condition's top-level equalities, the - keywords), since merging may already have dropped one; every other float - equality is handled as before. Float ranges are refused for now by - ``check_restriction`` (ITL-1477). + arguments as given (each mapping, each condition's top-level equalities and + memberships, and the keywords), before merging can drop or obscure a value. + Float ranges are refused for now by ``check_restriction`` (ITL-1477). Args: *conditions: The mappings and conditions given to ``where``. **columns: The keywords given to ``where``. Raises: - TypeError: If a column is to equal ``-0.0`` or a NaN. + TypeError: If an equality or membership uses ``-0.0`` or a NaN. """ given: list[tuple[object, object]] = list(columns.items()) for argument in conditions: @@ -921,15 +920,19 @@ def check_float_equalities( given.extend( (node.path.column, node.value) for node in argument.root.children - if isinstance(node, Term) and node.operator == EQUALS + if isinstance(node, Term) and node.operator in (EQUALS, "is_in") ) elif isinstance(argument, Mapping): given.extend(argument.items()) for column, value in given: - _check_float_equality(column, value) + members = ( + value if isinstance(value, (list, tuple, set, frozenset)) else (value,) + ) + for member in members: + check_float_equality(column, member) -def _check_float_equality(column: object, value: object) -> None: +def check_float_equality(column: object, value: object) -> None: """Refuse a literal for which deduplication could change the scan's matches.""" if _matched_by_bits(value): raise TypeError( diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 3cb82d459..7c5e5b71c 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2887,3 +2887,55 @@ def test_non_range_membership_cap_counts_matching_rows(project): assert scan.filter is None and scan.limit is None with pytest.raises(SourceTooLargeError): _timestamps(_source(max_rows=1).where(note=["n4", "n5", *misses])) + + +@pytest.mark.parametrize("large", [False, True], ids=["pushed", "local"]) +@pytest.mark.parametrize( + "values", + [(math.nan,), (-0.0,), (1.5, math.nan), (0.0, 1.5, -0.0)], + ids=["nan", "negative-zero", "mixed-nan", "mixed-negative-zero"], +) +def test_connector_refuses_unsafe_float_members_on_both_scan_paths( + project, large, values +): + extras = [float(i) for i in range(1000, 1513)] if large else [] + where = col("amplitude").is_in([*values, *extras]) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + with pytest.raises( + TypeError, match=r"where takes no equality to (nan|-0\.0).*ITL-1480" + ): + list(connector.scan_batches("event", where=where)) + assert fake_spiral_sdk.scan_log == [] + + +@pytest.mark.parametrize("large", [False, True], ids=["pushed", "local"]) +def test_connector_accepts_ordinary_float_members_on_both_scan_paths(project, large): + extras = [float(i) for i in range(1000, 1513)] if large else [] + where = col("amplitude").is_in([1.5, 4.5, *extras]) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + rows = pa.Table.from_batches(connector.scan_batches("event", where=where)) + assert rows["timestamp"].to_pylist() == [1, 4] + + +@pytest.mark.parametrize("bad", [math.nan, -0.0], ids=["nan", "negative-zero"]) +def test_where_checks_float_members_before_validating_other_literals(project, bad): + source = _source() + with pytest.raises( + TypeError, match=r"where takes no equality to (nan|-0\.0).*ITL-1480" + ) as equality: + source.where(amplitude=bad) + + for args, keywords in [ + ((col("amplitude").is_in([0.1, 0.0, bad]),), {}), + (({"amplitude": [0.1, 0.0, bad]},), {}), + ((), {"amplitude": [0.1, 0.0, bad]}), + ]: + with pytest.raises(TypeError) as membership: + source.where(*args, **keywords) + assert str(membership.value) == str(equality.value) + + with pytest.raises( + TypeError, match=r"where takes no equality to (nan|-0\.0).*ITL-1480" + ): + _source(where={"amplitude": [0.1, 0.0, bad]}) + assert fake_spiral_sdk.scan_log == [] diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 81b7ab0f3..6a49b550b 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -185,6 +185,30 @@ def test_local_membership_checks_nullability_only_on_matching_rows( list(connector.scan_batches("units", where=col("k1").is_in(["a", *misses]))) +def test_local_membership_checks_nullability_after_remaining_limit( + project: Any, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(fake, "scan_batch_rows", 10) + later = _rows().slice(0, 1) + later = later.set_column( + later.schema.get_field_index("z"), + pa.field("z", pa.float64()), + pa.array([None], pa.float64()), + ) + project.table("default.units").write(later) + fake.migrate("p", {"units": _WRITTEN}) + condition = col("k1").is_in(["a", *(f"absent{i}" for i in range(513))]) + with SpiralDBKeyedConnector("p") as connector: + rows = pa.Table.from_batches( + connector.scan_batches("units", where=condition, limit=1) + ) + assert rows["k2"].to_pylist() == [1] + assert rows["z"].to_pylist() == [3.0] + + with pytest.raises(NullInNonNullableColumnError, match="units.*z|z.*units"): + list(connector.scan_batches("units", where=condition, limit=2)) + + # ------------------------------------------------------------ a table that is not recorded From e913018f70649621ee34423062d3d3a4e69fe6a4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 16:30:50 -0800 Subject: [PATCH 05/12] fix(spiraldb): preserve constructor equality diagnostics --- .../core/sources/spiraldb_table_source.py | 6 ++--- src/orcapod/types/condition.py | 25 +++++++++++-------- .../test_spiraldb_table_source_where.py | 13 ++++++++++ 3 files changed, 31 insertions(+), 13 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 2e547c203..f268da554 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -383,9 +383,9 @@ def __init__( f"{name} must be a positive integer or None, got {value!r}" ) location = f"SpiralDB project {project_id!r}, dataset {dataset!r}" - # Check the original literals before merging or connecting to the table. + # Check membership before merging. Scalar equalities need the table schema. try: - check_float_equalities(where) + check_float_equalities((where,), memberships_only=True) except TypeError as exc: raise TypeError(f"{location}, table {table_name!r}: {exc}") from exc if isinstance(where, Condition): @@ -670,7 +670,7 @@ def where( """ try: # Check the original equality and membership values before merging. - check_float_equalities(*conditions, **columns) + check_float_equalities(conditions, columns) except TypeError as exc: raise TypeError(f"SpiralDB table {self._qualified!r}: {exc}") from exc condition = _where_condition(*conditions, **columns) diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index 6f3063b79..667658462 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -895,7 +895,10 @@ def _matched_by_bits(value: object) -> bool: def check_float_equalities( - *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object + conditions: Iterable[Mapping[str, object] | Condition | ColumnRef | None], + columns: Mapping[str, object] | None = None, + *, + memberships_only: bool = False, ) -> None: """Refuse equality or membership with ``-0.0`` or NaN before merging (ITL-1480). @@ -908,28 +911,30 @@ def check_float_equalities( Float ranges are refused for now by ``check_restriction`` (ITL-1477). Args: - *conditions: The mappings and conditions given to ``where``. - **columns: The keywords given to ``where``. + conditions: The mappings and conditions given to ``where``. + columns: The keywords given to ``where``. + memberships_only: Defer scalar equalities to schema validation. Raises: TypeError: If an equality or membership uses ``-0.0`` or a NaN. """ - given: list[tuple[object, object]] = list(columns.items()) + operators = ("is_in",) if memberships_only else (EQUALS, "is_in") + given: list[tuple[object, object]] = list(columns.items()) if columns else [] for argument in conditions: if isinstance(argument, Condition): given.extend( (node.path.column, node.value) for node in argument.root.children - if isinstance(node, Term) and node.operator in (EQUALS, "is_in") + if isinstance(node, Term) and node.operator in operators ) elif isinstance(argument, Mapping): given.extend(argument.items()) for column, value in given: - members = ( - value if isinstance(value, (list, tuple, set, frozenset)) else (value,) - ) - for member in members: - check_float_equality(column, member) + if isinstance(value, (list, tuple, set, frozenset)): + for member in value: + check_float_equality(column, member) + elif not memberships_only: + check_float_equality(column, value) def check_float_equality(column: object, value: object) -> None: diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 7c5e5b71c..402ccc4a7 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2939,3 +2939,16 @@ def test_where_checks_float_members_before_validating_other_literals(project, ba ): _source(where={"amplitude": [0.1, 0.0, bad]}) assert fake_spiral_sdk.scan_log == [] + + +@pytest.mark.parametrize("bad", [math.nan, -0.0]) +def test_constructor_float_equality_retains_schema_validation(project, bad): + for condition in ({"missing_column": bad}, col("missing_column") == bad): + with pytest.raises( + ValueError, match="where names columns that the table does not have" + ): + _source(where=condition) + + for condition in ({"timestamp": bad}, col("timestamp") == bad): + with pytest.raises(TypeError, match=r"holds uint64 .*the value .* is a float"): + _source(where=condition) From f1edf3cb391f2e952960a5852fd30a6a9948624d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 18:20:46 -0800 Subject: [PATCH 06/12] feat(spiraldb): push eligible membership into exact key ranges --- changelog.d/ITL-1986.md | 2 +- docs/concepts/sources.md | 16 ++- .../core/sources/spiraldb_table_source.py | 17 +-- .../databases/spiraldb_keyed/connector.py | 80 +++++++++++- .../test_spiraldb_table_source_where.py | 122 +++++++++++++++++- tests/test_databases/fake_spiral_sdk.py | 83 +++++++++++- ...st_spiraldb_keyed_connector_integration.py | 63 +++++++++ 7 files changed, 364 insertions(+), 19 deletions(-) diff --git a/changelog.d/ITL-1986.md b/changelog.d/ITL-1986.md index 551a957e0..988c5ffd4 100644 --- a/changelog.d/ITL-1986.md +++ b/changelog.d/ITL-1986.md @@ -4,4 +4,4 @@ ### Known limitations -- Large, sparse memberships can scan a wide key range and transfer many nonmatching rows for local filtering. +- Large, sparse memberships without an eligible fixed key prefix can scan a wide key range and transfer many nonmatching rows for local filtering. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index b02dada42..fd87a082b 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -921,12 +921,16 @@ print(Condition.of(day=day, started=started, recorded=recorded)) frozensets, such as `where(sensor_id=[106, 107])`. The collection must contain at least one value and cannot contain `None`. The equality type and exactness rules apply to every member. Duplicate values and value order have no effect on the selected rows or how - the membership is displayed or saved. The SDK - has no `IN` predicate, so Orcapod sends a balanced OR of equalities in one scan, - with a shared budget of up to 512 membership equalities. For larger memberships - or literals the SDK cannot represent, such as `float16` values, Orcapod checks - membership locally before applying the limit. On an integer, timestamp or date - key, it can also push the range from the least to greatest member into the scan. + the membership is displayed or saved. On the leading primary-key column, or on a + later key column with an equality on every preceding key column, Orcapod sends sorted + exact point ranges in one scan at every list size. Other pushed predicates still apply. + Float keys and prefixes containing float keys use the existing scan filters while + signed-zero behavior in point ranges remains unverified. For other memberships, + Orcapod can send a balanced OR of equalities, with a shared budget of up to 512 + membership equalities. For larger memberships or literals the SDK cannot represent, + such as `float16` values, Orcapod checks membership locally before applying the limit. + On an integer, timestamp or date key, it can also push the range from the least to + greatest member into the scan. A wide range can transfer many nonmatching rows. When a locally checked membership has no usable range or other pushed predicate, the source may scan the entire table. `max_rows` caps matching output rows. It does not cap the rows SpiralDB transfers. diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index f268da554..c37c5e96c 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -617,14 +617,15 @@ def where( (``is_null()``, ``!=``, two columns, ``|``, or negation of a comparison) is refused. Membership uses the equality rules for each value. None and empty sets are - refused. Order and duplicates have no effect. SpiralDB's SDK has no IN - predicate, so Orcapod sends a balanced OR of equalities to the scan when the - SDK supports the literals and the expression has room. The scan has a shared - budget of up to 512 membership equalities. For larger memberships or - unsupported literals (for example, ``float16``), Orcapod checks membership - locally before applying ``limit``. An integer, timestamp or date key can also - use a scan range from its least to greatest member. When no predicate can push - down, the scan may transfer the entire table. ``max_rows`` caps matching output. + refused. Order and duplicates have no effect. A leading key or a later key + with every preceding key fixed by equality uses exact point ranges at every + list size, unless a key in the prefix is floating-point. Other memberships + use a balanced OR of equalities when the SDK supports the literals and the + scan has room in its shared budget of up to 512 membership equalities. + Larger memberships or unsupported literals are checked locally before + applying ``limit``. An integer, timestamp or date key can also use a scan range + from its least to greatest member. With no pushed predicate, the scan may + transfer the entire table. ``max_rows`` caps matching output. For now, ``where()`` refuses float equality values that the column's Arrow type cannot hold exactly. For example, a plain float32 column accepts diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 322e635c2..7e90a4fd3 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -690,6 +690,75 @@ def _scan_terms(where: Condition | None) -> list[Term]: return terms +def _physical_key_value(value: object, arrow_type: pa.DataType) -> Any: + """Return a point key in its stored order, using counts for timestamps.""" + if isinstance(arrow_type, pa.TimestampType): + return timestamp_count(cast("datetime", value), arrow_type) + return value + + +def _key_point_ranges( + terms: Sequence[Term], key_columns: Sequence[str], schema: pa.Schema +) -> tuple[list[Any] | None, set[str]]: + """Return disjoint sorted point ranges and the memberships they enforce. + + A deeper membership can replace a shallower one only if earlier fields have + fixed equalities. Those fixed fields must also satisfy any memberships on them. + An empty range list means the restriction matches no row. + """ + memberships: dict[str, list[tuple[object, ...]]] = {} + equalities: dict[str, object] = {} + for term in terms: + if term.operator == "is_in": + assert isinstance(term.value, tuple) + memberships.setdefault(term.path.column, []).append(term.value) + elif term.operator == EQUALS: + equalities[term.path.column] = term.value + handled: set[str] = set() + if not memberships: + return None, handled + + ranges: list[Any] | None = None + prefix: list[Any] = [] + for column in key_columns: + kind = schema.field(column).type + # The float equality rule distinguishes the signs of zero. Key-bound + # behavior has not been verified for float fields, including in a prefix. + if pa.types.is_floating(kind): + break + equality = equalities.get(column) + literal = _literal(equality, kind) if equality is not None else None + if member_sets := memberships.get(column): + # Compare, deduplicate and sort in the stored key representation. + values = {_physical_key_value(value, kind) for value in member_sets[0]} + for members in member_sets[1:]: + values.intersection_update( + _physical_key_value(value, kind) for value in members + ) + if literal is not None: + values.intersection_update((_physical_key_value(equality, kind),)) + if not values: + return [], handled + + points = sorted(values) + point_literals = [ + sp.literal(point, kind) + if pa.types.is_timestamp(kind) + else _literal(point, kind) + for point in points + ] + if all(point is not None for point in point_literals): + ranges = [] + for point in point_literals: + bound = sp.KeyBound((*prefix, point)) + ranges.append(sp.KeyRange(bound, bound)) + handled.add(column) + if literal is None: + break + prefix.append(literal) + return ranges, handled + + def _balanced_predicate( predicates: list[Any], combine: Callable[[Any, Any], Any] ) -> Any: @@ -905,6 +974,15 @@ def scan_batches( connector = self._connector table = self._at(asof) reading = self._reading(table) + key_columns = self.key_columns + key_ranges, handled = _key_point_ranges(terms, key_columns, reading.found) + if key_ranges == []: + return + terms = [ + term + for term in terms + if term.operator != "is_in" or term.path.column not in handled + ] wanted: list[str] | None = None scanned: list[str] | None = None if columns is not None: @@ -916,7 +994,6 @@ def scan_batches( membership_budget = max(0, _MAX_SCAN_COMPARISONS - 2 * len(terms)) pushed_comparisons = sum(term.operator != "is_in" for term in terms) fallback_bounds: dict[str, tuple[Any, Any]] = {} - key_columns = self.key_columns # Every equality compared here, in the order given: two of one column both hold. local: list[tuple[str, object]] = [] local_memberships: list[tuple[str, pa.Array[Any]]] = [] @@ -987,6 +1064,7 @@ def scan_batches( # The limit counts rows that match every condition. limit=None if has_local else limit, batch_rows=_SCAN_BATCH_ROWS, + **({"key_ranges": key_ranges} if key_ranges is not None else {}), ).to_reader() left = limit try: diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 402ccc4a7..50369e3c3 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -2726,8 +2726,9 @@ def test_scan_pushes_membership_with_equality_range_and_limit(self, project): assert len(fake_spiral_sdk.scan_log) == 2 for scan in fake_spiral_sdk.scan_log: assert scan.limit == 2 - assert scan.filter.disjunctions + assert not scan.filter.disjunctions assert scan.filter.equalities == [("subject_id", "m2")] + assert _point_keys(scan) == [("m2", 1), ("m2", 2), ("m2", 4), ("m2", 5)] def test_constructor_and_run_summary_keep_membership(self, project, tmp_path): condition = col("subject_id").is_in(["m2", "m1"]) @@ -2952,3 +2953,122 @@ def test_constructor_float_equality_retains_schema_validation(project, bad): for condition in ({"timestamp": bad}, col("timestamp") == bad): with pytest.raises(TypeError, match=r"holds uint64 .*the value .* is a float"): _source(where=condition) + + +def _point_keys(scan) -> list[tuple[object, ...]]: + """Return the inclusive point keys passed to the fake SDK.""" + assert scan.key_ranges is not None + assert all( + point.start == point.end and point.start.inclusive for point in scan.key_ranges + ) + return [ + tuple(value.value for value in point.start.values) for point in scan.key_ranges + ] + + +@pytest.mark.parametrize("size", [0, 1000], ids=["small", "large"]) +def test_leading_membership_sorts_distinct_prefix_points(project, size): + source = _source() + absent = ["absent", *(f"missing{i}" for i in range(size))] + first = source.where(col("subject_id").is_in(["m2", "m1", "m2", *absent])) + second = source.where(col("subject_id").is_in([*reversed(absent), "m1", "m2"])) + first_rows, second_rows = (view.as_table(all_info=True) for view in (first, second)) + assert first_rows.equals(second_rows) + assert first_rows["timestamp"].to_pylist() == [1, 2, 3, 4, 5] + assert first.condition == second.condition + assert hash(first.condition) == hash(second.condition) + assert first.condition.canonical_form() == second.condition.canonical_form() + assert first.condition.text() == second.condition.text() + assert first.to_config()["where"] == second.to_config()["where"] + assert first.content_hash() == second.content_hash() == source.content_hash() + assert first.pipeline_hash() == second.pipeline_hash() == source.pipeline_hash() + assert first.source_id == second.source_id == source.source_id + assert len(fake_spiral_sdk.scan_log) == 2 + for scan in fake_spiral_sdk.scan_log: + assert _point_keys(scan) == [ + (value,) for value in sorted(["m1", "m2", *absent]) + ] + assert scan.filter is None + + +def test_key_memberships_intersect_at_the_longest_fixed_prefix(project): + source = _source() + restricted = source.where( + col("timestamp").is_in([999, 5, 4]), + col("subject_id").is_in(["m1", "m2"]), + col("timestamp").is_in([2, 4, 5, 4]), + subject_id="m2", + ) + assert _timestamps(restricted) == [4, 5] + (scan,) = fake_spiral_sdk.scan_log + assert _point_keys(scan) == [("m2", 4), ("m2", 5)] + assert scan.filter.equalities == [("subject_id", "m2")] + + empty = source.where(col("subject_id").is_in(["m1"]), subject_id="m2") + assert _timestamps(empty) == [] + assert fake_spiral_sdk.scan_log == [scan] + + +def test_membership_without_fixed_prefix_uses_scan_filter(project): + source = _source().where(col("timestamp").is_in([4, 2, 4])) + assert _timestamps(source) == [2, 4] + (scan,) = fake_spiral_sdk.scan_log + assert scan.key_ranges is None + assert scan.filter.disjunctions + + +def test_point_scan_applies_limit_after_local_membership(project): + source = _source(limit=1).where( + subject_id=["m2", "m1"], + note=["n4", "n3", *(f"missing{i}" for i in range(513))], + ) + assert _timestamps(source) == [3] + (scan,) = fake_spiral_sdk.scan_log + assert _point_keys(scan) == [("m1",), ("m2",)] + assert scan.limit is None + + +def test_float_key_memberships_keep_the_existing_scan_filter(project): + keys = pa.schema([("f", pa.float64()), ("k", pa.int64())]) + project.create_table("default.float_keys", key_schema=keys).write( + pa.table({"f": [-2.0, 1.5, 4.0], "k": [1, 2, 3], "payload": [10, 20, 30]}) + ) + source = SpiralDBTableSource(_PROJECT, "float_keys", record_id_columns=("k",)) + for restricted, expected in ( + (source.where(f=[4.0, -2.0]), [1, 3]), + (source.where(f=-2.0, k=[1, 3]), [1]), + ): + assert restricted.as_table()["k"].to_pylist() == expected + for scan in fake_spiral_sdk.scan_log: + assert scan.key_ranges is None + assert scan.filter.disjunctions + for bad in (math.nan, -0.0): + with pytest.raises(TypeError, match="ITL-1480"): + source.where(col("f").is_in([0.0, bad])) + + +def test_point_ranges_require_each_preceding_key_equality(project): + keys = pa.schema([("group", pa.string()), ("shard", pa.int32()), ("k", pa.int64())]) + project.create_table("default.compound_keys", key_schema=keys).write( + pa.table( + { + "group": ["a", "a", "a", "b"], + "shard": pa.array([0, 0, 1, 0], pa.int32()), + "k": [-3, 2, -3, 2], + "payload": [10, 20, 30, 40], + } + ) + ) + source = SpiralDBTableSource(_PROJECT, "compound_keys") + member = col("k").is_in([2, -3, 99, 2]) + exact = source.where(col("shard") == 0, member, col("group") == "a") + assert exact.as_table()["payload"].to_pylist() == [10, 20] + assert _point_keys(fake_spiral_sdk.scan_log[-1]) == [ + ("a", 0, -3), + ("a", 0, 2), + ("a", 0, 99), + ] + + gap = source.where(member, group="a") + assert gap.as_table()["payload"].to_pylist() == [10, 20, 30] + assert fake_spiral_sdk.scan_log[-1].key_ranges is None diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index d0e256694..95f53f374 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -22,11 +22,12 @@ import urllib.parse import uuid import warnings -from collections.abc import Iterator +from bisect import bisect_left, bisect_right +from collections.abc import Iterator, Sequence 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 @@ -128,6 +129,7 @@ class ScanRecord: limit: int | None batches_read: int = 0 closed: bool = False + key_ranges: Sequence[FakeKeyRange] | None = None @property def kwargs(self) -> dict[str, Any]: @@ -779,6 +781,77 @@ class _Literal: type: pa.DataType +class FakeKeyBound(NamedTuple): + """An inclusive or exclusive prefix bound, like the SDK.""" + + values: tuple[_Literal, ...] + inclusive: bool = True + + +class FakeKeyRange(NamedTuple): + """A pair of prefix bounds. An absent bound leaves the endpoint open.""" + + start: FakeKeyBound | None = None + end: FakeKeyBound | None = None + + +def _range_endpoint( + keys: Sequence[tuple[Any, ...]], + key_types: Sequence[pa.DataType], + bound: FakeKeyBound, + *, + start: bool, +) -> int: + """Find a prefix endpoint in the fake snapshot's key order.""" + values = bound.values + if not 0 < len(values) <= len(key_types): + raise SpiralError("range endpoints require a nonempty key prefix") + counts: list[Any] = [] + for item, kind in zip(values, key_types): + if not isinstance(item, _Literal) or item.value is None: + raise SpiralError("range endpoints require non-null typed literals") + if item.type != kind: + raise SpiralError( + "range endpoint literal type differs from the primary key" + ) + value = item.value + if pa.types.is_date(kind): + width = pa.int32() if pa.types.is_date32(kind) else pa.int64() + value = pa.array([value], type=kind).cast(width)[0].as_py() + counts.append(value) + search = bisect_left if start == bound.inclusive else bisect_right + return search(keys, tuple(counts), key=lambda row: row[: len(values)]) + + +def _replay_key_ranges( + rows: pa.Table, key_columns: Sequence[str], key_ranges: Sequence[FakeKeyRange] +) -> pa.Table: + """Replay the given ranges in request order, retaining overlaps.""" + key_types = [rows.schema.field(column).type for column in key_columns] + columns: list[list[Any]] = [] + for column, kind in zip(key_columns, key_types, strict=True): + array = rows.column(column) + if pa.types.is_temporal(kind): + array = array.cast(pa.int32() if pa.types.is_date32(kind) else pa.int64()) + columns.append(array.to_pylist()) + keys = list(zip(*columns, strict=True)) + selected: list[pa.Table] = [] + for bounds in key_ranges: + start = ( + 0 + if bounds.start is None + else _range_endpoint(keys, key_types, bounds.start, start=True) + ) + end = ( + len(keys) + if bounds.end is None + else _range_endpoint(keys, key_types, bounds.end, start=False) + ) + if end > start: + selected.append(rows.slice(start, end - start)) + return pa.concat_tables(selected) if selected else rows.slice(0, 0) + + @dataclass(frozen=True) class FakePredicate: """Comparisons a row must all match: ``(column, literal, operator)``.""" @@ -993,11 +1066,14 @@ def scan( filter: FakePredicate | None = None, limit: int | None = None, batch_rows: int | None = None, + key_ranges: Sequence[FakeKeyRange] | None = None, ) -> FakeScan: """Plan a scan (``rows``, ``literal``, ``float-eq``, ``float-order``).""" rows = self._store.read(self.resource_id, self._version) if filter is not None: rows = rows.filter(_predicate_mask(rows, filter)) + if key_ranges is not None: + rows = _replay_key_ranges(rows, self.key_columns, key_ranges) if columns is not None: rows = rows.select(columns) if limit is not None: @@ -1008,6 +1084,7 @@ def scan( columns, filter, limit, + key_ranges=key_ranges, ) size = ( scan_batch_rows if batch_rows is None else min(batch_rows, scan_batch_rows) @@ -1198,6 +1275,8 @@ def fake_http_get_json(url: str, token: str | None) -> dict[str, Any]: fake_module = types.SimpleNamespace( Client=FakeClient, + KeyBound=FakeKeyBound, + KeyRange=FakeKeyRange, SpiralError=SpiralError, column=column, literal=literal, diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index aed25ecb6..824f5e4ee 100644 --- a/tests/test_databases/test_spiraldb_keyed_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -801,6 +801,69 @@ def test_a_range_of_every_type_reads_pyarrows_rows(place: _Place, name: str) -> assert _keys_where(place, col(name).between(low, high)) == expected +@pytest.mark.parametrize("members", [[1, -1, 0, 1], [0, 1, -1]]) +def test_point_ranges_read_integer_key_prefixes( + place: _Place, members: list[int] +) -> None: + source = place.source("units") + restricted = source.where(col("k2").is_in(members), col("zz") >= 1).head(2) + rows = restricted.as_table() + assert list(zip(rows["k2"].to_pylist(), rows["k1"].to_pylist(), strict=True)) == [ + (0, "c"), + (1, "a"), + ] + with pytest.raises(TypeError, match="int"): + source.where(col("k2").is_in([0, 1.0])) + + +@pytest.mark.parametrize("members", [["c", "absent", "b", "c"], ["b", "c", "absent"]]) +def test_point_ranges_read_later_keys_with_projection_and_limit( + place: _Place, members: list[str] +) -> None: + condition = Condition.of(col("k1").is_in(members), col("zz") >= 1, k2=0) + with place.connector() as connector: + table = connector.lookup_table("units") + batches = list(table.scan_batches(where=condition, columns=["zz"], limit=1)) + rows = pa.Table.from_batches(batches) + assert rows.column_names == ["zz"] + assert rows["zz"].to_pylist() == [2] + + +def test_point_ranges_and_local_filter_apply_limit_to_matching_rows( + place: _Place, +) -> None: + source = place.source("typed", limit=1) + restricted = source.where( + k=[3, 1, 2, 2, 100], + s=["é", *(f"absent{i}" for i in range(513))], + ) + assert restricted.as_table()["k"].to_pylist() == [2] + + +def test_sdk_point_ranges_replay_request_order_and_overlaps(place: _Place) -> None: + sp: Any = connector_module.sp + with place.connector() as connector: + table = connector.lookup_table("units")._at(None) # pyright: ignore[reportPrivateUsage] # SDK conformance + leading = sp.KeyBound((sp.literal(0, pa.int32()),)) + later = sp.KeyBound((sp.literal(0, pa.int32()), sp.literal("c", pa.string()))) + full_range = sp.KeyRange(later, later) + prefix_range = sp.KeyRange(leading, leading) + replay = [full_range, prefix_range, full_range] + assert table.scan(["k1"], key_ranges=replay).to_table()["k1"].to_pylist() == [ + "c", + "b", + "c", + "c", + ] + selected = table.scan( + ["k1"], + key_ranges=replay, + filter=sp.gte(sp.column("zz"), sp.literal(1, pa.int64())), + limit=2, + ).to_table() + assert selected["k1"].to_pylist() == ["c", "c"] + + def test_the_service_orders_floats_by_total_order(place: _Place) -> None: """Why a float range is refused (ITL-998, D14; ITL-1477): through the SDK alone, a positive NaN is above every number, the negative NaN below, and -0.0 below 0.0.""" From a5397c27edfed325e729f4e556f0094576765b6c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 18:35:14 -0800 Subject: [PATCH 07/12] fix(spiraldb): address exact point-range review findings --- .../databases/spiraldb_keyed/connector.py | 60 ++++++++----- .../test_spiraldb_table_source_where.py | 53 ++++++++++++ tests/test_databases/fake_spiral_sdk.py | 45 +++++----- ...st_spiraldb_keyed_connector_integration.py | 84 +++++++++++++++---- 4 files changed, 186 insertions(+), 56 deletions(-) diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index 7e90a4fd3..d7c76288e 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -697,6 +697,31 @@ def _physical_key_value(value: object, arrow_type: pa.DataType) -> Any: return value +def _intersect_point_members( + member_sets: Sequence[tuple[object, ...]], kind: pa.DataType +) -> dict[Any, Any] | None: + """Build typed literals for every member before discarding any nonmatch.""" + points: dict[Any, Any] | None = None + for members in member_sets: + typed: dict[Any, Any] = {} + for member in members: + value = _physical_key_value(member, kind) + literal = ( + sp.literal(value, kind) + if pa.types.is_timestamp(kind) + else _literal(member, kind) + ) + if literal is None: + return None # The point route does not support literals of this type. + typed[value] = literal + points = ( + typed + if points is None + else {value: literal for value, literal in points.items() if value in typed} + ) + return points + + def _key_point_ranges( terms: Sequence[Term], key_columns: Sequence[str], schema: pa.Schema ) -> tuple[list[Any] | None, set[str]]: @@ -729,29 +754,18 @@ def _key_point_ranges( equality = equalities.get(column) literal = _literal(equality, kind) if equality is not None else None if member_sets := memberships.get(column): - # Compare, deduplicate and sort in the stored key representation. - values = {_physical_key_value(value, kind) for value in member_sets[0]} - for members in member_sets[1:]: - values.intersection_update( - _physical_key_value(value, kind) for value in members - ) - if literal is not None: - values.intersection_update((_physical_key_value(equality, kind),)) - if not values: - return [], handled - - points = sorted(values) - point_literals = [ - sp.literal(point, kind) - if pa.types.is_timestamp(kind) - else _literal(point, kind) - for point in points - ] - if all(point is not None for point in point_literals): - ranges = [] - for point in point_literals: - bound = sp.KeyBound((*prefix, point)) - ranges.append(sp.KeyRange(bound, bound)) + points = _intersect_point_members(member_sets, kind) + if points is not None: + values = points.keys() + if literal is not None: + values = values & {_physical_key_value(equality, kind)} + if ranges != []: + # Keep a contradiction from any earlier field, while still + # validating eligible members on later fields. + ranges = [] + for value in sorted(values): + bound = sp.KeyBound((*prefix, points[value])) + ranges.append(sp.KeyRange(bound, bound)) handled.add(column) if literal is None: break diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 50369e3c3..4bbeb5bf7 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -3072,3 +3072,56 @@ def test_point_ranges_require_each_preceding_key_equality(project): gap = source.where(member, group="a") assert gap.as_table()["payload"].to_pylist() == [10, 20, 30] assert fake_spiral_sdk.scan_log[-1].key_ranges is None + + +def test_date64_prefix_point_uses_physical_key_order(project): + rows = pa.table( + { + "day": pa.array([3_600_000, 0], pa.int64()).view(pa.date64()), + "suffix": ["a", "z"], + "payload": [10, 20], + } + ) + keys = pa.schema([rows.schema.field(name) for name in ("day", "suffix")]) + project.create_table("default.temporal", key_schema=keys).write(rows) + source = SpiralDBTableSource(_PROJECT, "temporal") + midnight = dt.date(1970, 1, 1) + result = source.where(col("day").is_in([midnight])).as_table() + assert result["payload"].to_pylist() == [20] + + sp = fake_spiral_sdk.fake_module + day = sp.column("day") + predicate = sp.or_( + sp.eq(day, sp.literal(midnight, pa.date64())), + sp.eq(day, sp.literal(dt.date(1970, 1, 2), pa.date64())), + ) + table = fake_spiral_sdk.FakeClient().keyed_table(_PROJECT, "default", "temporal") + assert table.scan(filter=predicate).to_table()["payload"].to_pylist() == [20] + + +def test_date64_keys_on_the_same_day_keep_distinct_counts(project): + rows = pa.table( + { + "day": pa.array([3_600_000, 0], pa.int64()).view(pa.date64()), + "suffix": ["a", "a"], + "payload": [10, 20], + } + ) + keys = pa.schema([rows.schema.field(name) for name in ("day", "suffix")]) + table = project.create_table("default.temporal", key_schema=keys) + table.write(rows) + table.write(rows.slice(1).set_column(2, "payload", pa.array([30], pa.int64()))) + stored = fake_spiral_sdk.FakeClient().keyed_table(_PROJECT, "default", "temporal") + scanned = stored.scan().to_table() + assert scanned["day"].cast(pa.int64()).to_pylist() == [0, 3_600_000] + assert scanned["payload"].to_pylist() == [30, 10] + + +def test_point_intersection_does_not_hide_an_invalid_uint8_member(project): + rows = pa.table({"k": pa.array([0, 2], pa.uint8()), "payload": [10, 20]}) + keys = pa.schema([rows.schema.field("k")]) + project.create_table("default.small_key", key_schema=keys).write(rows) + where = Condition.of(col("k").is_in([2, 256]), k=2) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + with pytest.raises((TypeError, ValueError, pa.ArrowInvalid)): + list(connector.scan_batches("small_key", where=where)) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 95f53f374..7dd7cb0f0 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -632,6 +632,24 @@ def _check_list_child_offsets(array: Any) -> None: _check_list_child_offsets(array.values) +def _physical_key_array(array: Any) -> Any: + """Keep temporal values as their stored counts, including off-midnight dates.""" + if pa.types.is_temporal(array.type): + width = pa.int32() if array.type.bit_width == 32 else pa.int64() + return array.cast(width) + return array + + +def _physical_keys(table: pa.Table, keys: Sequence[str]) -> list[tuple[Any, ...]]: + """Read physical key tuples for duplicate checks, ordering, and range lookup.""" + return list( + zip( + *(_physical_key_array(table.column(k)).to_pylist() for k in keys), + strict=True, + ) + ) + + def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: """Validate ``rows`` and return them as they are stored (``stage``).""" names = [name.split("\0")[0] for name in rows.column_names] # nul @@ -661,7 +679,7 @@ def _staged(rows: pa.Table, keys: list[str], stored: pa.Schema) -> pa.Table: raise _refuse(f"Key field '{key}' contains null values") if set(names) <= set(keys): raise _refuse("Write contains no data columns") - tuples = list(zip(*(rows.column(k).to_pylist() for k in keys))) + tuples = _physical_keys(rows, keys) if len(set(tuples)) != len(tuples): raise _refuse("Duplicate keys found in input batch") fields, arrays = [], [] @@ -733,12 +751,9 @@ def _upserted(stored: pa.Table, rows: pa.Table, keys: list[str]) -> pa.Table: values = _order([f for name, f in fields.items() if name not in keys]) schema = pa.schema([*(fields[k] for k in keys), *values]) - def key_of(table: pa.Table) -> list[tuple[Any, ...]]: - return list(zip(*(table.column(k).to_pylist() for k in keys))) - - old = {key: i for i, key in enumerate(key_of(stored))} - new = {key: i for i, key in enumerate(key_of(rows))} - # Python's order of these key values is the service's: text by code point. + old = {key: i for i, key in enumerate(_physical_keys(stored, keys))} + new = {key: i for i, key in enumerate(_physical_keys(rows, keys))} + # Order by the stored values, including temporal counts and text code points. ordered = sorted({**old, **new}) columns = [] for field in schema: @@ -815,9 +830,8 @@ def _range_endpoint( "range endpoint literal type differs from the primary key" ) value = item.value - if pa.types.is_date(kind): - width = pa.int32() if pa.types.is_date32(kind) else pa.int64() - value = pa.array([value], type=kind).cast(width)[0].as_py() + if pa.types.is_temporal(kind): + value = _physical_key_array(pa.array([value], type=kind))[0].as_py() counts.append(value) search = bisect_left if start == bound.inclusive else bisect_right return search(keys, tuple(counts), key=lambda row: row[: len(values)]) @@ -828,13 +842,7 @@ def _replay_key_ranges( ) -> pa.Table: """Replay the given ranges in request order, retaining overlaps.""" key_types = [rows.schema.field(column).type for column in key_columns] - columns: list[list[Any]] = [] - for column, kind in zip(key_columns, key_types, strict=True): - array = rows.column(column) - if pa.types.is_temporal(kind): - array = array.cast(pa.int32() if pa.types.is_date32(kind) else pa.int64()) - columns.append(array.to_pylist()) - keys = list(zip(*columns, strict=True)) + keys = _physical_keys(rows, key_columns) selected: list[pa.Table] = [] for bounds in key_ranges: start = ( @@ -943,8 +951,7 @@ def _predicate_mask(rows: pa.Table, predicate: FakePredicate) -> pa.BooleanArray stored: Any = rows.column(name) given: Any = pa.array([wanted.value], wanted.type) if pa.types.is_temporal(wanted.type): - width = pa.int32() if pa.types.is_date32(wanted.type) else pa.int64() - stored, given = stored.cast(width), given.cast(width) + stored, given = _physical_key_array(stored), _physical_key_array(given) elif op == "==" and pa.types.is_floating(wanted.type): # Read raw bits before to_pylist() can quiet a signaling NaN. bits = {16: pa.uint16(), 32: pa.uint32(), 64: pa.uint64()}[ diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index 824f5e4ee..708781bb3 100644 --- a/tests/test_databases/test_spiraldb_keyed_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -10,7 +10,8 @@ ``SPIRAL_VIEWER_KEY_FILE`` for a workload with viewer access to the test project. Spiral SDK cannot drop keyed tables. The reading cases seed a fixed set of tables once -and reuse their snapshots to avoid overlapping fragments on each run. Advance the default +and reuse their snapshots to avoid overlapping fragments on each run. Live point-range +cases open and verify the existing fixtures without seeding. Advance the default dataset version when the seed data changes. Use ``ORCAPOD_SPIRAL_CONFORMANCE_DATASET`` to select another dataset for that version. The discovery cases run Orcapod jobs with fixed names in a fixed writable dataset, overridable with @@ -30,7 +31,9 @@ from collections.abc import Iterator from contextlib import ExitStack from dataclasses import dataclass +from importlib import import_module from pathlib import Path +from types import SimpleNamespace from typing import Any, Literal from unittest.mock import patch @@ -369,6 +372,20 @@ def _require_fixture_snapshots(client: Any, schema_table: Any, scope: st.Scope) ) +def _open_existing_fixture(client: Any, place: _Place) -> None: + """Require a complete fixture without creating or modifying any table.""" + scope = st.Scope(place.project, place.dataset, "0" * 64) + registry = connector_module._open_keyed_table( # pyright: ignore[reportPrivateUsage] # SDK read-only lookup + client, place.project, place.dataset, st.SCHEMA_TABLE + ) + try: + if registry is None or not st.require_schema_table(registry): + raise st.TableSchemaError("the fixture has no completed schema registry") + _require_fixture_snapshots(client, registry, scope) + except st.TableSchemaError as exc: + pytest.skip(f"Read-only SpiralDB conformance fixture unavailable: {exc.reason}") + + def _seed(client: Any, place: _Place) -> None: """Create the fixed read fixtures once, resuming an interrupted first seed.""" project = client.project(place.project) @@ -443,23 +460,23 @@ def _in_order(found: Any, written: Any) -> Any: ) -@pytest.fixture( +_LIVE_ONLY = pytest.mark.skipif( + not (_LIVE and _PROJECT), + reason="Set SPIRAL_INTEGRATION_TESTS=1 and SPIRAL_PROJECT_ID", +) +_READ_ONLY_FIXTURE = pytest.mark.parametrize( + "place", + ["fake", pytest.param("live-read-only", marks=_LIVE_ONLY)], + indirect=True, scope="module", - params=[ - "fake", - pytest.param( - "live", - marks=pytest.mark.skipif( - not (_LIVE and _PROJECT), - reason="Set SPIRAL_INTEGRATION_TESTS=1 and SPIRAL_PROJECT_ID", - ), - ), - ], ) + + +@pytest.fixture(scope="module", params=["fake", pytest.param("live", marks=_LIVE_ONLY)]) def place( request: pytest.FixtureRequest, tmp_path_factory: pytest.TempPathFactory ) -> Iterator[_Place]: - """The seeded tables, on the fake or on SpiralDB.""" + """Seed a fake or writable fixture, or verify an existing live fixture.""" if request.param == "fake": root: Path = tmp_path_factory.mktemp("spiral") with fake.install(root): @@ -469,10 +486,45 @@ def place( return made = _Place(_PROJECT, _DATASET, {"server.url": _URL}) with made.connector() as connector: - _seed(connector._client, made) # pyright: ignore[reportPrivateUsage] # the SDK's client, for the test's own writes + client = connector._client # pyright: ignore[reportPrivateUsage] # direct SDK fixture access + if request.param == "live-read-only": + _open_existing_fixture(client, made) + else: + _seed(client, made) yield made +@pytest.mark.parametrize("complete", [True, False], ids=["existing", "incomplete"]) +def test_existing_live_fixture_opens_without_create( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, complete: bool +) -> None: + with fake.install(tmp_path): + client = fake.FakeClient() + if complete: + _seed(client, _Place("p", _DATASET, None)) + else: + client.project("p").create_keyed_table( + _DATASET, st.SCHEMA_TABLE, st.KEY_SCHEMA + ) + monkeypatch.setattr(import_module(__name__), "_PROJECT", "p") + + def refuse_write(*args: Any, **kwargs: Any) -> None: + raise AssertionError("read-only fixture attempted a create or write") + + monkeypatch.setattr(fake.FakeProject, "create_keyed_table", refuse_write) + monkeypatch.setattr(fake.FakeKeyedTable, "append", refuse_write) + monkeypatch.setattr(fake.FakeKeyedTable, "writer", refuse_write) + fixture = place.__wrapped__(SimpleNamespace(param="live-read-only"), None) # pyright: ignore[reportFunctionMemberAccess] # pytest's decorated fixture wrapper + try: + if complete: + assert next(fixture).project == "p" + else: + with pytest.raises(pytest.skip.Exception, match="fixture unavailable"): + next(fixture) + finally: + fixture.close() + + def test_reopening_a_seeded_fixture_keeps_its_snapshots(tmp_path: Path) -> None: """A second setup reuses the read fixtures without publishing new fragments.""" with fake.install(tmp_path): @@ -801,6 +853,7 @@ def test_a_range_of_every_type_reads_pyarrows_rows(place: _Place, name: str) -> assert _keys_where(place, col(name).between(low, high)) == expected +@_READ_ONLY_FIXTURE @pytest.mark.parametrize("members", [[1, -1, 0, 1], [0, 1, -1]]) def test_point_ranges_read_integer_key_prefixes( place: _Place, members: list[int] @@ -816,6 +869,7 @@ def test_point_ranges_read_integer_key_prefixes( source.where(col("k2").is_in([0, 1.0])) +@_READ_ONLY_FIXTURE @pytest.mark.parametrize("members", [["c", "absent", "b", "c"], ["b", "c", "absent"]]) def test_point_ranges_read_later_keys_with_projection_and_limit( place: _Place, members: list[str] @@ -829,6 +883,7 @@ def test_point_ranges_read_later_keys_with_projection_and_limit( assert rows["zz"].to_pylist() == [2] +@_READ_ONLY_FIXTURE def test_point_ranges_and_local_filter_apply_limit_to_matching_rows( place: _Place, ) -> None: @@ -840,6 +895,7 @@ def test_point_ranges_and_local_filter_apply_limit_to_matching_rows( assert restricted.as_table()["k"].to_pylist() == [2] +@_READ_ONLY_FIXTURE def test_sdk_point_ranges_replay_request_order_and_overlaps(place: _Place) -> None: sp: Any = connector_module.sp with place.connector() as connector: From 2b75807137e45d4ce2ad7f752354469d00460b45 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 18:53:13 -0800 Subject: [PATCH 08/12] fix(spiraldb): validate scan literals before routing --- .../databases/spiraldb_keyed/connector.py | 177 ++++++++---------- .../test_spiraldb_table_source_where.py | 90 +++++++++ tests/test_databases/fake_spiral_sdk.py | 16 +- ...st_spiraldb_keyed_connector_integration.py | 11 +- tests/test_databases/test_spiraldb_reading.py | 15 +- 5 files changed, 194 insertions(+), 115 deletions(-) diff --git a/src/orcapod/databases/spiraldb_keyed/connector.py b/src/orcapod/databases/spiraldb_keyed/connector.py index d7c76288e..b4f5d6c55 100644 --- a/src/orcapod/databases/spiraldb_keyed/connector.py +++ b/src/orcapod/databases/spiraldb_keyed/connector.py @@ -28,7 +28,7 @@ from contextlib import contextmanager from copy import copy from threading import Lock, local -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, Any, NamedTuple, cast from weakref import WeakValueDictionary, proxy import pyarrow as pa @@ -64,8 +64,10 @@ EQUALS, ColumnOperand, Condition, + Operator, Term, check_float_equality, + check_value_for_column, is_range_type, timestamp_count, ) @@ -613,7 +615,7 @@ def _literal(value: Any, arrow_type: pa.DataType) -> Any: arrow_type = pa.string() elif pa.types.is_large_binary(arrow_type): arrow_type = pa.binary() - if pa.types.is_float64(arrow_type): + if pa.types.is_float32(arrow_type) or pa.types.is_float64(arrow_type): return sp.literal(value, arrow_type) if pa.types.is_timestamp(arrow_type): # As a count of the unit: the SDK takes no datetime between two of them. @@ -626,10 +628,6 @@ def _literal(value: Any, arrow_type: pa.DataType) -> Any: or pa.types.is_date(arrow_type) ): return sp.literal(value, arrow_type) - if pa.types.is_float32(arrow_type): - scalar_value = float(value) if type(value) is int else value - if math.isnan(value) or pa.scalar(scalar_value, arrow_type).as_py() == value: - return sp.literal(value, arrow_type) return None @@ -637,41 +635,18 @@ def _literal(value: Any, arrow_type: pa.DataType) -> Any: """The SDK function of each order comparison.""" -def _range_predicate( - column: str, operator: str, value: object, arrow_type: pa.DataType -) -> Any: # pyright: ignore[reportExplicitAny] # an SDK expression, untyped - """Return the scan predicate ``column operator value``, applied by SpiralDB. +class _ScanTerm(NamedTuple): + """A scan requirement with validated values and its available SDK literals.""" - Only a column whose values SpiralDB orders as Orcapod does (``is_range_type``: - integers, timestamps, dates); a range is never read and compared here, since it - exists to bound the read. + column: str + operator: Operator + values: tuple[object, ...] + literals: tuple[Any, ...] - Args: - column: The column's name. - operator: ``<``, ``<=``, ``>`` or ``>=``. - value: A bound checked against the column (``check_restriction``). - arrow_type: The column's type as SpiralDB stores it. - Raises: - ValueError: If the column's type takes no range. - """ - literal = _literal(value, arrow_type) if is_range_type(arrow_type) else None - if literal is None: - raise ValueError( - f"column {column!r} holds {arrow_type}, which takes no range in a scan" - ) - return getattr(sp, _COMPARE[operator])(sp.column(column), literal) - - -def _scan_terms(where: Condition | None) -> list[Term]: - """Return the requirements of a scan's condition, refusing what a scan cannot apply. - - Raises: - ValueError: If a requirement is not equality, membership or a range of a - plain column (``check_restriction`` refuses these before a source reads). - TypeError: If a membership contains NaN or negative zero. - """ - terms: list[Term] = [] +def _scan_terms(where: Condition | None, schema: pa.Schema) -> list[_ScanTerm]: + """Validate and encode all scan literals before deciding how to read.""" + terms: list[_ScanTerm] = [] for node in () if where is None else where.root.children: if not ( isinstance(node, Term) @@ -682,11 +657,27 @@ def _scan_terms(where: Condition | None) -> list[Term]: raise ValueError( f"a scan applies equalities, memberships and ranges of a column only; got {where}" ) + column = node.path.column + field = schema.field(column) + if node.operator in _COMPARE and not is_range_type(field.type): + raise ValueError( + f"column {column!r} holds {field.type}, which takes no range in a scan" + ) + values: tuple[object, ...] = (node.value,) if node.operator == "is_in": assert isinstance(node.value, tuple) and node.value - for member in node.value: - check_float_equality(node.path.column, member) - terms.append(node) + values = node.value + + literals: list[Any] = [] + for value in values: + if node.operator == "is_in": + check_float_equality(column, value) + try: + check_value_for_column(value, field, require_exact=True) + literals.append(_literal(value, field.type)) + except (TypeError, ValueError, OverflowError) as exc: + raise TypeError(f"column {column!r} {exc}") from exc + terms.append(_ScanTerm(column, node.operator, values, tuple(literals))) return terms @@ -698,22 +689,17 @@ def _physical_key_value(value: object, arrow_type: pa.DataType) -> Any: def _intersect_point_members( - member_sets: Sequence[tuple[object, ...]], kind: pa.DataType + member_sets: Sequence[_ScanTerm], kind: pa.DataType ) -> dict[Any, Any] | None: - """Build typed literals for every member before discarding any nonmatch.""" + """Intersect the previously validated membership literals in physical key order.""" points: dict[Any, Any] | None = None - for members in member_sets: - typed: dict[Any, Any] = {} - for member in members: - value = _physical_key_value(member, kind) - literal = ( - sp.literal(value, kind) - if pa.types.is_timestamp(kind) - else _literal(member, kind) - ) - if literal is None: - return None # The point route does not support literals of this type. - typed[value] = literal + for term in member_sets: + if any(literal is None for literal in term.literals): + return None + typed = { + _physical_key_value(value, kind): literal + for value, literal in zip(term.values, term.literals, strict=True) + } points = ( typed if points is None @@ -723,7 +709,7 @@ def _intersect_point_members( def _key_point_ranges( - terms: Sequence[Term], key_columns: Sequence[str], schema: pa.Schema + terms: Sequence[_ScanTerm], key_columns: Sequence[str], schema: pa.Schema ) -> tuple[list[Any] | None, set[str]]: """Return disjoint sorted point ranges and the memberships they enforce. @@ -731,14 +717,13 @@ def _key_point_ranges( fixed equalities. Those fixed fields must also satisfy any memberships on them. An empty range list means the restriction matches no row. """ - memberships: dict[str, list[tuple[object, ...]]] = {} - equalities: dict[str, object] = {} + memberships: dict[str, list[_ScanTerm]] = {} + equalities: dict[str, _ScanTerm] = {} for term in terms: if term.operator == "is_in": - assert isinstance(term.value, tuple) - memberships.setdefault(term.path.column, []).append(term.value) + memberships.setdefault(term.column, []).append(term) elif term.operator == EQUALS: - equalities[term.path.column] = term.value + equalities[term.column] = term handled: set[str] = set() if not memberships: return None, handled @@ -752,16 +737,16 @@ def _key_point_ranges( if pa.types.is_floating(kind): break equality = equalities.get(column) - literal = _literal(equality, kind) if equality is not None else None + literal = equality.literals[0] if equality is not None else None if member_sets := memberships.get(column): points = _intersect_point_members(member_sets, kind) if points is not None: values = points.keys() - if literal is not None: - values = values & {_physical_key_value(equality, kind)} + if equality is not None and literal is not None: + values = values & {_physical_key_value(equality.values[0], kind)} if ranges != []: # Keep a contradiction from any earlier field, while still - # validating eligible members on later fields. + # planning the remaining fixed key fields. ranges = [] for value in sorted(values): bound = sp.KeyBound((*prefix, points[value])) @@ -982,12 +967,13 @@ def scan_batches( Raises: ValueError: If ``where`` holds anything else, or a range of a column whose type takes none. - TypeError: If a membership contains NaN or negative zero. + TypeError: If a literal does not fit its stored type exactly, or a + membership contains NaN or negative zero. """ - terms = _scan_terms(where) connector = self._connector table = self._at(asof) reading = self._reading(table) + terms = _scan_terms(where, reading.found) key_columns = self.key_columns key_ranges, handled = _key_point_ranges(terms, key_columns, reading.found) if key_ranges == []: @@ -995,29 +981,27 @@ def scan_batches( terms = [ term for term in terms - if term.operator != "is_in" or term.path.column not in handled + if term.operator != "is_in" or term.column not in handled ] wanted: list[str] | None = None scanned: list[str] | None = None if columns is not None: - needed = set(columns) | {t.path.column for t in terms} + needed = set(columns) | {t.column for t in terms} wanted = [n for n in reading.found.names if n in set(columns)] scanned = [n for n in reading.found.names if n in needed] reading = reading.projected(scanned) predicates: list[Any] = [] membership_budget = max(0, _MAX_SCAN_COMPARISONS - 2 * len(terms)) pushed_comparisons = sum(term.operator != "is_in" for term in terms) - fallback_bounds: dict[str, tuple[Any, Any]] = {} + fallback_bounds: dict[str, tuple[tuple[Any, Any], tuple[Any, Any]]] = {} # Every equality compared here, in the order given: two of one column both hold. local: list[tuple[str, object]] = [] local_memberships: list[tuple[str, pa.Array[Any]]] = [] for term in terms: - column, value = term.path.column, term.value + column, values, literals = term.column, term.values, term.literals column_type = reading.found.field(column).type if term.operator == "is_in": - assert isinstance(value, tuple) and value - if len(value) <= membership_budget: - literals = [_literal(member, column_type) for member in value] + if len(values) <= membership_budget: if all(literal is not None for literal in literals): field = sp.column(column) predicates.append( @@ -1025,49 +1009,44 @@ def scan_batches( [sp.eq(field, literal) for literal in literals], sp.or_ ) ) - membership_budget -= len(value) - pushed_comparisons += len(value) + membership_budget -= len(values) + pushed_comparisons += len(values) continue local_memberships.append( ( column, - _membership_values(value, reading.schema.field(column).type), + _membership_values(values, reading.schema.field(column).type), ) ) if column in key_columns and is_range_type(column_type): - ordered = cast("tuple[Any, ...]", value) - low, high = min(ordered), max(ordered) + ordered = [ + (_physical_key_value(member, column_type), literal) + for member, literal in zip(values, literals, strict=True) + ] + low = min(ordered, key=lambda item: item[0]) + high = max(ordered, key=lambda item: item[0]) if column in fallback_bounds: previous_low, previous_high = fallback_bounds[column] - low, high = max(low, previous_low), min(high, previous_high) + low = max(low, previous_low, key=lambda item: item[0]) + high = min(high, previous_high, key=lambda item: item[0]) fallback_bounds[column] = low, high continue - if term.operator != EQUALS: + (literal,) = literals + if term.operator in _COMPARE: predicates.append( - _range_predicate(column, term.operator, value, column_type) + getattr(sp, _COMPARE[term.operator])(sp.column(column), literal) ) - continue - literal = _literal(value, column_type) - if literal is None and pa.types.is_float32(column_type): - # No float32 is exactly this value. The SDK would round it, so 0.1 would - # match the float32 nearest to it; a comparison of the values does not. - return - if literal is None: - local.append((column, value)) - continue - predicates.append(sp.eq(sp.column(column), literal)) + elif literal is None: + local.append((column, values[0])) + else: + predicates.append(sp.eq(sp.column(column), literal)) # The bounds only narrow the candidate scan. Skip them if the required # comparisons already use the budget, and still check every membership locally. for column, (low, high) in fallback_bounds.items(): if pushed_comparisons + 2 > _MAX_SCAN_COMPARISONS: break - column_type = reading.found.field(column).type - predicates.extend( - ( - _range_predicate(column, ">=", low, column_type), - _range_predicate(column, "<=", high, column_type), - ) - ) + field = sp.column(column) + predicates.extend((sp.gte(field, low[1]), sp.lte(field, high[1]))) pushed_comparisons += 2 predicate = _balanced_predicate(predicates, sp.and_) has_local = bool(local or local_memberships) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 4bbeb5bf7..895baa155 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -3125,3 +3125,93 @@ def test_point_intersection_does_not_hide_an_invalid_uint8_member(project): with SpiralDBKeyedConnector(_PROJECT, "default") as connector: with pytest.raises((TypeError, ValueError, pa.ArrowInvalid)): list(connector.scan_batches("small_key", where=where)) + + +@pytest.mark.parametrize("route", ["points", "or", "span", "local"]) +@pytest.mark.parametrize( + "bad", [256, -1, 2.5], ids=["overflow", "negative", "fraction"] +) +@pytest.mark.parametrize( + "equality", [False, True], ids=["no-equality", "with-equality"] +) +def test_direct_scan_rejects_invalid_literals_before_routing( + project, monkeypatch, route, bad, equality +): + from orcapod.databases.spiraldb_keyed import connector as connector_module + + rows = pa.table( + {"prefix": ["a", "b"], "k": pa.array([0, 2], pa.uint8()), "payload": [10, 20]} + ) + keys = { + "points": ["k"], + "or": ["prefix", "k"], + "span": ["prefix", "k"], + "local": ["prefix"], + } + project.create_table( + "default.small_key", + key_schema=pa.schema([rows.schema.field(k) for k in keys[route]]), + ).write(rows) + if route in ("span", "local"): + monkeypatch.setattr(connector_module, "_MAX_SCAN_COMPARISONS", 0) + + where = col("k").is_in([0, 2, bad, 17]) + if equality: + where = where & (col("k") == 2) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + table = connector.lookup_table("small_key") + with pytest.raises(TypeError, match="column 'k' holds uint8"): + list(table.scan_batches(where=where)) + if equality: + invalid_equality = col("k").is_in([0, 2]) & (col("k") == bad) + with pytest.raises(TypeError, match="column 'k' holds uint8"): + list(table.scan_batches(where=invalid_equality)) + assert fake_spiral_sdk.scan_log == [] + + +@pytest.mark.parametrize( + "bad", [256, -1, 2.5], ids=["overflow", "negative", "fraction"] +) +def test_empty_point_intersection_still_validates_non_key_members(project, bad): + rows = pa.table( + {"k": pa.array([0, 2], pa.uint8()), "other": pa.array([0, 2], pa.uint8())} + ) + project.create_table( + "default.small_key", key_schema=pa.schema([rows.schema.field("k")]) + ).write(rows) + where = Condition.of(col("k").is_in([0]), k=2) & col("other").is_in([0, 2, bad, 17]) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + with pytest.raises(TypeError, match="column 'other' holds uint8"): + list(connector.scan_batches("small_key", where=where)) + assert fake_spiral_sdk.scan_log == [] + + +def test_fake_date64_point_literal_retains_milliseconds(project): + rows = pa.table( + { + "day": pa.array([3_600_000, 0], pa.int64()).view(pa.date64()), + "suffix": ["a", "a"], + "payload": [10, 20], + } + ) + keys = pa.schema([rows.schema.field(name) for name in ("day", "suffix")]) + project.create_table("default.temporal", key_schema=keys).write(rows) + sp = fake_spiral_sdk.fake_module + table = fake_spiral_sdk.FakeClient().keyed_table(_PROJECT, "default", "temporal") + literal = sp.literal(3_600_000, pa.date64()) + point = sp.KeyBound((literal,)) + assert table.scan(key_ranges=[sp.KeyRange(point, point)]).to_table()[ + "payload" + ].to_pylist() == [10] + assert table.scan(filter=sp.eq(sp.column("day"), literal)).to_table()[ + "payload" + ].to_pylist() == [10] + + +@pytest.mark.parametrize( + "bad", [256, -1, 2.5], ids=["overflow", "negative", "fraction"] +) +def test_uint8_scan_validation_agrees_with_sdk_encoder(bad): + sdk = pytest.importorskip("spiral") + with pytest.raises((TypeError, ValueError)): + sdk.literal(bad, pa.uint8()) diff --git a/tests/test_databases/fake_spiral_sdk.py b/tests/test_databases/fake_spiral_sdk.py index 7dd7cb0f0..23e76536b 100644 --- a/tests/test_databases/fake_spiral_sdk.py +++ b/tests/test_databases/fake_spiral_sdk.py @@ -829,10 +829,7 @@ def _range_endpoint( raise SpiralError( "range endpoint literal type differs from the primary key" ) - value = item.value - if pa.types.is_temporal(kind): - value = _physical_key_array(pa.array([value], type=kind))[0].as_py() - counts.append(value) + counts.append(item.value) search = bisect_left if start == bound.inclusive else bisect_right return search(keys, tuple(counts), key=lambda row: row[: len(values)]) @@ -886,12 +883,11 @@ def literal(value: Any, type: Any = None) -> _Literal: """Stand in for ``spiral.literal`` (``literal``): an explicit scalar type.""" if type is None or pa.types.is_large_string(type) or pa.types.is_large_binary(type): raise TypeError(f"unsupported literal Arrow type {type}") - if pa.types.is_timestamp(type): - scalar = pa.scalar(value, type) - # Kept as its integer count, never a Python value: an instant at either end of - # a count (year 1 east of UTC, the ends of timestamp[ns]) has no datetime or - # pandas Timestamp in its zone. The scan reads the count as the same type. - return _Literal(scalar.value, type) + if pa.types.is_temporal(type): + # Keep physical counts, including off-midnight date64 literals and + # timestamp counts outside the Python datetime range. + scalar = _physical_key_array(pa.array([value], type=type))[0] + return _Literal(scalar.as_py(), type) if ( pa.types.is_floating(type) and isinstance(value, int) diff --git a/tests/test_databases/test_spiraldb_keyed_connector_integration.py b/tests/test_databases/test_spiraldb_keyed_connector_integration.py index 708781bb3..0547e3bb4 100644 --- a/tests/test_databases/test_spiraldb_keyed_connector_integration.py +++ b/tests/test_databases/test_spiraldb_keyed_connector_integration.py @@ -730,10 +730,8 @@ def test_limit_reads_the_first_keys(place: _Place, limit: int) -> None: ({"h": 0.5}, [1]), ({"h": -0.0}, [2]), ({"h": math.nan}, [3]), - ({"f": 0.1}, []), ({"f": -0.0}, [2]), ({"f": math.nan}, [3]), - ({"f": 1e300}, []), ({"d": 0.1}, [1]), ({"d": 0.0}, []), ({"s": "é"}, [2]), @@ -756,6 +754,15 @@ def test_where(place: _Place, where: dict[str, Any], expected: list[int]) -> Non assert [k for b in batches for k in b.column("k").to_pylist()] == expected +@pytest.mark.parametrize("value", [0.1, 1e300]) +def test_direct_scan_refuses_inexact_float32_equality( + place: _Place, value: float +) -> None: + with place.connector() as connector: + with pytest.raises(TypeError, match="cannot hold .* exactly"): + list(connector.scan_batches("typed", where=Condition.of(f=value))) + + def test_counts(place: _Place) -> None: table = place.connector().lookup_table("units") assert table.count_rows(at_most=2) == 2 diff --git a/tests/test_databases/test_spiraldb_reading.py b/tests/test_databases/test_spiraldb_reading.py index 6a49b550b..750b1d848 100644 --- a/tests/test_databases/test_spiraldb_reading.py +++ b/tests/test_databases/test_spiraldb_reading.py @@ -377,13 +377,9 @@ def test_a_batch_is_mapped_by_name_and_never_by_position(project: Any) -> None: ("h", 0.0, []), ("h", -0.0, [2]), ("h", math.nan, [3]), - ("h", 0.1, []), - ("h", 1e300, []), - ("f", 0.1, []), ("f", 0.0, []), ("f", -0.0, [2]), ("f", math.nan, [3]), - ("f", 1e300, []), ("f", math.inf, []), ("n", 0.0, [1]), ("n", -0.0, []), @@ -418,6 +414,17 @@ def test_where_matches_as_the_service_does( assert [k for b in batches for k in b.column("k").to_pylist()] == expected +@pytest.mark.parametrize("column", ["h", "f"]) +@pytest.mark.parametrize("value", [0.1, 1e300]) +def test_where_refuses_inexact_stored_float_types( + project: Any, column: str, value: float +) -> None: + project.create_table("default.typed", key_schema=[("k", pa.int64())]).write(_TYPED) + with SpiralDBKeyedConnector("p") as connector: + with pytest.raises(TypeError, match="cannot hold .* exactly"): + list(connector.scan_batches("typed", where=Condition.of({column: value}))) + + @pytest.mark.parametrize("limit", [1, 2, 3]) def test_a_filter_applied_here_comes_before_the_limit(project: Any, limit: int) -> None: rows = pa.table( From 58e78777480a6c3f97e2fb4f3a5b8204173267d4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 19:06:29 -0800 Subject: [PATCH 09/12] test(spiraldb): verify span routing and SDK agreement --- .../test_spiraldb_table_source_where.py | 42 ++++++++++++++++--- 1 file changed, 36 insertions(+), 6 deletions(-) diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 895baa155..4e4cb9f1b 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -3152,12 +3152,16 @@ def test_direct_scan_rejects_invalid_literals_before_routing( "default.small_key", key_schema=pa.schema([rows.schema.field(k) for k in keys[route]]), ).write(rows) - if route in ("span", "local"): - monkeypatch.setattr(connector_module, "_MAX_SCAN_COMPARISONS", 0) - where = col("k").is_in([0, 2, bad, 17]) if equality: where = where & (col("k") == 2) + if route == "span": + # The four values exceed the OR budget of two, leaving room for both bounds. + cap = 2 * len(where.root.children) + 2 + monkeypatch.setattr(connector_module, "_MAX_SCAN_COMPARISONS", cap) + elif route == "local": + monkeypatch.setattr(connector_module, "_MAX_SCAN_COMPARISONS", 0) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: table = connector.lookup_table("small_key") with pytest.raises(TypeError, match="column 'k' holds uint8"): @@ -3166,7 +3170,23 @@ def test_direct_scan_rejects_invalid_literals_before_routing( invalid_equality = col("k").is_in([0, 2]) & (col("k") == bad) with pytest.raises(TypeError, match="column 'k' holds uint8"): list(table.scan_batches(where=invalid_equality)) - assert fake_spiral_sdk.scan_log == [] + assert fake_spiral_sdk.scan_log == [] + + if route == "span": + valid = col("k").is_in([0, 2, 8, 17]) + if equality: + valid = valid & (col("k") == 2) + assert len(valid.root.children) == len(where.root.children) + rows = pa.Table.from_batches(table.scan_batches(where=valid)) + assert rows["k"].to_pylist() == ([2] if equality else [0, 2]) + (scan,) = fake_spiral_sdk.scan_log + assert scan.key_ranges is None + assert not scan.filter.disjunctions + assert [ + (literal.value, op) + for column, literal, op in scan.filter.terms + if column == "k" and op in (">=", "<=") + ] == [(0, ">="), (17, "<=")] @pytest.mark.parametrize( @@ -3211,7 +3231,17 @@ def test_fake_date64_point_literal_retains_milliseconds(project): @pytest.mark.parametrize( "bad", [256, -1, 2.5], ids=["overflow", "negative", "fraction"] ) -def test_uint8_scan_validation_agrees_with_sdk_encoder(bad): +def test_uint8_scan_validation_agrees_with_sdk_encoder(project, bad): sdk = pytest.importorskip("spiral") + members = [0, 2, bad, 17] with pytest.raises((TypeError, ValueError)): - sdk.literal(bad, pa.uint8()) + for member in members: + sdk.literal(member, pa.uint8()) + + rows = pa.table({"k": pa.array([0, 2], pa.uint8()), "payload": [10, 20]}) + keys = pa.schema([rows.schema.field("k")]) + project.create_table("default.small_key", key_schema=keys).write(rows) + with SpiralDBKeyedConnector(_PROJECT, "default") as connector: + with pytest.raises(TypeError, match="column 'k' holds uint8"): + list(connector.scan_batches("small_key", where=col("k").is_in(members))) + assert fake_spiral_sdk.scan_log == [] From e21c4db59d77ec072269b51491f1581c39f42c43 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 19:54:39 -0800 Subject: [PATCH 10/12] fix(spiraldb): preserve mixed shorthand display order --- .../core/sources/spiraldb_table_source.py | 36 +++++++++++---- .../test_spiraldb_table_source_where.py | 44 ++++++++++++++++++- 2 files changed, 69 insertions(+), 11 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index c37c5e96c..9e27c042b 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -211,24 +211,42 @@ def _where_condition( *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object, ) -> Condition: - """Translate collection-valued source arguments to membership terms.""" - terms: list[Mapping[str, object] | Condition | ColumnRef | None] = [] + """Translate shorthand in mapping-then-keyword order, retaining its equality checks.""" + explicit: list[Condition | ColumnRef | None] = [] + scalar_mappings: list[dict[str, object]] = [] + ordered: list[str | Condition] = [] - def equalities(mapping: Mapping[str, object]) -> dict[str, object]: + def split(mapping: Mapping[str, object]) -> dict[str, object]: scalar: dict[str, object] = {} for column, value in mapping.items(): if isinstance(value, (list, tuple, set, frozenset)): - terms.append(col(column).is_in(value)) + ordered.append(col(column).is_in(value)) else: scalar[column] = value + ordered.append(column) return scalar for argument in conditions: - terms.append( - equalities(argument) if isinstance(argument, Mapping) else argument - ) - keywords = equalities(columns) - return Condition.of(*terms, **keywords) + if isinstance(argument, Mapping): + scalar_mappings.append(split(argument)) + else: + explicit.append(argument) + keywords = split(columns) + if all(isinstance(part, str) for part in ordered): + return Condition.of(*conditions, **columns) + + # Let Condition.of compare repeated scalar values across mappings and keywords. + # Then place the resulting equalities alongside membership in shorthand order. + equalities = ( + Condition.of(*scalar_mappings, **keywords).equalities + if any(scalar_mappings) or keywords + else {} + ) + shorthand = [ + col(part) == equalities[part] if isinstance(part, str) else part + for part in ordered + ] + return Condition.of(*explicit, *shorthand) class SpiralDBTableSource(RootSource): diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 4e4cb9f1b..4da35f342 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -3234,9 +3234,10 @@ def test_fake_date64_point_literal_retains_milliseconds(project): def test_uint8_scan_validation_agrees_with_sdk_encoder(project, bad): sdk = pytest.importorskip("spiral") members = [0, 2, bad, 17] + for control in (0, 2, 17): + sdk.literal(control, pa.uint8()) with pytest.raises((TypeError, ValueError)): - for member in members: - sdk.literal(member, pa.uint8()) + sdk.literal(bad, pa.uint8()) rows = pa.table({"k": pa.array([0, 2], pa.uint8()), "payload": [10, 20]}) keys = pa.schema([rows.schema.field("k")]) @@ -3245,3 +3246,42 @@ def test_uint8_scan_validation_agrees_with_sdk_encoder(project, bad): with pytest.raises(TypeError, match="column 'k' holds uint8"): list(connector.scan_batches("small_key", where=col("k").is_in(members))) assert fake_spiral_sdk.scan_log == [] + + +def test_mixed_where_shorthand_displays_mapping_then_keyword_order(project, tmp_path): + source = _source(source_id="events", tag_only_columns=True) + first = source.where( + {"subject_id": "m1", "timestamp": [3, 2]}, flag=True, note=["n3", "n2"] + ) + second = source.where( + {"timestamp": [2, 3], "subject_id": "m1"}, note=["n2", "n3"], flag=True + ) + expected = ( + "subject_id='m1', timestamp in [2, 3], flag=True, note in ['n2', 'n3']", + "timestamp in [2, 3], subject_id='m1', note in ['n2', 'n3'], flag=True", + ) + + for index, (restricted, text) in enumerate( + zip((first, second), expected, strict=True) + ): + assert restricted.condition.text() == text + summary = TestRunsAndSavedJobs._job( + tmp_path / f"store{index}", restricted, [] + ).run() + assert text in repr(summary) + assert restricted.content_hash() == source.content_hash() + assert restricted.pipeline_hash() == source.pipeline_hash() + assert restricted.source_id == source.source_id + + assert first.condition == second.condition + assert hash(first.condition) == hash(second.condition) + assert first.condition.canonical_form() == second.condition.canonical_form() + assert first.to_config() == second.to_config() + + +def test_mixed_where_shorthand_keeps_conflicting_equality_diagnostics(project): + source = _source() + with pytest.raises(ValueError, match="named twice in one call.*as a keyword"): + source.where({"subject_id": "m1", "timestamp": [2, 3]}, subject_id="m2") + with pytest.raises(ValueError, match="named twice in one call.*in two mappings"): + source.where({"subject_id": "m1", "timestamp": [2, 3]}, {"subject_id": "m2"}) From f1854d1d1f7510f4ebfcc40e081d476228b1733e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 20:03:13 -0800 Subject: [PATCH 11/12] fix(spiraldb): preserve positional restriction order --- .../core/sources/spiraldb_table_source.py | 31 ++++++-------- .../test_spiraldb_table_source_where.py | 42 +++++++++++++++++++ 2 files changed, 55 insertions(+), 18 deletions(-) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 9e27c042b..7f1350811 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -211,10 +211,10 @@ def _where_condition( *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object, ) -> Condition: - """Translate shorthand in mapping-then-keyword order, retaining its equality checks.""" - explicit: list[Condition | ColumnRef | None] = [] + """Expand mappings at their argument positions, followed by keywords.""" scalar_mappings: list[dict[str, object]] = [] - ordered: list[str | Condition] = [] + scalar_positions: dict[int, str] = {} + ordered: list[Condition | ColumnRef | None] = [] def split(mapping: Mapping[str, object]) -> dict[str, object]: scalar: dict[str, object] = {} @@ -223,30 +223,25 @@ def split(mapping: Mapping[str, object]) -> dict[str, object]: ordered.append(col(column).is_in(value)) else: scalar[column] = value - ordered.append(column) + scalar_positions[len(ordered)] = column + ordered.append(None) return scalar for argument in conditions: if isinstance(argument, Mapping): scalar_mappings.append(split(argument)) else: - explicit.append(argument) + ordered.append(argument) keywords = split(columns) - if all(isinstance(part, str) for part in ordered): + if all(part is None for part in ordered): return Condition.of(*conditions, **columns) - # Let Condition.of compare repeated scalar values across mappings and keywords. - # Then place the resulting equalities alongside membership in shorthand order. - equalities = ( - Condition.of(*scalar_mappings, **keywords).equalities - if any(scalar_mappings) or keywords - else {} - ) - shorthand = [ - col(part) == equalities[part] if isinstance(part, str) else part - for part in ordered - ] - return Condition.of(*explicit, *shorthand) + if scalar_positions: + # Check repeated scalar values across all mappings and keywords together. + equalities = Condition.of(*scalar_mappings, **keywords).equalities + for index, column in scalar_positions.items(): + ordered[index] = col(column) == equalities[column] + return Condition.of(*ordered) class SpiralDBTableSource(RootSource): diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py index 4da35f342..bc83d45a1 100644 --- a/tests/test_core/sources/test_spiraldb_table_source_where.py +++ b/tests/test_core/sources/test_spiraldb_table_source_where.py @@ -3285,3 +3285,45 @@ def test_mixed_where_shorthand_keeps_conflicting_equality_diagnostics(project): source.where({"subject_id": "m1", "timestamp": [2, 3]}, subject_id="m2") with pytest.raises(ValueError, match="named twice in one call.*in two mappings"): source.where({"subject_id": "m1", "timestamp": [2, 3]}, {"subject_id": "m2"}) + + +def test_where_keeps_positional_conditions_on_either_side_of_mapping(project): + source = _source() + mapping = {"note": ["n4"]} + explicit = col("channel").is_in([0]) + first = source.where(mapping, explicit) + second = source.where(explicit, mapping) + + assert first.condition.text() == "note in ['n4'], channel in [0]" + assert second.condition.text() == "channel in [0], note in ['n4']" + assert first.condition == second.condition + assert hash(first.condition) == hash(second.condition) + assert first.condition.canonical_form() == second.condition.canonical_form() + assert first.content_hash() == second.content_hash() == source.content_hash() + assert first.pipeline_hash() == second.pipeline_hash() == source.pipeline_hash() + assert first.source_id == second.source_id == source.source_id + assert first.to_config() == second.to_config() + + +@pytest.mark.parametrize( + ("mapping_first", "pushed_column"), + [(True, "note"), (False, "channel")], + ids=["mapping-first", "explicit-first"], +) +def test_where_positional_order_selects_membership_pushdown( + project, mapping_first, pushed_column +): + source = _source() + mapping = {"flag": True, "note": ["n4", *(f"miss{i}" for i in range(299))]} + explicit = col("channel").is_in([0, *range(1000, 1299)]) + arguments = (mapping, explicit) if mapping_first else (explicit, mapping) + assert source.where(*arguments).as_table()["timestamp"].to_pylist() == [4] + + (scan,) = fake_spiral_sdk.scan_log + pending = [scan.filter] + pushed = set() + while pending: + predicate = pending.pop() + pushed.update(name for name, _, _ in predicate.terms) + pending.extend(child for pair in predicate.disjunctions for child in pair) + assert pushed == {"flag", pushed_column} From 7667ad281456826fffef4e6647bb0cf07528d047 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 4 Dec 2026 20:52:33 -0800 Subject: [PATCH 12/12] docs(changelog): record keyed scan validation changes --- changelog.d/ITL-1986.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/changelog.d/ITL-1986.md b/changelog.d/ITL-1986.md index 988c5ffd4..d2724422a 100644 --- a/changelog.d/ITL-1986.md +++ b/changelog.d/ITL-1986.md @@ -2,6 +2,11 @@ - Restrict a keyed SpiralDB source to a set of values with `where(col(column).is_in(values))`. The restriction preserves source, pipeline and record identities. +### Changed + +- Direct scans through the keyed connector validate every equality and membership literal against the column's stored type before scanning. A value the column cannot represent exactly raises `TypeError`, including an inexact float16 or float32 value, an out-of-range integer, or a fractional value for an integer column. Some of these scans previously returned no rows. +- Keyed scans apply local conditions and the row limit before checking recorded nullability. A null in a discarded row no longer fails the read. A null in a returned row still raises if the column is recorded as non-nullable. + ### Known limitations - Large, sparse memberships without an eligible fixed key prefix can scan a wide key range and transfer many nonmatching rows for local filtering.