Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions changelog.d/ITL-1986.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
### 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.

### 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.
47 changes: 34 additions & 13 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -767,16 +766,16 @@ 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
counts them. A bound is checked as an equality value is: exactly of the column's Python type
(`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
Expand Down Expand Up @@ -829,14 +828,16 @@ 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
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
Expand Down Expand Up @@ -914,6 +915,25 @@ 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 how
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.
- **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`.
Expand All @@ -923,10 +943,11 @@ 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
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
Expand Down
101 changes: 75 additions & 26 deletions src/orcapod/core/sources/spiraldb_table_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -207,6 +207,43 @@ def spiraldb_table_address(
return address


def _where_condition(
*conditions: Mapping[str, object] | Condition | ColumnRef | None,
**columns: object,
) -> Condition:
"""Expand mappings at their argument positions, followed by keywords."""
scalar_mappings: list[dict[str, object]] = []
scalar_positions: dict[int, str] = {}
ordered: list[Condition | ColumnRef | None] = []

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)):
ordered.append(col(column).is_in(value))
else:
scalar[column] = value
scalar_positions[len(ordered)] = column
ordered.append(None)
return scalar

for argument in conditions:
if isinstance(argument, Mapping):
scalar_mappings.append(split(argument))
else:
ordered.append(argument)
keywords = split(columns)
if all(part is None for part in ordered):
return Condition.of(*conditions, **columns)

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):
"""A read-only Source over a table in a SpiralDB dataset, read in batches.

Expand Down Expand Up @@ -264,9 +301,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
Expand Down Expand Up @@ -359,11 +395,16 @@ 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 membership before merging. Scalar equalities need the table schema.
try:
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):
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}"
Expand All @@ -390,8 +431,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)
Expand Down Expand Up @@ -571,37 +610,48 @@ 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. 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
``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.

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.
Expand All @@ -627,18 +677,17 @@ 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_float_equalities(*conditions, **columns)
# 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
condition = Condition.of(*conditions, **columns)
condition = _where_condition(*conditions, **columns)
restricted = self._copy()
try:
restricted._apply_restriction(condition)
Expand Down Expand Up @@ -696,7 +745,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.
"""
Expand Down Expand Up @@ -968,7 +1017,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=<n> or a narrower where= or where(...) (equalities, and ranges "
"with limit=<n> 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)."
)
Expand Down
Loading
Loading