diff --git a/changelog.d/ITL-1374.md b/changelog.d/ITL-1374.md index 0632ab2b6..dffe6fe74 100644 --- a/changelog.d/ITL-1374.md +++ b/changelog.d/ITL-1374.md @@ -6,9 +6,11 @@ `col("unit").is_in([3, 7])`, `col("t") >= 1.0`, `col("t").between(0.5, 2.0)`, `col("rate").is_null()`, `col("info").field("kind") != "noise"` (a field of a struct column), `col("a") < col("b")`, combined with `&`, `|` and `~`. Values are checked against - their column's type and never converted; a null makes a comparison unknown and drops the - row (SQL's rule); floats match as Orcapod matches them everywhere (`0.0` equals `-0.0`, - NaN equals NaN and sorts above every number). The operator's identity is an order-free + their column's type and never converted; a null makes a comparison unknown (SQL's + rule), and a row is dropped when its whole condition is false or unknown, so + `col("rate").is_null() | (col("rate") > 1.0)` keeps the null rows; floats match as + Orcapod matches them everywhere (`0.0` equals `-0.0`, NaN equals NaN and sorts above every + number). The operator's identity is an order-free canonical form of its condition. `Filter` is provisional: its identity is not frozen yet. - `orcapod.types.Condition` holds these conditions as a tree (`Condition.root`), with `canonical_form()`, and `to_config()` / `from_config()` for every kind; a condition of diff --git a/changelog.d/ITL-1378.md b/changelog.d/ITL-1378.md new file mode 100644 index 000000000..4135b8030 --- /dev/null +++ b/changelog.d/ITL-1378.md @@ -0,0 +1,9 @@ +### Added + +- A `Filter` step changes only which rows flow (ITL-1378): its output has its input's + columns, Arrow types, nullability, system tags, source info and row order, and every + value passes through bit for bit (the rows are taken with an Arrow mask, with no Polars + round trip). `col(c).is_not_null()` keeps the rows but does not narrow `T | None` to + `T`; `drop_nulls(c)` does. A filter whose condition does not fit its input's Arrow types + (an integer outside its column's range, a naive datetime for a zoned column) raises + `InputValidationError` when it is applied, on the sync and the async path alike. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 009155368..d1b407571 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -999,7 +999,7 @@ The provisional operators are listed in one place: from orcapod.operators import PROVISIONAL_OPERATORS print(sorted(PROVISIONAL_OPERATORS)) -# ['AddTags', 'Batch', 'GroupBy', 'Index', 'MapColumns', 'MapTags', 'MergeJoin', 'Pick', 'PolarsFilter', 'Rejoin', 'TagBy'] +# ['AddTags', 'Batch', 'Filter', 'GroupBy', 'Index', 'MapColumns', 'MapTags', 'MergeJoin', 'Pick', 'PolarsFilter', 'Rejoin', 'TagBy'] ``` They are the operators whose identity choice is not yet obvious and solid (developer, @@ -1014,6 +1014,7 @@ November 19, 2026). Each name maps to the issue that decides its identity or out | `Pick`, `Index` | the policy for a miss, which changes the output (ITL-439) | | `PolarsFilter` | whether the order of its predicates belongs to its identity (ITL-1247) | | `TagBy`, `AddTags` | days old, their identities just changed: the review of the tag operators (ITL-1290) | +| `Filter` | new: a row filter over a condition, provisional until its first use has shown what the canonical form of a condition must hold (ITL-1374) | | `Rejoin` | new: puts the branches of one stream back together by matching system tags (ITL-1336); its matching rule changed in this release (ITL-1355) | Every other operator is frozen with data context v1: `Join`, `SemiJoin`, `MapData`, the diff --git a/src/orcapod/core/operators/__init__.py b/src/orcapod/core/operators/__init__.py index ceb11a8a6..a5975963c 100644 --- a/src/orcapod/core/operators/__init__.py +++ b/src/orcapod/core/operators/__init__.py @@ -9,6 +9,7 @@ SelectTagColumns, ) from .drop_nulls import DropNulls +from .filter import Filter from .filters import PolarsFilter from .group_by import GroupBy from .index import Index @@ -38,6 +39,7 @@ "SelectColumns", "DropColumns", "PolarsFilter", + "Filter", "DropNulls", "AddTags", "Pick", diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py new file mode 100644 index 000000000..fd7405a1e --- /dev/null +++ b/src/orcapod/core/operators/filter.py @@ -0,0 +1,322 @@ +"""Filter: keep the rows that satisfy a ``Condition`` (ITL-1374, ITL-1378). + +A step of the pipeline: its identity is the condition's canonical form, so it enters +every hash downstream. The rows are chosen by an Arrow mask (``filter_mask``) and taken +with ``Table.filter``, so every value passes through bit for bit; no Polars. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from typing import TYPE_CHECKING, Any, ClassVar + +from orcapod.channels import ReadableChannel, WritableChannel +from orcapod.core.data_tags import stream_data_tags +from orcapod.core.operators.base import UnaryOperator +from orcapod.core.operators.filter_mask import ( + check_filter_condition, + condition_mask, + filter_table, +) +from orcapod.core.operators.meta_columns import WithoutMetaWriter +from orcapod.core.streams.arrow_table_stream import ArrowTableStream +from orcapod.errors import InputValidationError +from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.system_constants import constants +from orcapod.types import ColumnConfig, ContentHash, Schema +from orcapod.types.condition import Condition, check_condition_columns +from orcapod.utils.lazy_module import LazyModule + +if TYPE_CHECKING: + import pyarrow as pa +else: + pa = LazyModule("pyarrow") + + +def _user_columns( + tag_columns: Sequence[str], data_columns: Sequence[str] +) -> tuple[str, ...]: + """Return the columns a condition may name: user tags and data, data-tags once. + + Meta columns are left out: a stream built straight from a table lists them among + its data columns (ITL-846), and they are not user columns. + """ + return tuple( + dict.fromkeys( + name + for name in (*tag_columns, *data_columns) + if not name.startswith(constants.META_PREFIX) + ) + ) + + +class Filter(UnaryOperator): + """Keep the rows that satisfy a condition; every value passes through as it is. + + The condition is a ``Condition`` (``orcapod.types``): column equalities and the + terms ``col(name)`` builds (comparisons, ``is_in``, ``between``, null tests, + struct fields, column against column), combined with ``&``, ``|`` and ``~``. + Tag columns, data columns and data-tags are named alike. Nulls follow Kleene + logic (a row whose condition is unknown is dropped) and floats Orcapod's matching + rule (``0.0`` equals ``-0.0``, NaN equals NaN and is greater than every number). + + The output has the input's columns, types and nullability (``is_not_null`` does + not narrow ``T | None``: ``DropNulls`` does), system tags (names and values), + source info and row order. Only the rows change. + + The operator's identity is ``("Filter", condition.canonical_form())``: the order + of keywords, arguments, operands and ``is_in`` values never changes it. + + Filter is provisional (``PROVISIONAL_OPERATORS``): its identity may change in a + later release. + + Args: + condition: The condition, or a mapping of column equalities. + + Raises: + ValueError: If the condition names no column. + TypeError: If ``condition`` is neither a condition nor a mapping. + """ + + # Data-tags (ITL-1023): a data-tag is one column, named alike as tag or data. + DATA_TAGS_ISSUE: ClassVar[str | None] = None + + # A filter chooses rows and never changes a column (ITL-912). + OUTPUT_SCHEMA_IS_INPUT_SCHEMA: ClassVar[bool] = True + + # Its head shows the matching rows of its input's head (decision 13, ITL-1374). + HEAD_FROM_INPUT_HEAD: ClassVar[bool] = True + + # Its identity is not frozen with data context v1 (ITL-1374). + PROVISIONAL: ClassVar[bool] = True + + def __init__( + self, condition: Condition | Mapping[str, object], **kwargs: Any + ) -> None: + self._condition: Condition = Condition.of(condition) + super().__init__(**kwargs) + + @property + def condition(self) -> Condition: + """The condition every kept row satisfies.""" + return self._condition + + def identity_structure(self) -> Any: + """Return the operator's identity: its class name and the canonical condition. + + Returns: + ``("Filter", condition.canonical_form())``. + """ + self._note_provisional_identity_use() # a direct read is a use (ITL-1279) + return (self.__class__.__name__, self._condition.canonical_form()) + + def to_config(self) -> dict[str, Any]: + """Serialize this operator to a config dict. + + Returns: + A dict with ``class_name``, ``module_path`` and ``config`` keys, where + ``config`` holds ``condition``, the condition's saved form + (``Condition.to_config``). + """ + config = super().to_config() + config["config"] = {"condition": self._condition.to_config()} + return config + + @classmethod + def from_config(cls, config: dict[str, Any]) -> Filter: + """Reconstruct a Filter from a config dict. + + Args: + config: Dict as returned by ``to_config()``. + + Returns: + A new ``Filter`` with the saved condition. + """ + return cls(Condition.from_config(config["config"]["condition"])) + + # ------------------------------------------------------------------ + # Validation and schema prediction + # ------------------------------------------------------------------ + + def validate_unary_input(self, stream: StreamProtocol) -> None: + """Check the condition against the stream's Python schema (graph build). + + Every column a term names must be a user tag or data column, and a value + term's value of the column's Python type. Struct fields, Arrow widths, + ranges and time zones are checked when the filter is applied. + + Args: + stream: The upstream stream. + + Raises: + InputValidationError: If a column is missing or a value does not fit it. + """ + tag_schema, data_schema = stream.output_schema() + names = _user_columns(tuple(tag_schema), tuple(data_schema)) + python_schema = { + name: tag_schema[name] if name in tag_schema else data_schema[name] + for name in names + } + try: + check_condition_columns(self._condition, python_schema) + except (TypeError, ValueError) as error: + raise InputValidationError(f"Filter: {error}") from error + + def unary_output_schema( + self, + stream: StreamProtocol, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[Schema, Schema]: + """Return the input's schemas: a filter changes no column. + + Args: + stream: The upstream stream. + columns: Column inclusion config passed through to ``output_schema``. + all_info: Whether to include all info columns. + + Returns: + A ``(tag_schema, data_schema)`` tuple. + """ + return stream.output_schema(columns=columns, all_info=all_info) + + # ------------------------------------------------------------------ + # Execution + # ------------------------------------------------------------------ + + def _check_arrow(self, schema: pa.Schema, names: Sequence[str]) -> None: + """Check the condition against the Arrow types of the user columns ``names``. + + Raises: + InputValidationError: If a field is missing, or a value or a column's + type does not fit its term. + """ + check_filter_condition( + self._condition, pa.schema([schema.field(name) for name in names]) + ) + + def head_rows(self, stream: StreamProtocol, table: pa.Table) -> pa.Table | None: + """The rows of ``table`` (what ``stream``'s ``head`` shows) the condition keeps. + + Decision 13 of ITL-1374: a filter holds no user code, has no effect and keeps a + row by that row alone, so its head may evaluate the condition over the rows its + input's head shows. This is the plain stream's head: a filter captured + in a job is a job node, which shows its current run (ITL-1095) and so reads not + computed before its first run. Nothing is computed, polled or written. A condition that does + not fit the input's Arrow types shows nothing here; its error appears at the run. + + Args: + stream: The input. + table: The rows its head shows. + + Returns: + The matching rows, without meta columns, or ``None`` when the condition does + not fit ``table``. + """ + names = _user_columns(*stream.keys()) + try: + self._check_arrow(table.schema, names) + except InputValidationError: + return None + meta = [n for n in table.column_names if n.startswith(constants.META_PREFIX)] + return filter_table(table.drop_columns(meta), self._condition) + + def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: + """Return the stream's rows that satisfy the condition, in input order. + + Args: + stream: The upstream stream. + + Returns: + A stream over the kept rows, every column as it is. A result with no + rows has the same columns and types. + + Raises: + InputValidationError: If the condition does not fit the input's Arrow + types. + """ + # Every system column passes through: source info, system tags and each row's + # data context (a raw stream may hold several). + table = stream.as_table( + columns={ + "source": True, + "system_tags": True, + "context": True, + "sort_by_tags": False, + } + ) + tag_columns, data_columns = stream.keys() + self._check_arrow(table.schema, _user_columns(tag_columns, data_columns)) + return ArrowTableStream( + filter_table(table, self._condition), + tag_columns=tag_columns, + data_tags=stream_data_tags(stream), + data_context=stream.data_context_key, + ) + + async def async_execute( + self, + inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]], + output: WritableChannel[tuple[TagProtocol, DataProtocol]], + *, + input_pipeline_hashes: Sequence[ContentHash], + ) -> None: + """Streaming: test each row as it arrives and pass the kept ones on. + + Each row's user columns are read from its tag and data Arrow tables into one + one-row table, and the kernel of the sync path decides whether it is kept. A + kept row is passed on as it arrived (without its meta columns), so its values, + types and system tags are those of the sync path. + + On this channel path the condition is checked against each row's Arrow types, + the only schema the channel carries: an input with no rows is never checked, and + a raw stream's Arrow ``null`` column arrives as ``large_string`` (``Data``'s null + convention, ITL-1319), so a condition its sync path refuses on either can pass + here. A job run (either orchestrator) checks its input's Arrow schema before any + row, as the sync path does, and refuses both; no source holds a ``null`` column. + + Args: + inputs: Single-element sequence of readable channels. + output: Channel to send kept rows to. + input_pipeline_hashes: Not used: a filter keeps system-tag names as they + are. + """ + try: + output = WithoutMetaWriter(output) + # Schemas already checked; a list, since a schema holding a logical type + # is not hashable. + checked: list[pa.Schema] = [] + async for tag, data in inputs[0]: + row = self._row_table(tag, data) + if not any(row.schema.equals(seen) for seen in checked): + self._check_arrow(row.schema, row.column_names) + checked.append(row.schema) + mask = condition_mask(row, self._condition) + if mask.to_pylist() == [True]: + await output.send((tag, data)) + finally: + await output.close() + + @staticmethod + def _row_table(tag: TagProtocol, data: DataProtocol) -> pa.Table: + """Return one row's user tag and data columns as a one-row table. + + A data-tag is one column, read from the tag. + """ + tag_table = tag.as_table() + data_table = data.as_table() + names = _user_columns(tag_table.column_names, data_table.column_names) + columns = [ + tag_table.column(name) + if name in tag_table.column_names + else data_table.column(name) + for name in names + ] + fields = [ + tag_table.schema.field(name) + if name in tag_table.column_names + else data_table.schema.field(name) + for name in names + ] + return pa.Table.from_arrays(columns, schema=pa.schema(fields)) diff --git a/src/orcapod/core/operators/filter_mask.py b/src/orcapod/core/operators/filter_mask.py new file mode 100644 index 000000000..2715353a1 --- /dev/null +++ b/src/orcapod/core/operators/filter_mask.py @@ -0,0 +1,270 @@ +"""The mask kernel of ``Filter`` (ITL-1378): a ``Condition`` to an Arrow boolean mask. + +``check_filter_condition`` checks a condition against a table's Arrow schema (the one rule, +``orcapod.types.condition.check_condition``); ``condition_mask`` then evaluates it and +returns one boolean per row: ``True`` keeps the row, ``False`` or null drops it +(``table.filter(mask, null_selection_behavior="drop")``). Every path of the operator (sync, +async) uses them, so they keep the same rows. + +The rules (docs/dev/specs/itl-1374-filter.md, sections 2.3 to 2.6): + +- Nulls follow Kleene logic: a comparison with a null is null (unknown), ``&`` / ``|`` / + ``~`` are ``and_kleene`` / ``or_kleene`` / ``invert``. Null tests are never null. +- Floats follow Orcapod's matching rule, not IEEE: ``0.0`` equals ``-0.0``, NaN equals NaN, + and NaN is greater than every number (Polars' total order, the order ``GroupBy`` uses). +- A literal is compared in its column's type: an integer at the column's width, a float + rounded to the column's width, a timestamp as a count of the column's unit. +- A struct field is read with ``pc.struct_field`` (a null struct gives a null field); a + user class column through its storage struct. + +Only the mask is computed here: no value of the table is converted or rewritten. A column +may be cast for the comparison only (``float16`` to ``float32``, a layout to its large +variant), which changes no row the filter keeps. +""" + +from __future__ import annotations + +import math +import struct +from collections.abc import Sequence +from datetime import date, datetime, timezone +from typing import TYPE_CHECKING, Any, TypeAlias + +from orcapod.errors import InputValidationError +from orcapod.types.condition import ( + AllOf, + ColumnOperand, + Condition, + FieldPath, + Negation, + Node, + Term, + check_condition, +) +from orcapod.utils import arrow_utils +from orcapod.utils.datetime_utils import instant_microseconds +from orcapod.utils.lazy_module import LazyModule + +if TYPE_CHECKING: + import pyarrow as pa + import pyarrow.compute as pc +else: + pa = LazyModule("pyarrow") + pc = LazyModule("pyarrow.compute") + + +EQ, NE, LT, LE, GT, GE = "==", "!=", "<", "<=", ">", ">=" +IS_IN, IS_NULL, IS_NOT_NULL = "is_in", "is_null", "is_not_null" + +_Values: TypeAlias = Any # pyright: ignore[reportExplicitAny] # a column, a mask or a scalar: pyarrow's stubs type each compute kernel per argument kind, and these flow between chunked arrays, arrays and scalars +"""What the kernel passes between Arrow compute calls.""" + +# The comparison ``a b`` is ``b a``. +_SWAPPED = {LT: GT, LE: GE, GT: LT, GE: LE, EQ: EQ, NE: NE} + +_EPOCH_MICROSECONDS = (date(1970, 1, 1).toordinal() - 1) * 86_400_000_000 +_MICROSECONDS_PER_UNIT = {"s": 1_000_000, "ms": 1_000, "us": 1} + + +def check_filter_condition(condition: Condition, schema: pa.Schema) -> None: + """Check ``condition`` against the Arrow types of a table's user columns. + + Args: + condition: The condition. + schema: The user tag and data columns (no system, source-info or meta column). + + Raises: + InputValidationError: If a column or field is missing, a value does not fit its + column, or an operator does not apply to a column's type + (``check_condition``'s rule). + """ + try: + check_condition(condition, schema) + except (TypeError, ValueError) as error: + raise InputValidationError(f"Filter: {error}") from error + + +def _compute_form(values: _Values) -> _Values: + """Return ``values`` as Arrow compute compares them: ``float16`` as ``float32``. + + An exact widening, for the mask only. + """ + if pa.types.is_float16(values.type): + return values.cast(pa.float32()) + return values + + +def _resolve(table: pa.Table, path: FieldPath) -> _Values: + """Return the values ``path`` names in ``table`` (checked by ``check_condition``).""" + values = table.column(path.column) + for name in path.fields: + if isinstance(values.type, pa.ExtensionType): + # A user class column: its storage struct holds its declared fields. + storage_type = values.type.storage_type + values = pa.chunked_array( + [chunk.storage for chunk in values.chunks], # pyright: ignore[reportAttributeAccessIssue] # chunks of an extension column are extension arrays + type=storage_type, + ) + values = pc.struct_field(values, [values.type.get_field_index(name)]) + return values + + +def _literal_scalar(arrow_type: pa.DataType, value: object) -> _Values: + """Return a checked literal as a scalar compared in its column's type. + + ``check_condition`` has checked that ``value`` is of the column's Python type and + that the column holds it (a float: within its range). A float is rounded to the + column's width (``float16`` columns are compared as ``float32``, an exact widening); + a timestamp is the count of the column's unit since the epoch. + """ + if pa.types.is_floating(arrow_type): + assert isinstance(value, float) + if pa.types.is_float64(arrow_type): + return pa.scalar(value, type=pa.float64()) + if pa.types.is_float16(arrow_type) and math.isfinite(value): + (value,) = struct.unpack("e", struct.pack("e", value)) + return pa.scalar(value, type=pa.float32()) + if pa.types.is_string(arrow_type) or pa.types.is_large_string(arrow_type): + return pa.scalar(value, type=pa.large_string()) + if pa.types.is_binary(arrow_type) or pa.types.is_large_binary(arrow_type): + return pa.scalar(value, type=pa.large_binary()) + if pa.types.is_timestamp(arrow_type): + assert isinstance(value, datetime) + instant = instant_microseconds(value) + if instant is None: + # A naive value against a naive column: its wall time, read as UTC. + instant = instant_microseconds(value.replace(tzinfo=timezone.utc)) + assert instant is not None + micros = instant - _EPOCH_MICROSECONDS + unit = arrow_type.unit + count = ( + micros * 1_000 if unit == "ns" else micros // _MICROSECONDS_PER_UNIT[unit] + ) + return pa.scalar(count, type=arrow_type) + return pa.scalar(value, type=arrow_type) + + +def _null_where_any_null(result: _Values, *operands: _Values) -> _Values: + """Return ``result`` with a null wherever an operand is null (unknown).""" + valid = pc.is_valid(operands[0]) + for operand in operands[1:]: + valid = pc.and_(valid, pc.is_valid(operand)) + return pc.if_else(valid, result, pa.scalar(None, type=pa.bool_())) + + +def _float_compare(op: str, left: _Values, right: _Values) -> _Values: + """Compare two float operands (arrays or scalars) by Orcapod's float rule. + + ``0.0`` equals ``-0.0``, NaN equals NaN, NaN is greater than every number. The + result is not yet null where an operand is null; the caller sets those. + """ + left_nan = pc.is_nan(left) + right_nan = pc.is_nan(right) + if op in (EQ, NE): + equal = pc.or_(pc.equal(left, right), pc.and_(left_nan, right_nan)) + return equal if op == EQ else pc.invert(equal) + if op in (GT, GE): + return _float_compare(_SWAPPED[op], right, left) + if op == LT: + # left < right: numbers by IEEE, or a number below a NaN. + return pc.or_(pc.less(left, right), pc.and_(pc.invert(left_nan), right_nan)) + # LE: numbers by IEEE, or anything (NaN included) below a NaN. + return pc.or_(pc.less_equal(left, right), right_nan) + + +_ARROW_COMPARE = { + EQ: pc.equal, + NE: pc.not_equal, + LT: pc.less, + LE: pc.less_equal, + GT: pc.greater, + GE: pc.greater_equal, +} + + +def _compare(op: str, left: _Values, right: _Values, floats: bool) -> _Values: + """Compare ``left`` with ``right`` (an array or a scalar) by ``op``, Kleene nulls.""" + if floats: + # Nulls in the result are set below, whatever the float rule gives them. + result = _float_compare(op, left, right) + else: + result = _ARROW_COMPARE[op](left, right) + if isinstance(right, pa.Scalar): + return _null_where_any_null(result, left) + return _null_where_any_null(result, left, right) + + +def _term_mask(table: pa.Table, term: Term) -> _Values: + """Return the mask of one checked term over ``table``.""" + values = _resolve(table, term.path) + if term.operator == IS_NULL: + return pc.is_null(values) + if term.operator == IS_NOT_NULL: + return pc.is_valid(values) + arrow_type = values.type + floats = pa.types.is_floating(arrow_type) + computed = _compute_form(values) + if term.operator == IS_IN: + assert isinstance(term.value, tuple) + scalars = [_literal_scalar(arrow_type, v) for v in term.value] + if floats: + # Arrow's is_in does not equate 0.0 with -0.0: one equality per value. + result = _float_compare(EQ, computed, scalars[0]) + for scalar in scalars[1:]: + result = pc.or_(result, _float_compare(EQ, computed, scalar)) + else: + set_type = scalars[0].type + value_set = pa.array([s.as_py() for s in scalars], type=set_type) + result = pc.is_in(computed.cast(set_type), value_set=value_set) + return _null_where_any_null(result, values) + if isinstance(term.value, ColumnOperand): + other = _compute_form(_resolve(table, term.value.path)) + # One type after large normalization (checked): compared in the large layout. + large = arrow_utils.normalize_to_large_types(computed.type, keep_null=True) + return _compare(term.operator, computed.cast(large), other.cast(large), floats) + scalar = _literal_scalar(arrow_type, term.value) + return _compare(term.operator, computed.cast(scalar.type), scalar, floats) + + +def _node_mask(table: pa.Table, node: Node) -> _Values: + if isinstance(node, Term): + return _term_mask(table, node) + if isinstance(node, Negation): + return pc.invert(_node_mask(table, node.child)) + if not node.children: + # An empty AND holds everywhere; an empty OR nowhere. + return pa.chunked_array( + [pa.array([isinstance(node, AllOf)] * table.num_rows, type=pa.bool_())] + ) + combine = pc.and_kleene if isinstance(node, AllOf) else pc.or_kleene + result = _node_mask(table, node.children[0]) + for child in node.children[1:]: + result = combine(result, _node_mask(table, child)) + return result + + +def condition_mask(table: pa.Table, condition: Condition) -> _Values: + """Return the mask of ``condition`` over ``table``: ``True`` keeps a row, ``False`` + or null (unknown) drops it. + + The condition must have passed ``check_filter_condition`` against ``table``'s user + columns; nothing is checked here. + + Args: + table: The rows; the condition's columns are columns of it. + condition: The checked condition. + + Returns: + One boolean (or null) per row of ``table``. + """ + return _node_mask(table, condition.root) + + +def filter_table(table: pa.Table, condition: Condition) -> pa.Table: + """Return the rows of ``table`` whose checked condition holds, every value as it is.""" + return table.filter( + condition_mask(table, condition), null_selection_behavior="drop" + ) + + +__all__: Sequence[str] = ("check_filter_condition", "condition_mask", "filter_table") diff --git a/src/orcapod/core/operators/provisional.py b/src/orcapod/core/operators/provisional.py index 3575dd26a..1b6da4bfe 100644 --- a/src/orcapod/core/operators/provisional.py +++ b/src/orcapod/core/operators/provisional.py @@ -59,6 +59,9 @@ # New (developer, November 21, 2026): puts the branches of one stream back # together by matching every system-tag column (ITL-1336). "Rejoin": "ITL-1336", + # New (developer, November 22, 2026): a general row filter over a Condition; + # shipped provisional for the workshop, frozen after it (ITL-1374). + "Filter": "ITL-1374", } ) """The provisional operators: class name to the issue that decides its identity.""" diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index dbc7b13d3..6263026f0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -81,6 +81,15 @@ class StaticOutputOperatorPod(TraceableBase): predicate, so no user code runs to learn the column types (ITL-912). """ + HEAD_FROM_INPUT_HEAD: ClassVar[bool] = False + """Whether ``head`` may show this operator over the rows its input's head shows. + + Declared by an operator that keeps or drops each input row by that row alone, with + no user code and no effect (``Filter``, decision 13 of ITL-1374); its ``head_rows`` + then chooses the rows. Any other operator's head shows no rows before it is computed, + and its input's head is never asked for. + """ + PROVISIONAL: ClassVar[bool] = False """Whether the operator is provisional: its identity is not frozen (ITL-1266). @@ -502,6 +511,26 @@ def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: upstream, ) + def head_rows(self, stream: StreamProtocol, table: pa.Table) -> pa.Table | None: + """The rows ``head`` may show of this operator over ``stream``, from the rows + ``stream``'s own ``head`` shows (``table``), before the result is computed. + + Asked only when ``HEAD_FROM_INPUT_HEAD`` is set. ``None`` (the default): nothing + is shown, because the head of an operator is + not, in general, the operator over the head of its input (a group over ten rows + has the wrong members). An operator whose result row by row is a choice among + its input's rows, decided by no user code and with no effect, may answer with + the rows of ``table`` it keeps (``Filter``, decision 13 of ITL-1374). + + Args: + stream: The operator's one input. + table: The rows its ``head`` shows, with the columns it was asked for. + + Returns: + The rows to show, with ``table``'s columns, or ``None``. + """ + return None + def zero_row_result(self, *inputs: StreamProtocol) -> StreamProtocol: """This operator's result over zero-row inputs, for its zero-row table (ITL-912). @@ -1082,12 +1111,57 @@ def head( return head_of( self._cached_stream.head(n, columns=config), self, origin="computed" ) + matching = self._matching_head(n, config) + if matching is not None: + return matching return self._head_without_rows( config, ViewStatus.NOT_COMPUTED, note=STALE_NOTE if had_result else None, ) + def _matching_head(self, n: int, config: ColumnConfig) -> StreamView | None: + """The head an operator shows from its input's head (``head_rows``), or ``None``. + + Only for one input whose own ``head`` shows rows (or knows it has none), which + never computes, polls or delivers; the operator's ``head_rows`` decides. The + view says which rows were looked at: those its input's head shows. + """ + if not self._pod.HEAD_FROM_INPUT_HEAD or len(self._upstreams) != 1: + return None + (upstream,) = self._upstreams + upstream_view = head_of(upstream.head(n, columns=config), upstream) + if upstream_view.status is not ViewStatus.ROWS: + return None + rows = self._pod.head_rows(upstream, upstream_view.table) + if rows is None: + return None + looked_at = upstream_view.table.num_rows + complete = ( + upstream_view.total_rows == looked_at + and not upstream_view.total_is_estimate + ) + shown = rows.num_rows + sorting = ", sorted by tags" if upstream_view.sorted_by_tags else "" + if complete: + description = ( + f"all {shown:,} matching {'row' if shown == 1 else 'rows'} of its " + f"input's {looked_at:,}{sorting}" + ) + else: + description = ( + f"{shown:,} matching {'row' if shown == 1 else 'rows'} among the " + f"{looked_at:,} its input's head shows{sorting} (not computed; run() " + "computes every row)" + ) + return StreamView.of_rows( + self, + rows, + tag_columns=upstream_view.tag_columns, + total_rows=shown if complete else None, + description=description, + ) + def __repr__(self) -> str: # Upstreams by class and label only: their own repr would nest every path (ITL-1111). upstreams = ", ".join( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index a076f31b3..031478bb4 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -30,7 +30,7 @@ StreamProtocol, TagProtocol, ) -from orcapod.types import ColumnConfig, Schema +from orcapod.types import ColumnConfig, Condition, Schema from orcapod.utils import arrow_utils from orcapod.utils.lazy_module import LazyModule @@ -646,6 +646,42 @@ def polars_filter( self, label=label ) + def filter( + self, + *conditions: Condition | Mapping[str, object], + label: str | None = None, + **columns: object, + ) -> StreamBase: + """Keep the rows that satisfy every condition; a step of the pipeline. + + ``s.filter(session="s1")``, ``s.filter({"session": "s1"})`` and + ``s.filter(col("t") >= 1.0, col("unit").is_in([3, 7]), session="s1")``: + keywords and mappings are equalities, every other condition is built with + ``col``; all of them must hold. Tag and data columns are named alike. The + output has this stream's columns and types; only the rows change. See + ``orcapod.core.operators.Filter``. + + Args: + *conditions: Conditions (built with ``col`` or ``Condition.of``) and + mappings of column name to value. + label: Optional node label for the pipeline graph. A column named + ``label`` is written ``filter({"label": ...})`` or with ``col``. + **columns: Column name to the value it must equal. + + Returns: + A stream over the kept rows, in input order. + + Raises: + ValueError: If no condition is given. + TypeError: If an argument is neither a condition nor a mapping, or a + value is not exactly of a supported type. + InputValidationError: If a column is missing or a value does not fit + its column. + """ + from orcapod.core.operators import Filter + + return Filter(Condition.of(*conditions, **columns))(self, label=label) + def drop_nulls( self, columns: str | Collection[str] | None = None, diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 29142a2b6..3f1a4ff88 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -216,6 +216,7 @@ def _build_operator_registry() -> dict[str, type]: DropDataColumns, DropNulls, DropTagColumns, + Filter, GroupBy, Join, MapColumns, @@ -248,6 +249,7 @@ def _build_operator_registry() -> dict[str, type]: "MapData": MapData, "MapColumns": MapColumns, "PolarsFilter": PolarsFilter, + "Filter": Filter, "DropNulls": DropNulls, "TagBy": TagBy, "AddTags": AddTags, diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 010d29232..0affbe8a0 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -13,7 +13,7 @@ from orcapod.protocols.core_protocols.datagrams import DataProtocol, TagProtocol from orcapod.protocols.core_protocols.traceable import TraceableProtocol from orcapod.protocols.hashing_protocols import PipelineElementProtocol -from orcapod.types import ColumnConfig, Schema +from orcapod.types import ColumnConfig, Condition, Schema if TYPE_CHECKING: import pandas as pd @@ -432,6 +432,19 @@ def polars_filter( **constraints: Any, ) -> "StreamProtocol": ... + def filter( + self, + *conditions: Condition | Mapping[str, object], + label: str | None = None, + **columns: object, + ) -> "StreamProtocol": + """ + Keep the rows that satisfy every condition, as a step of the pipeline: + keywords and mappings are equalities, other conditions are built with + ``col``. The output has this stream's columns and types. + """ + ... + def drop_nulls( self, columns: str | Collection[str] | None = None, diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index ee0885827..89f8baf4a 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -196,11 +196,14 @@ def _condition_hash_key(value: object) -> tuple[type, object]: def _condition_value_to_config(value: object) -> object: """Return a condition value in its JSON form (date, datetime, bytes and a NaN or - infinite float tagged: ``{"float": "nan" | "inf" | "-inf"}``).""" + infinite float tagged: ``{"float": "nan" | "inf" | "-inf"}``; ``-0.0`` as ``0.0``).""" if isinstance(value, float) and not math.isfinite(value): return { _FLOAT_KEY: "nan" if value != value else ("inf" if value > 0 else "-inf") } + if isinstance(value, float) and value == 0.0: + # -0.0 is 0.0 (the float rule), so two equal conditions save one form. + return 0.0 if isinstance(value, datetime): return {_DATETIME_KEY: value.isoformat()} if isinstance(value, date): @@ -289,6 +292,9 @@ def _require_condition_value(column: object, value: object) -> None: _UTC_ORIGIN = datetime(1, 1, 1, tzinfo=timezone.utc) """0001-01-01 UTC, the origin of ``instant_microseconds``.""" +_MAX_WALL_MICROSECONDS = (datetime.max - datetime.min) // timedelta(microseconds=1) +"""The wall time ``datetime.max``, in microseconds since 0001-01-01.""" + def _frozen(value: object) -> object: """Return a condition value as a condition holds it: nothing in it calls back later. @@ -303,7 +309,9 @@ def _frozen(value: object) -> object: Every other value is returned as it is. An instant that has no UTC ``datetime`` (year 1 at a positive offset, year 9999 at - a negative one) keeps its wall time under its offset as a fixed ``timezone``. + a negative one) is held at the nearest wall time (``datetime.min`` or + ``datetime.max``) under the fixed offset that names the instant there, so its + representation depends on the instant only. """ if type(value) is not datetime: return value @@ -326,18 +334,16 @@ def _frozen(value: object) -> object: return _UTC_ORIGIN + timedelta(microseconds=instant) except OverflowError: # An instant with no UTC datetime (year 1 at a positive offset, year 9999 at a - # negative one) keeps its wall time under the offset read above, as a fixed, - # immutable timezone: still nothing calls the original tzinfo again. - return datetime( - value.year, - value.month, - value.day, - value.hour, - value.minute, - value.second, - value.microsecond, - tzinfo=fixed, - ) + # negative one) is held at the nearest wall time a datetime has, under the fixed + # offset that names the instant there. Decided by the instant alone, so every + # spelling of one instant is held, written and saved the same way. + if instant < 0: + wall = datetime.min + shift = timedelta(microseconds=-instant) + else: + wall = datetime.max + shift = timedelta(microseconds=_MAX_WALL_MICROSECONDS - instant) + return wall.replace(tzinfo=timezone(shift)) def _checked_value(column: str, value: object) -> object: @@ -1185,9 +1191,16 @@ def combined(self, other: Condition) -> Condition: The condition requiring everything both require. """ 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) for node in other._root.children: - if any(same_node(node, kept) for kept in children): + bucket = kept_by_key.setdefault(_node_hash_key(node), []) + if any(same_node(node, kept) for kept in bucket): continue + bucket.append(node) children.append(node) return Condition._of_children(tuple(children)) diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index ed87a8f66..7e1d38802 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -35,6 +35,7 @@ DropColumns, DropDataColumns, DropNulls, + Filter, DropTagColumns, GroupBy, Index, @@ -62,6 +63,7 @@ StreamProtocol, TagProtocol, ) +from orcapod.types import Condition, col from orcapod.utils import arrow_utils # The ``semijoin_shared_data_column`` case shares a data column name on purpose; SemiJoin @@ -680,6 +682,30 @@ def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: Case("index", lambda: Index("l8", 0), lambda: (source_a(),)), Case("pick", lambda: Pick("d", "q"), lambda: (source_a(),)), Case("drop_nulls", lambda: DropNulls("nul"), lambda: (source_a(),)), + Case( + "filter", + lambda: Filter(Condition.of(col("nul").is_not_null(), col("k") >= 1)), + lambda: (source_a(),), + ), + Case( + "filter_many", + # A tag, a narrow integer, a string, a struct field, a null test and membership. + lambda: Filter( + Condition.of( + col("ta").is_in([5, 6]), + col("i8") < 3, + col("st").field("y") != "c", + col("p").is_not_null(), + s="a", + ) + ), + lambda: (source_a(),), + ), + Case( + "filter_data_tags", + lambda: Filter(Condition.of(col("k") > 1)), + lambda: (source_a(with_data_tags=True),), + ), Case( "drop_nulls_many", # A nullable column with a null, one without, a tag, a non-nullable list. diff --git a/tests/test_core/operators/test_filter.py b/tests/test_core/operators/test_filter.py new file mode 100644 index 000000000..dc2663887 --- /dev/null +++ b/tests/test_core/operators/test_filter.py @@ -0,0 +1,571 @@ +"""The ``Filter`` operator (ITL-1378): ``stream.filter(...)``, a step of the pipeline. + +Through the public interface: ``stream.filter(...)`` or ``Filter(condition)(stream)``, +read back through the stream's methods. The kernel's semantics term by term are in +``test_filter_mask.py``; the arrangement, order and role matrix in +``test_several_items.py``. +""" + +from __future__ import annotations + +import itertools +import struct +import warnings +from decimal import Decimal + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col +from orcapod.core.operators import PROVISIONAL_OPERATORS, Filter, SelectDataColumns +from orcapod.core.operators.provisional import reset_provisional_operator_warnings +from orcapod.core.sources import ArrowTableSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InputValidationError, ProvisionalHashWarning +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.pipeline.serialization import _build_operator_registry # pyright: ignore[reportPrivateUsage] # the registry a saved job loads operators through +from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator +from orcapod.types import CacheMode, Condition + +from .several_items import async_rows, rows_fingerprint + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +NAN = float("nan") + + +def _units(**kwargs: object) -> ArrowTableSource: + """The design's example: tags ``session``, ``unit``; data ``t``, ``rate``, ``probe``.""" + table = pa.table( + { + "session": pa.array( + ["s1", "s1", "s1", "s2", "s2", "s3"], pa.large_string() + ), + "unit": pa.array([3, 7, 9, 3, 7, 3], pa.int64()), + "t": pa.array([0.5, 1.2, 2.0, 0.7, NAN, 3.1], pa.float64()), + "rate": pa.array([4.0, None, 2.5, 6.1, 0.0, None], pa.float64()), + "probe": pa.array( + ["imec0", "imec1", "imec0", "imec1", "imec0", "imec1"], + pa.large_string(), + ), + } + ) + options: dict[str, object] = {"tag_only_columns": True, "source_id": "units"} + options.update(kwargs) + return ArrowTableSource(table, tag_columns=["session", "unit"], **options) # pyright: ignore[reportArgumentType] + + +def _kept(stream) -> list[tuple[str, int]]: + table = stream.as_table() + return list( + zip(table.column("session").to_pylist(), table.column("unit").to_pylist()) + ) + + +S1 = [("s1", 3), ("s1", 7), ("s1", 9)] + + +class TestSpelling: + """The table of section 1 of the design, through ``stream.filter``.""" + + def test_keyword(self): + assert _kept(_units().filter(session="s1")) == S1 + + def test_several_keywords_and_mapping(self): + expected = [("s1", 3), ("s1", 9)] + assert _kept(_units().filter(session="s1", probe="imec0")) == expected + assert _kept(_units().filter({"session": "s1", "probe": "imec0"})) == expected + assert _kept(_units().filter({"probe": "imec0"}, session="s1")) == expected + + def test_is_in(self): + assert _kept(_units().filter(col("unit").is_in([3, 7]))) == [ + ("s1", 3), + ("s1", 7), + ("s2", 3), + ("s2", 7), + ("s3", 3), + ] + + def test_comparison_keeps_nan(self): + assert _kept(_units().filter(col("t") >= 1.0)) == [ + ("s1", 7), + ("s1", 9), + ("s2", 7), + ("s3", 3), + ] + + def test_between(self): + assert _kept(_units().filter(col("t").between(0.5, 2.0))) == [ + ("s1", 3), + ("s1", 7), + ("s1", 9), + ("s2", 3), + ] + + def test_null_tests(self): + assert _kept(_units().filter(col("rate").is_null())) == [("s1", 7), ("s3", 3)] + assert len(_kept(_units().filter(col("rate").is_not_null()))) == 4 + + def test_several_positional_and_keyword(self): + assert _kept(_units().filter(col("t") >= 1.0, session="s1")) == [ + ("s1", 7), + ("s1", 9), + ] + assert _kept( + _units().filter(col("t") >= 1.0, col("unit").is_in([7, 9]), session="s1") + ) == [("s1", 7), ("s1", 9)] + + def test_and(self): + assert _kept(_units().filter((col("t") >= 1.0) & (col("session") == "s1"))) == [ + ("s1", 7), + ("s1", 9), + ] + + def test_label_names_the_node_not_a_column(self): + stream = _units().filter(session="s1", label="first_session") + assert _kept(stream) == S1 + + def test_no_condition_refused(self): + with pytest.raises(ValueError): + _units().filter() + + +class TestTreeSpelling: + """``|``, ``~`` and column against column (after the workshop subset).""" + + def test_negation(self): + assert _kept(_units().filter(~col("unit").is_in([3, 7]))) == [("s1", 9)] + + def test_or(self): + stream = _units().filter((col("session") == "s3") | (col("t") < 0.6)) + assert _kept(stream) == [("s1", 3), ("s3", 3)] + + def test_column_against_column(self): + stream = _units().filter(col("rate") > col("t")) + assert _kept(stream) == [("s1", 3), ("s1", 9), ("s2", 3)] + + +class TestRoles: + """Tag, data and data-tag columns are named alike.""" + + def test_data_tag(self): + source = _units(tag_only_columns=["session"]) # ``unit`` is a data-tag + assert "unit" in source.keys()[1] + assert _kept(source.filter(col("unit") > 3)) == [ + ("s1", 7), + ("s1", 9), + ("s2", 7), + ] + + def test_conditions_on_every_role_together(self): + source = _units(tag_only_columns=["session"]) + stream = source.filter( + col("unit") >= 7, col("rate").is_not_null(), session="s1" + ) + assert _kept(stream) == [("s1", 9)] + + def test_system_columns_are_not_named(self): + source = _units() + system = [ + name + for name in source.as_table(all_info=True).column_names + if name.startswith("_") + ] + assert system + for name in system: + with pytest.raises(InputValidationError): + source.filter(col(name).is_null()) + + +class TestPassThrough: + def test_schema_is_the_input_schema(self): + source = _units() + stream = source.filter(col("t") >= 1.0) + assert stream.output_schema() == source.output_schema() + assert stream.output_schema(all_info=True) == source.output_schema( + all_info=True + ) + assert stream.keys() == source.keys() + + def test_prediction_equals_the_computed_schema(self): + source = _units(tag_only_columns=["session"]) + op = Filter(col("t") >= 1.0) + computed = op.unary_static_process(source) + for columns in (None, {"system_tags": True}, {"source": True}): + assert op(source).output_schema(columns=columns) == computed.output_schema( + columns=columns + ) + + def test_is_not_null_does_not_narrow(self): + source = _units() + stream = source.filter(col("rate").is_not_null()) + assert stream.output_schema()[1]["rate"] == source.output_schema()[1]["rate"] + table = stream.as_table() + assert table.schema.field("rate").nullable + + def test_system_tags_source_info_and_order_pass_through(self): + source = _units() + full = source.as_table(all_info=True) + kept = source.filter(col("unit").is_in([7, 9])).as_table(all_info=True) + assert kept.column_names == full.column_names + assert kept.schema == full.schema + expected = full.filter(pa.array([False, True, True, False, True, False])) + # ``t`` holds a NaN, which ``equals`` never matches: compared by its bits. + assert kept.drop_columns(["t"]).equals(expected.drop_columns(["t"])) + assert kept.column("t").combine_chunks().view(pa.int64()) == expected.column( + "t" + ).combine_chunks().view(pa.int64()) + + def test_values_bit_for_bit(self): + signalling = bytes.fromhex("0100807f") + table = pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "f32": pa.Array.from_buffers( + pa.float32(), + 3, + [None, pa.py_buffer(signalling + struct.pack("= 2)(stream).as_table(all_info=True) + assert kept["_context_key"].to_pylist() == ["held-b", "held-c"] + selected = SelectDataColumns(["v", "w"])(stream).as_table(all_info=True) + assert kept.equals(selected.filter(pa.array([False, True, True]))) + + def test_no_meta_columns(self): + table = pa.table( + { + "k": pa.array([1, 2], pa.int64()), + "v": pa.array([10, 20], pa.int64()), + "__note": pa.array(["a", "b"], pa.large_string()), + } + ) + stream = ArrowTableStream(table, tag_columns=["k"]) + out = Filter(col("v") > 10)(stream) + assert "__note" not in out.as_table(all_info=True).column_names + assert "__note" not in out.output_schema(all_info=True)[1] + + +class TestZeroRows: + def test_no_matching_row(self): + source = _units() + stream = source.filter(session="none") + table = stream.as_table(all_info=True) + assert table.num_rows == 0 + assert table.schema == source.as_table(all_info=True).schema + + def test_zero_row_input(self): + empty = _units().filter(session="none") + stream = empty.filter(col("t") >= 1.0) + assert stream.as_table().num_rows == 0 + assert stream.as_table().schema == empty.as_table().schema + + +class TestRefusals: + def test_missing_column_at_build(self): + with pytest.raises(InputValidationError, match="nope"): + _units().filter(nope=1) + + def test_value_of_another_kind_at_build(self): + with pytest.raises(InputValidationError): + _units().filter(t=1) # an int for a float column + with pytest.raises(InputValidationError): + _units().filter(unit=True) + + def test_out_of_range_when_applied(self): + table = pa.table( + {"k": pa.array([1], pa.int8()), "v": pa.array([1], pa.int64())} + ) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="narrow" + ) + stream = source.filter(k=300) # an int: the Python check passes + with pytest.raises(InputValidationError): + stream.as_table() + + @pytest.mark.parametrize("mask", [[True, False], True, (True,)]) + def test_a_mask_by_position_is_refused(self, mask: object): + with pytest.raises(TypeError): + _units().filter(mask) # pyright: ignore[reportArgumentType] + + +class TestIdentity: + def test_keyword_order(self): + a = Filter(Condition.of(session="s1", probe="imec0")) + b = Filter(Condition.of(probe="imec0", session="s1")) + assert a.content_hash() == b.content_hash() + source = _units() + assert a(source).pipeline_hash() == b(source).pipeline_hash() + + def test_argument_and_operand_order(self): + terms = [col("t") >= 1.0, col("unit").is_in([7, 3]), col("rate").is_null()] + hashes = { + _units().filter(*order).content_hash().to_string() + for order in itertools.permutations(terms) + } + hashes.add( + _units() + .filter(col("unit").is_in([3, 7]), *terms[::2]) + .content_hash() + .to_string() + ) + assert len(hashes) == 1 + + def test_values_of_different_types_differ(self): + one = Filter(col("x") == 1).content_hash() + assert one != Filter(col("x") == 1.0).content_hash() + assert one != Filter(col("x") == True).content_hash() # noqa: E712 # a condition, not a comparison + + def test_signed_zero_agrees(self): + assert ( + Filter(col("x") == 0.0).content_hash() + == Filter(col("x") == -0.0).content_hash() + ) + + def test_a_condition_changes_every_hash_downstream(self): + source = _units() + a = source.filter(session="s1").drop_nulls("rate") + b = source.filter(session="s2").drop_nulls("rate") + assert a.content_hash() != b.content_hash() + assert a.pipeline_hash() != b.pipeline_hash() + + def test_identity_structure(self): + condition = col("t") >= 1.0 + assert Filter(condition).identity_structure() == ( + "Filter", + condition.canonical_form(), + ) + + +class TestConfig: + @pytest.mark.parametrize( + "condition", + [ + Condition.of(session="s1", probe="imec0"), + Condition.of(col("t") >= 1.0, col("unit").is_in([3, 7]), session="s1"), + Condition.of(col("rate").is_null()), + ], + ids=["equalities", "terms", "null_test"], + ) + def test_round_trip(self, condition: Condition): + op = Filter(condition) + config = op.to_config() + assert config["class_name"] == "Filter" + rebuilt = _build_operator_registry()["Filter"].from_config(config) + assert rebuilt.condition == condition + assert rebuilt.content_hash() == op.content_hash() + assert _kept(rebuilt(_units())) == _kept(op(_units())) + + +class TestProvisional: + def test_listed_and_marked(self): + assert "Filter" in PROVISIONAL_OPERATORS + assert Filter.PROVISIONAL + + def test_building_one_warns_once(self): + reset_provisional_operator_warnings() + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + Filter(Condition.of(session="s1")) + Filter(Condition.of(session="s2")) + provisional = [ + w for w in caught if issubclass(w.category, ProvisionalHashWarning) + ] + assert len(provisional) == 1 + assert "Filter" in str(provisional[0].message) + finally: + reset_provisional_operator_warnings() + + +class TestAsync: + @pytest.mark.parametrize( + "condition", + [ + Condition.of(session="s1"), + Condition.of(col("t") >= 1.0, col("unit").is_in([3, 7])), + Condition.of(col("rate").is_null(), session="s3"), + ], + ids=["equality", "terms", "null_test"], + ) + def test_async_rows_equal_sync_rows(self, condition: Condition): + for options in ({}, {"tag_only_columns": ["session"]}): + source = _units(**options) + sync = rows_fingerprint(list(Filter(condition)(source).iter_data())) + assert rows_fingerprint(async_rows(Filter(condition), source)) == sync + + def test_async_refuses_what_sync_refuses(self): + table = pa.table( + {"k": pa.array([1], pa.int8()), "v": pa.array([1], pa.int64())} + ) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="narrow" + ) + with pytest.raises(InputValidationError): + async_rows(Filter(Condition.of(k=300)), source) + + +class TestInAJob: + @pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] + ) + def test_a_value_its_column_cannot_hold_raises_with_no_rows(self, orchestrator): + """The job path refuses what the sync path refuses, also with no rows to read a + type from (review of PR 497, finding 5): the node checks the input's Arrow schema.""" + table = pa.table( + {"k": pa.array([1], pa.int8()), "v": pa.array([1], pa.int64())} + ) + job = PipelineJob(name="narrow", database=InMemoryArrowDatabase()) + with job: + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="narrow" + ) + empty = source.filter(v=999, label="none") + Filter(Condition.of(k=300))(empty, label="kept") + with pytest.raises(InputValidationError, match="int8"): + job.run(orchestrator=orchestrator()) + + def test_a_job_node_reads_not_computed_before_its_first_run(self): + """A job node shows its current run (ITL-1095): before the first run its head + reads not computed, although the same filter outside a job shows its input's + matching rows (decision 13 is for the plain stream; review finding 6).""" + job = PipelineJob(name="head", database=InMemoryArrowDatabase()) + with job: + stream = _units().filter(session="s1", label="kept") + assert stream.head().status.value == "rows" + assert job.nodes["kept"].head().status.value == "not_computed" + job.run() + assert _kept(job.nodes["kept"].head()) == S1 + + @pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] + ) + def test_same_rows_inside_and_outside_a_job(self, orchestrator): + outside = _kept(_units().filter(col("t") >= 1.0, session="s1")) + database = InMemoryArrowDatabase() + job = PipelineJob(name="filter", database=database) + with job: + _units().filter(col("t") >= 1.0, session="s1", label="kept") + job.nodes["kept"].attach_databases( + pipeline_database=database.at("filter"), cache_mode=CacheMode.LOG + ) + job.run(orchestrator=orchestrator()) + assert _kept(job.nodes["kept"]) == outside + + def test_drop_nulls_after_filter_narrows(self): + stream = _units().filter(col("rate").is_not_null()).drop_nulls("rate") + assert stream.output_schema()[1]["rate"] is float + + +class TestHead: + """Decision 13 of ITL-1374: a Filter's head evaluates its condition over the rows its + input's head shows; it never computes, and the header says which rows it looked at.""" + + def test_over_a_source_shows_the_matching_rows(self): + stream = _units().filter(col("t") >= 1.0) + view = stream.head() + assert view.status.value == "rows" + assert _kept(view) == [("s1", 7), ("s1", 9), ("s2", 7), ("s3", 3)] + assert "all 4 matching rows of its input's 6" in view.header() + + def test_matches_among_a_shorter_head_say_so(self): + view = _units().filter(col("t") >= 1.0).head(3) + assert _kept(view) == [("s1", 7), ("s1", 9)] + assert "2 matching rows among the 3 its input's head shows" in view.header() + assert "not computed" in view.header() + + def test_no_match_shows_typed_columns(self): + source = _units() + view = source.filter(session="none").head() + assert view.table.num_rows == 0 + assert view.table.schema == source.head().table.schema + + def test_equals_the_computed_rows_with_every_column_group(self): + stream = _units().filter(col("unit").is_in([7, 9])) + for columns in ( + None, + {"system_tags": True, "source": True}, + {"sort_by_tags": True}, + ): + head = stream.head(columns=columns).table + # A fresh stream, so the computed head is not the one above. + computed = _units().filter(col("unit").is_in([7, 9])) + computed.run() + expected = computed.head(columns=columns).table + # ``t`` holds a NaN, which ``equals`` never matches: compared as text. + assert head.schema == expected.schema + assert repr(head.to_pylist()) == repr(expected.to_pylist()) + + def test_does_not_compute_the_stream(self): + stream = _units().filter(session="s1") + _ = stream.head() + assert ( + stream.head().header().endswith("not computed; run() computes every row)") + is False + ) + assert stream._cached_stream is None # pyright: ignore[reportAttributeAccessIssue,reportPrivateUsage] # nothing was computed + + def test_over_a_function_pod_reads_not_computed(self): + from orcapod import function_pod + + calls: list[int] = [] + + @function_pod(output_keys="doubled") + def double(t: float | None) -> float: + calls.append(1) + return 2 * (t or 0.0) + + stream = Filter(col("doubled") > 1.0)( + double.pod(_units().select_data_columns(["t"])) + ) + view = stream.head() + assert view.status.value == "not_computed" + assert view.table.num_rows == 0 + assert calls == [] + + def test_an_ill_typed_condition_shows_nothing_and_raises_at_the_run(self): + table = pa.table( + {"k": pa.array([1], pa.int8()), "v": pa.array([1], pa.int64())} + ) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="narrow" + ) + stream = source.filter(k=300) + assert stream.head().status.value == "not_computed" + with pytest.raises(InputValidationError): + stream.run() diff --git a/tests/test_core/operators/test_filter_mask.py b/tests/test_core/operators/test_filter_mask.py new file mode 100644 index 000000000..d928cfe87 --- /dev/null +++ b/tests/test_core/operators/test_filter_mask.py @@ -0,0 +1,515 @@ +"""The mask kernel of ``Filter`` (ITL-1378): every term kind on Arrow tables. + +Conditions are built with ``col`` and checked with ``check_filter_condition`` (the one +rule, ``check_condition``) before the kernel evaluates them. +""" + +from __future__ import annotations + +import operator +from collections.abc import Callable +import struct +from datetime import date, datetime, timedelta, timezone +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod.core.operators.filter_mask import ( + check_filter_condition, + condition_mask, + filter_table, +) +from orcapod.errors import InputValidationError +from orcapod.types import Condition, col +from orcapod.types.condition import ColumnRef + +NAN = float("nan") + +_OPERATORS: dict[str, Callable[[Any, Any], Any]] = { + "==": operator.eq, + "!=": operator.ne, + "<": operator.lt, + "<=": operator.le, + ">": operator.gt, + ">=": operator.ge, +} + + +def c(name: str, *fields: str) -> ColumnRef: + """``col(name)``, then ``.field(f)`` for each field.""" + ref = col(name) + for field in fields: + ref = ref.field(field) + return ref + + +def term(ref: ColumnRef, op: str, value: object = None) -> Condition: + """The condition ``ref value``, spelled as a user writes it.""" + if op == "is_in": + assert isinstance(value, tuple) + return ref.is_in(list(value)) + if op == "is_null": + return ref.is_null() + if op == "is_not_null": + return ref.is_not_null() + return _OPERATORS[op](ref, value) + + +def all_of(*conditions: Condition) -> Condition: + result = conditions[0] + for condition in conditions[1:]: + result = result & condition + return result + + +def any_of(*conditions: Condition) -> Condition: + result = conditions[0] + for condition in conditions[1:]: + result = result | condition + return result + + +def checked(table: pa.Table, condition: Condition) -> Condition: + check_filter_condition(condition, table.schema) + return condition + + +def _filtered(table: pa.Table, condition: Condition) -> pa.Table: + return filter_table(table, checked(table, condition)) + + +def mask(table: pa.Table, condition: Condition) -> list[bool | None]: + return condition_mask(table, checked(table, condition)).to_pylist() + + +@pytest.fixture +def units() -> pa.Table: + return pa.table( + { + "session": pa.array( + ["s1", "s1", "s1", "s2", "s2", "s3"], pa.large_string() + ), + "unit": pa.array([3, 7, 9, 3, 7, 3], pa.int64()), + "t": pa.array([0.5, 1.2, 2.0, 0.7, NAN, 3.1], pa.float64()), + "rate": pa.array([4.0, None, 2.5, 6.1, 0.0, None], pa.float64()), + "probe": pa.array( + ["imec0", "imec1", "imec0", "imec1", "imec0", "imec1"], + pa.large_string(), + ), + } + ) + + +def kept(table: pa.Table, condition: Condition) -> list[tuple[Any, Any]]: + out = filter_table(table, checked(table, condition)) + return list(zip(out.column("session").to_pylist(), out.column("unit").to_pylist())) + + +class TestSpecExamples: + """The table of section 1 of the design.""" + + def test_equality(self, units): + assert kept(units, term(c("session"), "==", "s1")) == [ + ("s1", 3), + ("s1", 7), + ("s1", 9), + ] + + def test_several_equalities(self, units): + node = all_of(term(c("session"), "==", "s1"), term(c("probe"), "==", "imec0")) + assert kept(units, node) == [("s1", 3), ("s1", 9)] + + def test_is_in(self, units): + assert kept(units, term(c("unit"), "is_in", (3, 7))) == [ + ("s1", 3), + ("s1", 7), + ("s2", 3), + ("s2", 7), + ("s3", 3), + ] + + def test_comparison_keeps_nan(self, units): + assert kept(units, term(c("t"), ">=", 1.0)) == [ + ("s1", 7), + ("s1", 9), + ("s2", 7), + ("s3", 3), + ] + + def test_between(self, units): + node = all_of(term(c("t"), ">=", 0.5), term(c("t"), "<=", 2.0)) + assert kept(units, node) == [("s1", 3), ("s1", 7), ("s1", 9), ("s2", 3)] + + def test_null_tests(self, units): + assert kept(units, term(c("rate"), "is_null")) == [("s1", 7), ("s3", 3)] + assert len(kept(units, term(c("rate"), "is_not_null"))) == 4 + + def test_negation(self, units): + assert kept(units, ~(term(c("unit"), "is_in", (3, 7)))) == [("s1", 9)] + + def test_or(self, units): + node = any_of(term(c("session"), "==", "s3"), term(c("t"), "<", 0.6)) + assert kept(units, node) == [("s1", 3), ("s3", 3)] + + def test_mixed(self, units): + node = all_of(term(c("t"), ">=", 1.0), term(c("session"), "==", "s1")) + assert kept(units, node) == [("s1", 7), ("s1", 9)] + + +class TestKleene: + @pytest.fixture + def t(self) -> pa.Table: + return pa.table({"x": pa.array([1, None, 3], pa.int64())}) + + def test_comparison_with_null_is_unknown(self, t): + assert mask(t, term(c("x"), "==", 1)) == [True, None, False] + assert mask(t, term(c("x"), "!=", 1)) == [False, None, True] + assert mask(t, term(c("x"), "is_in", (1,))) == [True, None, False] + + def test_not_of_unknown_is_unknown(self, t): + assert mask(t, ~(term(c("x"), ">", 1))) == [True, None, False] + + def test_and_or(self, t): + unknown_or_false = term(c("x"), "==", 1) + false_everywhere = term(c("x"), ">", 5) + true_where_valid = term(c("x"), ">=", 0) + assert mask(t, all_of(unknown_or_false, false_everywhere)) == [ + False, + None, + False, + ] + assert mask(t, all_of(unknown_or_false, term(c("x"), "is_null"))) == [ + False, + None, + False, + ] + assert mask(t, all_of(term(c("x"), "is_not_null"), unknown_or_false)) == [ + True, + False, + False, + ] + assert mask(t, any_of(unknown_or_false, true_where_valid)) == [ + True, + None, + True, + ] + assert mask(t, any_of(term(c("x"), "is_null"), true_where_valid)) == [ + True, + True, + True, + ] + + def test_null_dropped_and_kept_by_saying_so(self): + t = pa.table({"rate": pa.array([4.0, None, 0.5])}) + assert _filtered(t, term(c("rate"), "!=", 4.0)).column(0).to_pylist() == [0.5] + node = any_of(term(c("rate"), "<=", 1.0), term(c("rate"), "is_null")) + assert _filtered(t, node).column(0).to_pylist() == [None, 0.5] + + +class TestFloatRule: + @pytest.fixture + def t(self) -> pa.Table: + return pa.table( + {"x": pa.array([1.0, NAN, -0.0, 0.0, float("inf"), None], pa.float64())} + ) + + def test_equality(self, t): + assert mask(t, term(c("x"), "==", NAN)) == [ + False, + True, + False, + False, + False, + None, + ] + assert mask(t, term(c("x"), "==", 0.0)) == [ + False, + False, + True, + True, + False, + None, + ] + assert mask(t, term(c("x"), "==", -0.0)) == mask(t, term(c("x"), "==", 0.0)) + assert mask(t, term(c("x"), "!=", NAN)) == [ + True, + False, + True, + True, + True, + None, + ] + + def test_is_in(self, t): + assert mask(t, term(c("x"), "is_in", (NAN, -0.0))) == [ + False, + True, + True, + True, + False, + None, + ] + + @pytest.mark.parametrize( + "op,value,expected", + [ + (">=", 1.0, [True, True, False, False, True, None]), + (">", 1.0, [False, True, False, False, True, None]), + ("<", 1.0, [False, False, True, True, False, None]), + ("<=", 1.0, [True, False, True, True, False, None]), + ("<", NAN, [True, False, True, True, True, None]), + ("<=", NAN, [True, True, True, True, True, None]), + (">", NAN, [False, False, False, False, False, None]), + (">=", NAN, [False, True, False, False, False, None]), + (">", float("inf"), [False, True, False, False, False, None]), + ("<", 0.0, [False, False, False, False, False, None]), + ], + ) + def test_order_nan_greatest(self, t, op, value, expected): + assert mask(t, term(c("x"), op, value)) == expected + + def test_float32_rounds_literal(self): + stored = struct.unpack("f", struct.pack("f", 0.1))[0] + t = pa.table({"x": pa.array([stored, 0.2], pa.float32())}) + assert mask(t, term(c("x"), "<=", 0.1)) == [True, False] + assert mask(t, term(c("x"), "==", 0.1)) == [True, False] + + def test_float32_out_of_range_refused(self): + t = pa.table({"x": pa.array([1.0], pa.float32())}) + with pytest.raises(InputValidationError, match="range does not reach"): + mask(t, term(c("x"), "<", 1e300)) + assert mask(t, term(c("x"), "<", float("inf"))) == [True] + + def test_float16(self): + t = pa.table({"x": pa.array([1.5, 2.0], pa.float32()).cast(pa.float16())}) + assert mask(t, term(c("x"), ">", 1.6)) == [False, True] + with pytest.raises(InputValidationError, match="range does not reach"): + mask(t, term(c("x"), "<", 1e6)) + + +class TestLiterals: + @pytest.mark.parametrize("arrow_type", [pa.uint8(), pa.uint32(), pa.int64()]) + def test_int_on_every_width(self, arrow_type): + t = pa.table({"x": pa.array([7, 8], arrow_type)}) + assert mask(t, term(c("x"), "==", 7)) == [True, False] + assert mask(t, term(c("x"), "is_in", (7, 9))) == [True, False] + + def test_out_of_range_refused(self): + with pytest.raises(InputValidationError, match="cannot hold"): + mask(pa.table({"x": pa.array([1], pa.uint32())}), term(c("x"), "==", -1)) + with pytest.raises(InputValidationError, match="cannot hold"): + mask(pa.table({"x": pa.array([1], pa.int8())}), term(c("x"), "==", 300)) + with pytest.raises(InputValidationError, match="cannot hold"): + mask( + pa.table({"x": pa.array([1], pa.int8())}), + term(c("x"), "is_in", (1, 300)), + ) + + @pytest.mark.parametrize( + "arrow_type,value", + [ + (pa.float64(), 7), + (pa.int64(), True), + (pa.int64(), "7"), + (pa.int64(), 7.0), + (pa.date32(), "2026-01-01"), + (pa.date32(), datetime(2026, 1, 1)), + (pa.bool_(), 1), + ], + ) + def test_kind_mismatch_refused(self, arrow_type, value): + t = pa.table({"x": pa.array([], arrow_type)}) + with pytest.raises(InputValidationError, match="converts no value"): + mask(t, term(c("x"), "==", value)) + + def test_strings_and_bytes_order(self): + t = pa.table( + { + "s": pa.array(["a", "B", "b"], pa.string()), + "b": pa.array([b"\x00", b"\xff", b"a"], pa.binary()), + } + ) + assert mask(t, term(c("s"), "<", "a")) == [False, True, False] + assert mask(t, term(c("b"), ">", b"a")) == [False, True, False] + assert mask(t, term(c("s"), "is_in", ("b", "a"))) == [True, False, True] + + def test_dates(self): + t = pa.table({"d": pa.array([date(2026, 1, 1), date(2026, 2, 1)], pa.date32())}) + assert mask(t, term(c("d"), ">=", date(2026, 1, 15))) == [False, True] + t64 = t.cast(pa.schema([("d", pa.date64())])) + assert mask(t64, term(c("d"), "==", date(2026, 2, 1))) == [False, True] + + def test_aware_timestamps_compare_instants(self): + utc = datetime(2026, 1, 1, 12, tzinfo=timezone.utc) + t = pa.table( + {"ts": pa.array([utc, utc + timedelta(hours=1)], pa.timestamp("us", "UTC"))} + ) + plus_two = timezone(timedelta(hours=2)) + assert mask( + t, term(c("ts"), "==", datetime(2026, 1, 1, 14, tzinfo=plus_two)) + ) == [ + True, + False, + ] + with pytest.raises(InputValidationError, match="must be an aware datetime"): + mask(t, term(c("ts"), "==", datetime(2026, 1, 1, 12))) + + def test_naive_timestamps(self): + t = pa.table({"ts": pa.array([datetime(2026, 1, 1, 12)], pa.timestamp("ns"))}) + assert mask(t, term(c("ts"), "==", datetime(2026, 1, 1, 12))) == [True] + with pytest.raises(InputValidationError, match="must be a naive datetime"): + mask(t, term(c("ts"), "==", datetime(2026, 1, 1, 12, tzinfo=timezone.utc))) + + def test_sub_unit_literal_refused(self): + t = pa.table({"ts": pa.array([datetime(2026, 1, 1)], pa.timestamp("s"))}) + assert mask(t, term(c("ts"), "==", datetime(2026, 1, 1))) == [True] + with pytest.raises(InputValidationError, match="cannot hold .* exactly"): + mask(t, term(c("ts"), "<", datetime(2026, 1, 1, 0, 0, 0, 1))) + + def test_bool_equality_but_no_order(self): + t = pa.table({"b": pa.array([True, False, None])}) + assert mask(t, term(c("b"), "==", True)) == [True, False, None] + with pytest.raises(InputValidationError, match="no order"): + mask(t, term(c("b"), "<", True)) + + def test_unsupported_types_take_null_tests_only(self): + t = pa.table( + { + "l": pa.array([[1], None], pa.large_list(pa.int64())), + "d": pa.array([1, 2], pa.decimal128(5, 0)), + } + ) + assert mask(t, term(c("l"), "is_null")) == [False, True] + for name in ("l", "d"): + with pytest.raises(InputValidationError, match="only a null test"): + mask(t, term(c(name), "==", 1)) + + def test_missing_column(self): + with pytest.raises(InputValidationError, match="no column 'y'"): + mask(pa.table({"x": [1]}), term(c("y"), "==", 1)) + + +class TestStructFields: + @pytest.fixture + def t(self) -> pa.Table: + info = pa.struct( + [ + ("kind", pa.large_string()), + ("depth", pa.struct([("um", pa.float64())])), + ] + ) + return pa.table( + { + "info": pa.array( + [ + {"kind": "good", "depth": {"um": 10.0}}, + {"kind": "noise", "depth": {"um": 20.0}}, + None, + {"kind": None, "depth": None}, + ], + info, + ) + } + ) + + def test_field(self, t): + kind = c("info", "kind") + assert mask(t, term(kind, "!=", "noise")) == [True, False, None, None] + assert mask(t, term(kind, "is_null")) == [False, False, True, True] + + def test_field_of_field(self, t): + um = c("info", "depth", "um") + assert mask(t, term(um, ">", 15.0)) == [False, True, None, None] + + def test_missing_field_lists_fields(self, t): + with pytest.raises(InputValidationError, match="kind: large_string"): + mask(t, term(c("info", "kinds"), "==", "x")) + + def test_field_of_non_struct(self): + with pytest.raises(InputValidationError, match="which is not a struct"): + mask(pa.table({"x": [1]}), term(c("x", "f"), "==", 1)) + + +class TestColumnAgainstColumn: + def test_same_type(self): + t = pa.table( + { + "a": pa.array([1.0, NAN, 2.0, None, NAN, -0.0]), + "b": pa.array([2.0, 1.0, 2.0, 1.0, NAN, 0.0]), + } + ) + assert mask(t, term(c("a"), "<", col("b"))) == [ + True, + False, + False, + None, + False, + False, + ] + assert mask(t, term(c("a"), "<=", col("b"))) == [ + True, + False, + True, + None, + True, + True, + ] + assert mask(t, term(c("a"), "==", col("b"))) == [ + False, + False, + True, + None, + True, + True, + ] + assert mask(t, term(c("b"), ">", col("a"))) == mask( + t, term(c("a"), "<", col("b")) + ) + + def test_null_never_greater_than_nan(self): + t = pa.table({"a": pa.array([None], pa.float64()), "b": pa.array([NAN])}) + assert mask(t, term(c("a"), "<=", col("b"))) == [None] + + def test_layouts_of_one_type(self): + t = pa.table( + { + "a": pa.array(["x", "y"], pa.string()), + "b": pa.array(["x", "z"], pa.large_string()), + } + ) + assert mask(t, term(c("a"), "==", col("b"))) == [True, False] + + def test_different_types_refused(self): + t = pa.table({"a": pa.array([1], pa.int32()), "b": pa.array([1], pa.int64())}) + with pytest.raises(InputValidationError, match="have different types"): + mask(t, term(c("a"), "==", col("b"))) + + +def test_a_condition_is_checked_against_the_schema_alone(): + schema = pa.schema([("x", pa.int8())]) + check_filter_condition(term(c("x"), "==", 3), schema) + with pytest.raises(InputValidationError): + check_filter_condition(term(c("x"), "==", 300), schema) + + +def test_values_pass_through_bit_for_bit(): + # A float32 signalling NaN, built from its bits (a Python float would quiet it). + values = pa.Array.from_buffers( + pa.float32(), + 2, + [None, pa.py_buffer(bytes.fromhex("0100807f") + struct.pack(" ArrowTableStream: + """A stream with a zoned timestamp column at ``unit``: the epoch and one second on.""" + values = pa.array([0, 1], pa.int64()).cast(pa.timestamp("s", "UTC")) + return ArrowTableStream( + pa.table({"id": [1, 2], "x": values.cast(pa.timestamp(unit, "UTC"))}), + tag_columns=["id"], + ) + + +def _ids(stream) -> list[int]: + return stream.as_table()["id"].to_pylist() + + +class TestFinding1ContextPassesThrough: + """Sync filtering replaced each kept row's data context with the default.""" + + @pytest.mark.parametrize( + ("condition", "kept"), + [ + (col("k") >= 2, ["held-b", "held-c"]), + (col("k") == 1, ["held-a"]), + (col("k").is_in([1, 3]), ["held-a", "held-c"]), + (col("k") > 9, []), + ], + ids=["tail", "head", "gaps", "none"], + ) + def test_each_kept_rows_context_is_its_own(self, condition, kept): + table = pa.table( + { + "k": pa.array([1, 2, 3], pa.int64()), + "v": pa.array([10, 20, 30], pa.int64()), + "_context_key": pa.array( + ["held-a", "held-b", "held-c"], pa.large_string() + ), + } + ) + stream = ArrowTableStream(table, tag_columns=["k"]) + out = Filter(condition)(stream).as_table(columns={"context": True}) + assert out["_context_key"].to_pylist() == kept + # As every operator that passes rows through keeps it. + selected = SelectDataColumns(["v"])(stream).as_table(columns={"context": True}) + assert selected["_context_key"].to_pylist() == ["held-a", "held-b", "held-c"] + + +class _CountingZone(dt.tzinfo): + """A mutable zone that counts the times its offset is read.""" + + def __init__(self) -> None: + self.hours = 0 + self.calls = 0 + + def utcoffset(self, value: dt.datetime | None) -> dt.timedelta: + self.calls += 1 + return dt.timedelta(hours=self.hours) + + def dst(self, value: dt.datetime | None) -> dt.timedelta: + return dt.timedelta(0) + + def tzname(self, value: dt.datetime | None) -> str: + return "counting" + + +class TestFinding2DatetimesAreFrozenWhenBuilt: + """A datetime with a mutable tzinfo stayed live: its callback ran in head() and + a changed offset chose other rows under the same hash.""" + + @pytest.mark.parametrize("unit", UNITS) + @pytest.mark.parametrize( + "build", + [ + lambda v: col("x") == v, + lambda v: col("x") >= v, + lambda v: col("x").is_in([v]), + lambda v: col("x").between(v, v), + ], + ids=["equal", "order", "is_in", "between"], + ) + def test_no_callback_after_build_and_the_same_rows(self, unit, build): + zone = _CountingZone() + stream = Filter(build(dt.datetime(1970, 1, 1, tzinfo=zone)))(_instants(unit)) + before = stream.pipeline_hash() + calls = zone.calls + head = _ids(stream.head()) + zone.hours = 1 # would move the instant by an hour if still read + assert _ids(stream) == head + assert zone.calls == calls + assert stream.pipeline_hash() == before + + +class TestFinding3OneInstantOneIdentity: + """One instant spelled with a sub-second offset was refused, and its saved form + changed its identity.""" + + @pytest.mark.parametrize("unit", ("us", "ns")) + @pytest.mark.parametrize( + "spelling", + [ + EPOCH + dt.timedelta(seconds=1), + dt.datetime(1970, 1, 1, tzinfo=dt.timezone(-dt.timedelta(seconds=1))), + dt.datetime( + 1970, + 1, + 1, + 5, + 30, + 1, + tzinfo=dt.timezone(dt.timedelta(hours=5, minutes=30)), + ), + dt.datetime( + 1970, + 1, + 1, + 0, + 0, + 0, + 999_999, + tzinfo=dt.timezone(-dt.timedelta(microseconds=1)), + ), + ], + ids=["utc", "whole_second_offset", "half_hour_offset", "microsecond_offset"], + ) + def test_every_spelling_selects_the_row_and_keeps_its_identity( + self, unit, spelling + ): + condition = col("x") == spelling + reference = col("x") == EPOCH + dt.timedelta(seconds=1) + assert condition.canonical_form() == reference.canonical_form() + assert _ids(Filter(condition)(_instants(unit))) == [2] + saved = json.loads(json.dumps(Filter(condition).to_config())) + rebuilt = Filter.from_config(saved) + assert rebuilt.condition.canonical_form() == reference.canonical_form() + + +class TestFinding4BetweenComparesInstants: + """``between`` compared wall times, so a range across a daylight-saving overlap that + ends before it starts was accepted.""" + + def test_a_reversed_range_across_the_overlap_is_refused(self): + zone = pytest.importorskip("zoneinfo").ZoneInfo("America/New_York") + start = dt.datetime(2025, 11, 2, 1, 0, tzinfo=zone, fold=1) + end = dt.datetime(2025, 11, 2, 1, 30, tzinfo=zone, fold=0) + assert start.timestamp() > end.timestamp() + with pytest.raises(ValueError, match="low end above its high end"): + _instants("us").filter(col("x").between(start, end)) + + +class TestFinding5DirectChannelLimits: + """The direct async channel cannot check what it does not receive. Documented in + ``Filter.async_execute``; pinned here, beside the job path, which refuses.""" + + @staticmethod + def _narrow() -> ArrowTableSource: + table = pa.table( + {"k": pa.array([1], pa.int8()), "v": pa.array([1], pa.int64())} + ) + return ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="narrow" + ) + + def test_no_rows_on_the_channel_are_not_checked(self): + empty = self._narrow().filter(v=999) + with pytest.raises(InputValidationError): + Filter(Condition.of(k=300))(empty).as_table() # sync refuses + assert async_rows(Filter(Condition.of(k=300)), empty) == [] # the limit + + def test_a_raw_null_column_arrives_typed_as_text(self): + raw = ArrowTableStream( + pa.table({"k": [1, 2], "v": pa.nulls(2)}), tag_columns=["k"] + ) + with pytest.raises(InputValidationError, match="null"): + Filter(Condition.of(v="x"))(raw).as_table() # sync refuses + assert async_rows(Filter(Condition.of(v="x")), raw) == [] # the limit + + @pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] + ) + def test_a_job_refuses_with_no_rows(self, orchestrator): + job = PipelineJob(name="narrow", database=InMemoryArrowDatabase()) + with job: + empty = self._narrow().filter(v=999, label="none") + Filter(Condition.of(k=300))(empty, label="kept") + with pytest.raises(InputValidationError, match="int8"): + job.run(orchestrator=orchestrator()) + + +class TestFinding7SavedTreesLoadAsBuilt: + """A saved tree with two equalities on one column loaded and changed meaning when + saved again. Contradictions are now kept as written (developer, 2026-11-22): the + saved tree loads as built, selects no row, and saves to the same form.""" + + @pytest.mark.parametrize("values", [(1, 2), (2, 1), (1, 2, 3)]) + def test_a_contradiction_round_trips_with_no_row(self, values): + source = ArrowTableSource( + pa.table({"k": pa.array([1, 2, 3], pa.int64()), "v": [4, 5, 6]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="keys", + ) + condition = col("k") == values[0] + for value in values[1:]: + condition = condition & (col("k") == value) + op = Filter(condition) + saved = json.loads(json.dumps(op.to_config())) + rebuilt = Filter.from_config(saved) + assert rebuilt.condition == condition + assert rebuilt.to_config() == saved + assert rebuilt(source).as_table().num_rows == 0 + assert rebuilt.content_hash() == op.content_hash() + + +class TestChangelogClaimOfPr497: + """CodeRabbit (PR 497 review body): a row is dropped when its WHOLE condition is + false or unknown, so ``is_null() | ...`` keeps the null rows the changelog names.""" + + @pytest.mark.parametrize( + ("condition", "kept"), + [ + (col("rate").is_null() | (col("rate") > 1.0), [1, 2, 3]), + (col("rate") > 1.0, [1, 3]), + (~(col("rate") > 1.0), [4]), + ((col("rate") > 1.0) | (col("k") == 2), [1, 2, 3]), + ], + ids=["null_or_value", "value_alone", "not_value", "value_or_other_column"], + ) + def test_a_row_is_kept_when_its_whole_condition_holds(self, condition, kept): + stream = ArrowTableStream( + pa.table( + { + "k": [1, 2, 3, 4], + "rate": pa.array([4.0, None, 2.5, 0.5], pa.float64()), + } + ), + tag_columns=["k"], + ) + assert sorted(_ids_by(Filter(condition)(stream), "k")) == kept + + +def _ids_by(stream, name: str) -> list[int]: + return stream.as_table()[name].to_pylist() diff --git a/tests/test_core/operators/test_provisional_operators.py b/tests/test_core/operators/test_provisional_operators.py index 13b39d420..bdb62c23e 100644 --- a/tests/test_core/operators/test_provisional_operators.py +++ b/tests/test_core/operators/test_provisional_operators.py @@ -125,6 +125,8 @@ def test_the_list_and_the_markers_agree() -> None: "AddTags": "ITL-1290", # Developer, November 21, 2026 (ITL-1336). "Rejoin": "ITL-1336", + # Developer, November 22, 2026 (ITL-1374): provisional for the workshop. + "Filter": "ITL-1374", } # The operators frozen with data context v1 (ITL-1279). FROZEN = { @@ -374,6 +376,7 @@ def _other() -> ArrowTableSource: "Pick": lambda: _lists().pick("meta", "k"), "Index": lambda: _lists().index("values", 0), "MergeJoin": lambda: operators.MergeJoin()(_stream(), _other()), + "Filter": lambda: _stream().filter(subject="s1"), # Two branches of one source, put back together. "Rejoin": lambda: ( lambda branched: branched.select_data_columns(["age"]).rejoin( diff --git a/tests/test_core/operators/test_several_items.py b/tests/test_core/operators/test_several_items.py index 3c7443897..124e9f852 100644 --- a/tests/test_core/operators/test_several_items.py +++ b/tests/test_core/operators/test_several_items.py @@ -43,6 +43,7 @@ DropDataColumns, DropNulls, DropTagColumns, + Filter, Join, MapColumns, MapData, @@ -55,14 +56,14 @@ SemiJoin, TagBy, ) -from orcapod import PipelineJob +from orcapod import PipelineJob, col from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.sources import ArrowTableSource from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InputValidationError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator -from orcapod.types import CacheMode +from orcapod.types import CacheMode, Condition from orcapod.protocols.core_protocols import StreamProtocol from .several_items import ( @@ -134,6 +135,10 @@ class UnaryCase: "polars_filter_predicates", lambda: PolarsFilter(predicates=[pl.col("d1") > 10, pl.col("t3") == 1]), ), + UnaryCase( + "filter", + lambda: Filter(Condition.of(col("d1") > 10, col("t3").is_in([1, 2]), t1="a")), + ), UnaryCase("drop_nulls_named", lambda: DropNulls(["d2", "t2"])), UnaryCase("drop_nulls_all", DropNulls), UnaryCase("batch", lambda: Batch(batch_size=4)), @@ -310,6 +315,16 @@ class OrderCase: OrderCase("select_columns", ("t1", "d3", "t3", "d1"), SelectColumns), OrderCase("drop_columns", ("t1", "d3", "d1"), DropColumns), OrderCase("drop_nulls", ("d2", "t2", "d1"), DropNulls), + OrderCase( + "filter_keywords", + (("t1", "a"), ("t2", 1), ("t3", 2)), + lambda items: Filter(Condition.of(**items)), + ), + OrderCase( + "filter_conditions", + (col("t1") == "a", col("d1") > 10, col("d2").is_not_null()), + lambda items: Filter(Condition.of(*items)), + ), OrderCase("map_tags", (("t1", "u1"), ("t2", "u2"), ("t3", "u3")), MapTags), # A swap: each target is another entry's source. OrderCase("map_tags_swap", (("t1", "t3"), ("t3", "t1")), MapTags, roles=(PLAIN,)), @@ -496,6 +511,11 @@ class RoleCase: lambda: DropNulls(["t3", "t2", "d2"]), (("t1", "t2", "t3"), ("t1", "t3", "d1", "d2", "d3")), ), + RoleCase( + "filter", + lambda: Filter(Condition.of(col("t3") == 1, col("t2") >= 2, d3="w")), + (("t1", "t2", "t3"), ("t1", "t3", "d1", "d2", "d3")), + ), RoleCase( "polars_filter", lambda: PolarsFilter(constraints={"t3": 1, "t2": 2, "d3": "w"}), diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index bf14a167a..b6c8697d7 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -35,9 +35,11 @@ from __future__ import annotations import asyncio +import functools import inspect import itertools import json +import operator import re import sqlite3 from collections.abc import Callable, Sequence @@ -51,12 +53,13 @@ import pytest import orcapod -from orcapod import PipelineJob, function_pod, operators, sources, streams +from orcapod import PipelineJob, col, function_pod, operators, sources, streams from orcapod.channels import Channel from orcapod.core.nodes import SourceJobNode from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase +from orcapod.types import Condition from orcapod.operators import ( AddTags, Batch, @@ -64,6 +67,7 @@ DropDataColumns, DropNulls, DropTagColumns, + Filter, GroupBy, Index, Join, @@ -425,6 +429,32 @@ def apply(source: Any) -> Any: argument_issue="ITL-1247", ), ), + "Filter": ( + # Positional conditions on a tag, a data column and every role. + OperatorCase( + "filter_conditions", + lambda items: Filter(Condition.of(*items)), + (col("t1") == "a", col("d1") > 10, col("t3").is_in([1, 2])), + ), + # Keywords. + OperatorCase( + "filter_keywords", + lambda items: Filter(Condition.of(**dict(items))), + (("t1", "a"), ("t2", 1)), + ), + # The values of is_in. + OperatorCase( + "filter_is_in_values", + lambda items: Filter(col("d1").is_in(list(items))), + (20, 30, 50), + ), + # The operands of |. + OperatorCase( + "filter_or_operands", + lambda items: Filter(functools.reduce(operator.or_, items)), + (col("t2") == 2, col("d2").is_null(), col("d3") == "x"), + ), + ), "DropNulls": ( OperatorCase("drop_nulls_named", _names(DropNulls), ("d2", "t2", "d1")), OperatorCase("drop_nulls_all", _plain(DropNulls)), diff --git a/tests/test_types_condition_tree.py b/tests/test_types_condition_tree.py index 7766af85c..a0a45f5de 100644 --- a/tests/test_types_condition_tree.py +++ b/tests/test_types_condition_tree.py @@ -1160,3 +1160,114 @@ def test_a_saved_comparison_holds_one_operand(operator, value): } with pytest.raises(ValueError, match="one operand"): Condition.from_config(saved) + + +def _same_everywhere(a: Condition, b: Condition) -> None: + """Equal conditions agree in every form: equality, hash, canonical form and text, + the saved config (as JSON), and the condition the saved config loads as.""" + assert a == b + assert hash(a) == hash(b) + assert a.canonical_form() == b.canonical_form() + assert a.canonical_text() == b.canonical_text() + saved_a = json.dumps(a.to_config(), sort_keys=True) + assert saved_a == json.dumps(b.to_config(), sort_keys=True) + reloaded = Condition.from_config(json.loads(saved_a)) + assert reloaded == a + assert json.dumps(reloaded.to_config(), sort_keys=True) == saved_a + + +class TestCodeRabbitBodiesOfPr497: + """CodeRabbit's review bodies on PR 497 (a72f9187): items outside the diff.""" + + @pytest.mark.parametrize( + "build", + [ + lambda z: col("x") == z, + lambda z: col("x") >= z, + lambda z: col("x") < z, + lambda z: col("x") != z, + lambda z: col("x").is_in([z, 1.0]), + lambda z: (col("x") == z) & (col("y") > 1), + lambda z: ~(col("x") <= z), + lambda z: Condition.of(x=z), + ], + ids=["eq", "ge", "lt", "ne", "is_in", "tree_eq", "not", "mapping"], + ) + def test_signed_zero_is_saved_as_zero(self, build): + _same_everywhere(build(-0.0), build(0.0)) + + @pytest.mark.parametrize( + "build", + [ + lambda z: (col("x") >= z) & (col("x") >= -z), + lambda z: (col("x") == z) | (col("x") == -z), + ], + ids=["and", "or"], + ) + def test_signed_zero_in_either_operand_order(self, build): + _same_everywhere(build(-0.0), build(0.0)) + + @pytest.mark.parametrize( + ("first", "second"), + [ + ( + dt.datetime(1, 1, 1, 0, 0, tzinfo=dt.timezone(dt.timedelta(hours=1))), + dt.datetime(1, 1, 1, 1, 0, tzinfo=dt.timezone(dt.timedelta(hours=2))), + ), + ( + dt.datetime(1, 1, 1, 0, 30, tzinfo=dt.timezone(dt.timedelta(hours=5))), + dt.datetime( + 1, + 1, + 1, + 0, + 0, + 0, + 1, + tzinfo=dt.timezone( + dt.timedelta(hours=4, minutes=30, microseconds=1) + ), + ), + ), + ( + dt.datetime( + 9999, 12, 31, 23, 0, tzinfo=dt.timezone(-dt.timedelta(hours=1)) + ), + dt.datetime( + 9999, 12, 31, 22, 0, tzinfo=dt.timezone(-dt.timedelta(hours=2)) + ), + ), + ], + ids=["year_1_whole_hours", "year_1_fractional_offset", "year_9999"], + ) + @pytest.mark.parametrize( + "build", + [ + lambda a, b: (col("t") == a, col("t") == b), + lambda a, b: (col("t").is_in([a, b]), col("t").is_in([b, a])), + lambda a, b: (col("t") >= a, col("t") >= b), + ], + ids=["equal", "is_in_orders", "order"], + ) + def test_an_instant_outside_utc_range_has_one_representation( + self, first, second, build + ): + _same_everywhere(*build(first, second)) + + def test_combining_keeps_the_first_occurrence_and_contradictions(self): + wide = Condition.of({f"c{i}": i for i in range(2000)}) + again = wide & Condition.of({f"c{i}": i for i in range(1000)}) + assert again == wide + assert [t.path.column for t in again.terms()][:3] == ["c0", "c1", "c2"] + contradiction = (col("k") == 1) & (col("k") == 2) & (col("k") == 1) + assert sorted(repr(t.value) for t in contradiction.terms()) == ["1", "2"] + + def test_a_contradiction_is_not_read_as_equalities(self): + contradiction = (col("k") == 1) & (col("k") == 2) + assert not contradiction.only_equalities + assert "k" in json.dumps(contradiction.to_config()) + assert ":condition" in contradiction.to_config() + + def test_two_binary_layouts_compare_as_one_type(self): + schema = pa.schema([("a", pa.binary()), ("b", pa.large_binary())]) + check_condition(col("a") == col("b"), schema)