diff --git a/changelog.d/ITL-1777.md b/changelog.d/ITL-1777.md new file mode 100644 index 000000000..3de25bb25 --- /dev/null +++ b/changelog.d/ITL-1777.md @@ -0,0 +1,11 @@ +### Added + +- A boolean column is a condition on its own (ITL-1777): `stream.filter(col("flag"))` + keeps the rows where `flag` is true and `stream.filter(~col("flag"))` the rows where it + is false. They are the conditions `col("flag") == True` and `col("flag") == False`, with + the same identity, so no hash moves and the two spellings give one filter. A null is + neither true nor false, so a row with a null is kept by neither. A bare column combines + with other conditions through `&` and `|` (`col("flag") & (col("t") > 1.0)`) and is + accepted by `filter`, `Filter`, `Condition.of` and a SpiralDB source's `where`, which + sends it to SpiralDB as that equality. `col(c).is_true()` is the explicit form. A column + that is not boolean is refused when the condition meets the stream. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index ac4d034b1..2d41dc0ad 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -772,6 +772,7 @@ The conditions are: | comparison | `col(c) < v`, `<=`, `>`, `>=` | integers, floats, strings, binary, dates, timestamps | | range | `col(c).between(low, high)`, both ends included | the same | | null test | `col(c).is_null()`, `col(c).is_not_null()` | every type | +| boolean column | `col(c)` (true rows, `col(c) == True`), `~col(c)` (false rows, `col(c) == False`) | bool | | struct field | `col(c).field("f")`, then any condition above | a struct column | | two columns | `col(a) < col(b)` and the other comparisons | two columns of one Arrow type | | combined | several arguments and keywords (all hold), `a & b`, `a \| b`, `~a` | | @@ -806,6 +807,50 @@ assert (False or bounds) is bounds Use `col(c).is_in([...])` to test membership in a list. +A boolean column is a condition on its own: `col("c")` keeps the rows where it is true and +`~col("c")` the rows where it is false. They are the conditions `col("c") == True` and +`col("c") == False`, with the same identity. A null is neither true nor false, so a row +with a null is kept by neither. A column that is not boolean is refused when the filter +meets the stream: + +```python +from orcapod.errors import InputValidationError + +checked = ArrowTableSource( + pa.table( + { + "unit": [3, 7, 9, 11], + "noisy": [False, True, None, False], + "sorted": [True, True, False, None], + } + ), + tag_columns=["unit"], + tag_only_columns=True, + source_id="checked", +) + + +def units(stream): + return sorted(stream.as_table()["unit"].to_pylist()) + + +print(units(checked.filter(col("noisy")))) +# [7] +print(units(checked.filter(~col("noisy")))) +# [3, 11] +print(units(checked.filter(~col("noisy") & col("sorted")))) +# [3] +print(units(checked.filter(col("noisy") | ~col("sorted")))) +# [7, 9] +assert checked.filter(~col("noisy")).content_hash() == checked.filter(noisy=False).content_hash() + +try: + checked.filter(col("unit")) +except InputValidationError as error: + print(str(error).split(";")[0]) +# Filter: column 'unit' holds int, but the value True is a bool +``` + A condition that no row can satisfy is kept as written and keeps zero rows: Orcapod does not try to tell a contradiction (there is no general way). Naming one column twice in one call with two values is refused, as an argument error: diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index 17e97ee11..ebf849227 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -26,7 +26,7 @@ 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.types.condition import ColumnRef, Condition, check_condition_columns def _user_columns( @@ -67,7 +67,8 @@ class Filter(UnaryOperator): later release. Args: - condition: The condition, or a mapping of column equalities. + condition: The condition, a mapping of column equalities, or a bare + ``col(c)`` of a boolean column (``col(c) == True``). Raises: ValueError: If the condition names no column. @@ -87,7 +88,7 @@ class Filter(UnaryOperator): PROVISIONAL: ClassVar[bool] = True def __init__( - self, condition: Condition | Mapping[str, object], **kwargs: Any + self, condition: Condition | ColumnRef | Mapping[str, object], **kwargs: Any ) -> None: self._condition: Condition = Condition.of(condition) super().__init__(**kwargs) diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index eff376f2d..5e48b0870 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -83,7 +83,7 @@ require_same_process, ) from orcapod.errors import InputValidationError, RowIdentifierError, SourceTooLargeError -from orcapod.types import ColumnConfig, Condition +from orcapod.types import ColumnConfig, ColumnRef, Condition from orcapod.types.condition import check_float_equalities, check_restriction from orcapod.utils import arrow_utils from orcapod.utils.schema_utils import _normalize_column_list @@ -541,7 +541,7 @@ def table_id(self) -> str: def where( self, /, - *conditions: "Mapping[str, object] | Condition | None", + *conditions: "Mapping[str, object] | Condition | ColumnRef | None", **columns: object, ) -> "SpiralDBTableSource": """Return a new source on the same table that reads only the matching rows. @@ -559,7 +559,10 @@ def where( ``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 - value (a keyword, a mapping, ``col(c) == v``), and a range of an integer, + 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, 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 diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 916afcf81..24978dc78 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -57,7 +57,7 @@ ) from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, Condition, ContentHash, Schema +from orcapod.types import ColumnConfig, ColumnRef, Condition, ContentHash, Schema from orcapod.utils import arrow_utils if TYPE_CHECKING: @@ -1123,7 +1123,7 @@ def polars_filter( def filter( self, - *conditions: Condition | Mapping[str, object], + *conditions: Condition | ColumnRef | Mapping[str, object], label: str | None = None, **columns: object, ) -> StreamBase: @@ -1137,7 +1137,9 @@ def filter( ``orcapod.core.operators.Filter``. Args: - *conditions: Conditions (built with ``col`` or ``Condition.of``) and + *conditions: Conditions (built with ``col`` or ``Condition.of``; a bare + ``col(c)`` of a boolean column keeps its true rows, ``~col(c)`` its + false rows) 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``. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 8cd7a5312..bd681e63a 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -17,7 +17,7 @@ IdentityChainProtocol, PipelineElementProtocol, ) -from orcapod.types import ColumnConfig, Condition, Schema +from orcapod.types import ColumnConfig, ColumnRef, Condition, Schema if TYPE_CHECKING: from orcapod.types.explanation import Explanation @@ -496,7 +496,7 @@ def polars_filter( def filter( self, - *conditions: Condition | Mapping[str, object], + *conditions: Condition | ColumnRef | Mapping[str, object], label: str | None = None, **columns: object, ) -> "StreamProtocol": diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index b93607743..534ed7b0d 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -489,6 +489,7 @@ def check_value_for_column( f"to {expected.__name__} (a " "NumPy scalar with .item(), a date or time string with date.fromisoformat " "or datetime.fromisoformat): Orcapod converts no value" + + _bare_reference_hint(value) ) if isinstance(value, datetime): zoned = getattr(arrow_type, "tz", None) is not None @@ -527,6 +528,21 @@ def check_value_for_column( ) +def _bare_reference_hint(value: object) -> str: + """Return what a bool value given for a column of another type may come from. + + A bare reference (``col(c)``, ``~col(c)``) is the equality to ``True`` or ``False``, + so a bare reference to a column that is not boolean meets the value check here. + """ + if type(value) is not bool: + return "" + return ( + ". A bare col(c) stands for col(c) == True and ~col(c) for col(c) == False: " + "both take a boolean column only; compare a column of another type with a " + "value of its own type" + ) + + def _literal_repr(value: object) -> str: """Show a rejected literal even when Python limits integer string conversion.""" if type(value) is int: @@ -716,7 +732,7 @@ def check_condition_columns( raise TypeError( f"column {term.path.column!r} holds {getattr(column_type, '__name__', column_type)}, " f"but the value {one!r} is a {type(one).__name__}; convert it " - "explicitly: Orcapod converts no value" + "explicitly: Orcapod converts no value" + _bare_reference_hint(one) ) @@ -871,7 +887,7 @@ def _matched_by_bits(value: object) -> bool: def check_float_equalities( - *conditions: Mapping[str, object] | Condition | None, **columns: object + *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object ) -> None: """For now, refuse equality to ``-0.0`` or NaN before merging (ITL-1480). @@ -1106,6 +1122,55 @@ def __gt__(self, other: object) -> Condition: def __ge__(self, other: object) -> Condition: return self._term(">=", other) + def is_true(self) -> Condition: + """Return the condition that this boolean column is true: ``col(c) == True``. + + A bare reference stands for it wherever a condition is taken + (``filter(col("flag"))``, ``col("flag") & (col("t") > 1)``), so the two forms + are one condition, with one identity. A null is not true, so a row with a null + is not kept. The column must be boolean, checked when the condition meets a + stream. + + Returns: + The condition. + """ + return self._term(EQUALS, True) + + def __invert__(self) -> Condition: + """Return the condition that this boolean column is false: ``col(c) == False``. + + ``~col("flag")`` and ``col("flag") == False`` are one condition, with one + identity. A null is neither true nor false, so a row with a null is kept by + neither ``col("flag")`` nor ``~col("flag")``. + """ + return self._term(EQUALS, False) + + def __and__(self, other: object) -> Condition: + """Return ``self.is_true() & other`` (``other`` a condition or a reference).""" + right = _as_condition(other) + if right is None: + return NotImplemented + return self.is_true() & right + + def __rand__(self, other: object) -> Condition: + left = _as_condition(other) + if left is None: + return NotImplemented + return left & self.is_true() + + def __or__(self, other: object) -> Condition: + """Return ``self.is_true() | other`` (``other`` a condition or a reference).""" + right = _as_condition(other) + if right is None: + return NotImplemented + return self.is_true() | right + + def __ror__(self, other: object) -> Condition: + left = _as_condition(other) + if left is None: + return NotImplemented + return left | self.is_true() + __hash__ = None # pyright: ignore[reportAssignmentType] # == builds a condition, so no hash def __bool__(self) -> Never: @@ -1127,6 +1192,16 @@ def __repr__(self) -> str: ) +def _as_condition(value: object) -> Condition | None: + """Return ``value`` as a condition: a bare reference is ``is_true()``; ``None`` for + anything that is neither a condition nor a reference.""" + if isinstance(value, ColumnRef): + return value.is_true() + if isinstance(value, Condition): + return value + return None + + def col(name: str) -> ColumnRef: """Return a reference to the column ``name``, to build conditions on. @@ -1135,7 +1210,10 @@ def col(name: str) -> ColumnRef: ``not`` raise ``TypeError``. Pass separate conditions to ``filter()`` (or separate equality keywords to ``where()``), or combine conditions with ``&``, ``|`` and ``~``, putting each comparison in parentheses. For a range, use - ``col("t").between(1, 5)``, which includes both ends. + ``col("t").between(1, 5)``, which includes both ends. A bare reference to a boolean + column is a condition too: ``col("flag")`` keeps the rows where it is true + (``col("flag") == True``) and ``~col("flag")`` those where it is false + (``col("flag") == False``); a null is kept by neither. Example:: @@ -1249,7 +1327,7 @@ def _of_children(cls, children: tuple[Node, ...]) -> Condition: def of( cls, /, - *conditions: Mapping[str, object] | Condition | None, + *conditions: Mapping[str, object] | Condition | ColumnRef | None, **columns: object, ) -> Condition: """Build a condition from conditions and column values, as ``where()`` and @@ -1258,7 +1336,8 @@ def of( ``Condition.of(unit_id=106)``, ``Condition.of({"unit_id": 106})`` and both together are one condition: each named column must equal its value. A positional argument is a mapping (column name to value) or a condition (built beforehand, - or with ``col``); all of them and every keyword must hold. Given one condition + or with ``col``; a bare ``col(c)`` of a boolean column is ``col(c) == True``); + all of them and every keyword must hold. Given one condition and nothing else, it returns it unchanged. Args: @@ -1293,8 +1372,10 @@ def of( for argument in conditions: if argument is None: continue - if isinstance(argument, Condition): - built.append(argument) + if isinstance(argument, (Condition, ColumnRef)): + condition_argument = _as_condition(argument) + assert condition_argument is not None + built.append(condition_argument) elif isinstance(argument, Mapping): for column, given in argument.items(): value = _checked_value(column, given) @@ -1449,17 +1530,21 @@ def combined(self, other: Condition) -> Condition: children.append(node) return Condition._of_children(tuple(children)) - def __and__(self, other: Condition) -> Condition: - """Return ``self.combined(other)``: both must hold.""" - if not isinstance(other, Condition): + def __and__(self, other: Condition | ColumnRef) -> Condition: + """Return ``self.combined(other)``: both must hold (a bare reference to a + boolean column is ``is_true()``).""" + right = _as_condition(other) + if right is None: return NotImplemented - return self.combined(other) + return self.combined(right) - def __or__(self, other: Condition) -> Condition: + def __or__(self, other: Condition | ColumnRef) -> Condition: """Return the condition that this one or ``other`` holds (Kleene: unknown or - true is true).""" - if not isinstance(other, Condition): + true is true; a bare reference to a boolean column is ``is_true()``).""" + converted = _as_condition(other) + if converted is None: return NotImplemented + other = converted if self.is_empty or other.is_empty: raise ValueError( "an empty condition holds for every row, so 'or' with it holds for " diff --git a/tests/test_core/operators/test_filter_boolean_column.py b/tests/test_core/operators/test_filter_boolean_column.py new file mode 100644 index 000000000..4028feb69 --- /dev/null +++ b/tests/test_core/operators/test_filter_boolean_column.py @@ -0,0 +1,377 @@ +"""A bare boolean column is a condition: ``filter(col("flag"))`` and ``~col("flag")``. + +``col(c)`` given where a condition is taken stands for ``col(c) == True`` and +``~col(c)`` for ``col(c) == False``: one condition each, with the identity of that +equality, so no new condition kind and no new identity form exist. A null is neither +true nor false, so a row with a null is kept by neither. A column that is not boolean +is refused when the condition meets the stream. A SpiralDB source's ``where`` sends the +two forms as the equalities they are. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col +from orcapod.core.operators import Filter +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InputValidationError +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.sources import SpiralDBTableSource +from orcapod.types import CacheMode, Condition +from tests.test_databases import fake_spiral_sdk + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +# Rows: (row, session, good, flag, ok, v) +# good and flag are boolean (good a tag, flag data), each with a null. +_ROWS = [ + (1, "s1", True, True, True, 10), + (2, "s1", False, False, True, 20), + (3, "s2", None, None, False, 30), + (4, "s2", True, True, None, 40), + (5, "s3", False, False, False, 50), +] + + +def _table(layout: str = "tags_first") -> pa.Table: + columns = { + "row": pa.array([r[0] for r in _ROWS], pa.int64()), + "session": pa.array([r[1] for r in _ROWS], pa.large_string()), + "good": pa.array([r[2] for r in _ROWS], pa.bool_()), + "flag": pa.array([r[3] for r in _ROWS], pa.bool_()), + "ok": pa.array([r[4] for r in _ROWS], pa.bool_()), + "v": pa.array([r[5] for r in _ROWS], pa.int64()), + } + order = list(columns) + if layout == "data_first": + order = ["v", "ok", "flag", "good", "session", "row"] + return pa.table({name: columns[name] for name in order}) + + +def _source( + layout: str = "tags_first", + tag_columns: tuple[str, ...] = ("row", "session", "good"), +) -> ArrowTableSource: + return ArrowTableSource( + _table(layout), + tag_columns=list(tag_columns), + tag_only_columns=True, + source_id="flags", + ) + + +def _rows(stream: Any) -> list[int]: + return sorted(row["row"] for row in stream.as_table().to_pylist()) + + +# --- Rows: true, false, null -------------------------------------------------------- + + +class TestRows: + @pytest.mark.parametrize("column", ["flag", "good"], ids=["data", "tag"]) + def test_the_true_rows_and_the_false_rows(self, column): + """``col(c)`` keeps the true rows, ``~col(c)`` the false ones; the null row + (row 3) is kept by neither.""" + source = _source() + assert _rows(source.filter(col(column))) == [1, 4] + assert _rows(source.filter(~col(column))) == [2, 5] + + def test_a_data_tag_is_filtered_alike(self): + """A boolean data-tag (tag and data at once) is named alike.""" + source = ArrowTableSource( + _table(), + tag_columns=["row", "session", "flag"], + tag_only_columns=False, + source_id="flags", + ) + assert _rows(source.filter(col("flag"))) == [1, 4] + assert _rows(source.filter(~col("flag"))) == [2, 5] + + @pytest.mark.parametrize("layout", ["tags_first", "data_first"]) + @pytest.mark.parametrize( + "tag_columns", + [("row", "session", "good"), ("good", "session", "row")], + ids=["tags_a", "tags_b"], + ) + def test_several_boolean_columns_combined(self, layout, tag_columns): + """Bare columns combine with each other and with every other condition, in + either operand order, on several tag orders and table layouts.""" + source = _source(layout, tag_columns) + cases = [ + (col("flag") & col("ok"), [1]), + (col("ok") & col("flag"), [1]), + (col("flag") | ~col("ok"), [1, 3, 4, 5]), + (~col("ok") | col("flag"), [1, 3, 4, 5]), + (col("good") & (col("v") > 15), [4]), + ((col("v") > 15) & col("good"), [4]), + (~col("good") | (col("session") == "s2"), [2, 3, 4, 5]), + ((col("session") == "s2") | ~col("good"), [2, 3, 4, 5]), + (~col("flag") & ~col("ok"), [5]), + (~(col("flag") | col("ok")), [5]), + ] + for condition, expected in cases: + assert _rows(source.filter(condition)) == expected, condition + # Separate arguments all hold, in any order, mixed with keywords. + assert _rows(source.filter(col("flag"), col("ok"))) == [1] + assert _rows(source.filter(col("ok"), col("flag"))) == [1] + assert _rows(source.filter(~col("ok"), session="s3")) == [5] + assert _rows(source.filter({"session": "s3"}, ~col("good"))) == [5] + + def test_a_struct_field(self): + """``col(c).field(f)`` of a boolean field is a condition too.""" + table = pa.table( + { + "row": [1, 2, 3, 4], + "info": pa.array( + [{"bad": True}, {"bad": False}, {"bad": None}, None], + pa.struct([pa.field("bad", pa.bool_())]), + ), + } + ) + source = ArrowTableSource( + table, tag_columns=["row"], tag_only_columns=True, source_id="s" + ) + assert _rows(source.filter(col("info").field("bad"))) == [1] + assert _rows(source.filter(~col("info").field("bad"))) == [2] + + +# --- Refusals ------------------------------------------------------------------------ + + +class TestRefusals: + @pytest.mark.parametrize( + "condition", + [col("v"), ~col("v"), col("session"), ~col("session")], + ids=["int", "not int", "string tag", "not string tag"], + ) + def test_a_column_that_is_not_boolean_is_refused(self, condition): + """At validation (the stream's types are known then), naming the remedy.""" + with pytest.raises(InputValidationError, match="bare col"): + _source().filter(condition) + + def test_a_struct_field_that_is_not_boolean_is_refused(self): + table = pa.table( + { + "row": [1, 2], + "info": pa.array( + [{"n": 1}, {"n": 2}], pa.struct([pa.field("n", pa.int64())]) + ), + } + ) + source = ArrowTableSource( + table, tag_columns=["row"], tag_only_columns=True, source_id="s" + ) + with pytest.raises(InputValidationError, match="bare col"): + source.filter(col("info").field("n")).as_table() + + def test_no_truth_value(self): + """``not col(c)`` and ``col(a) and col(b)`` still raise, as before.""" + with pytest.raises(TypeError): + not col("flag") # noqa: B015 # pyright: ignore[reportGeneralTypeIssues] # the truth test is what is tested + with pytest.raises(TypeError): + col("flag") and col("ok") # noqa: B015 # the truth test is what is tested + + def test_anything_else_is_not_combined(self): + with pytest.raises(TypeError): + col("flag") & True # pyright: ignore[reportOperatorIssue, reportUnusedExpression] # refused at run time + with pytest.raises(TypeError): + "x" | col("flag") # pyright: ignore[reportOperatorIssue, reportUnusedExpression] # refused at run time + + +# --- Identity ------------------------------------------------------------------------ + + +class TestIdentity: + def test_a_bare_column_is_the_equality_to_true(self): + """One condition and one identity with ``== True`` and ``flag=True``.""" + source = _source() + bare = source.filter(col("flag")) + assert Condition.of(col("flag")) == (col("flag") == True) # noqa: E712 # the equality is what is compared + assert Condition.of(col("flag")) == Condition.of(flag=True) + assert bare.content_hash() == source.filter(flag=True).content_hash() + assert bare.pipeline_hash() == source.filter(flag=True).pipeline_hash() + assert ( + Filter(col("flag")).identity_structure() + == Filter(Condition.of(flag=True)).identity_structure() + ) + + def test_the_negation_is_the_equality_to_false(self): + source = _source() + assert (~col("flag")) == (col("flag") == False) # noqa: E712 # the equality is what is compared + assert source.filter(~col("flag")).content_hash() == ( + source.filter(flag=False).content_hash() + ) + + def test_the_negation_differs_from_the_plain_form(self): + source = _source() + plain, negated = source.filter(col("flag")), source.filter(~col("flag")) + assert plain.content_hash() != negated.content_hash() + assert plain.pipeline_hash() != negated.pipeline_hash() + assert Condition.of(col("flag")) != ~col("flag") + + @pytest.mark.parametrize( + "first, second", + [ + (col("flag") & col("ok"), col("ok") & col("flag")), + (col("flag") | ~col("ok"), ~col("ok") | col("flag")), + ( + (col("v") > 15) & col("good") & ~col("ok"), + ~col("ok") & col("good") & (col("v") > 15), + ), + ( + Condition.of(col("flag"), ~col("good"), session="s1"), + Condition.of({"session": "s1"}, ~col("good"), col("flag")), + ), + ], + ids=["and", "or", "three", "arguments"], + ) + def test_the_order_written_never_counts(self, first, second): + """Equal conditions written in different orders: equal conditions, forms, + saved forms and hashes.""" + source = _source() + assert first == second + assert first.canonical_form() == second.canonical_form() + assert first.to_config() == second.to_config() + assert ( + source.filter(first).content_hash() == source.filter(second).content_hash() + ) + assert ( + source.filter(first).pipeline_hash() + == source.filter(second).pipeline_hash() + ) + + def test_the_saved_form_is_the_equality(self): + """``to_config`` writes the equality, which reads back as the same condition.""" + assert Condition.of(col("flag")).to_config() == {"flag": True} + assert Condition.of(~col("flag")).to_config() == {"flag": False} + mixed = col("flag") | ~col("ok") + assert Condition.from_config(mixed.to_config()) == mixed + + +# --- Execution paths and a saved job ------------------------------------------------- + + +class TestJob: + @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) + def test_sync_and_async_keep_the_same_rows(self, tmp_path, orchestrator): + job = PipelineJob(name="flags", database=DeltaTableDatabase(tmp_path)) + with job: + source = _source() + source.filter(col("flag") & ~col("ok"), label="plain_and_not") + source.filter(~col("good") | col("ok"), label="not_or_plain") + job.run(orchestrator=orchestrator() if orchestrator else None) + assert _rows(job.nodes["plain_and_not"]) == [] + assert _rows(job.nodes["not_or_plain"]) == [1, 2, 5] + + def test_a_saved_job_reloads_the_same_filter(self, tmp_path: Path): + store = tmp_path / "store" + database = DeltaTableDatabase(store) + job = PipelineJob(name="flags", database=database) + condition = (col("flag") | ~col("ok")) & ~col("good") + with job: + _source().filter(condition, label="kept") + job.nodes["kept"].attach_databases( + pipeline_database=database.at("flags"), cache_mode=CacheMode.LOG + ) + job.run() + expected = _rows(job.nodes["kept"]) + assert expected == [5] + + path = tmp_path / "job.json" + job.save(path) + loaded = PipelineJob.load(path, database=DeltaTableDatabase(store)) + kept, reloaded = job.nodes["kept"], loaded.nodes["kept"] + assert reloaded.pipeline_hash() == kept.pipeline_hash() + assert reloaded.content_hash() == kept.content_hash() + operator = reloaded.producer + assert isinstance(operator, Filter) + assert operator.condition == condition + assert _rows(reloaded.as_source()) == expected + + +# --- SpiralDB where ------------------------------------------------------------------ + +_PROJECT = "workshop-sample" +_KEYS = pa.schema([pa.field("unit", pa.string()), pa.field("t", pa.uint64())]) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """A fake SpiralDB project holding a keyed table with two boolean columns.""" + monkeypatch.setattr(fake_spiral_sdk, "scan_batch_rows", 2) + with fake_spiral_sdk.install(tmp_path / "spiral"): + project = fake_spiral_sdk.ExternalProject(_PROJECT) + project.create_table("default.marks", key_schema=_KEYS).write( + pa.table( + { + "unit": ["a", "a", "b", "b", "c"], + "t": pa.array([1, 2, 3, 4, 5], pa.uint64()), + "flag": pa.array([True, False, None, True, False]), + "ok": pa.array([True, True, False, None, False]), + "n": pa.array([1, 2, 3, 4, 5], pa.int32()), + } + ) + ) + fake_spiral_sdk.scan_log.clear() + yield project + fake_spiral_sdk.scan_log.clear() + + +def _marks() -> SpiralDBTableSource: + return SpiralDBTableSource( + _PROJECT, "marks", source_id="marks", tag_only_columns=True + ) + + +def _times(stream: Any) -> list[int]: + return sorted(stream.as_table()["t"].to_pylist()) + + +class TestSpiralDBWhere: + def test_the_bare_column_reaches_the_scan_as_equality_to_true(self, project): + restricted = _marks().where(col("flag")) + assert _times(restricted) == [1, 4] + assert repr(fake_spiral_sdk.scan_log[-1].kwargs["where"]) == "flag == True" + + def test_the_negation_reaches_the_scan_as_equality_to_false(self, project): + restricted = _marks().where(~col("flag")) + assert _times(restricted) == [2, 5] + assert repr(fake_spiral_sdk.scan_log[-1].kwargs["where"]) == "flag == False" + + @pytest.mark.parametrize( + "arguments", + [(col("flag"), ~col("ok")), (~col("ok"), col("flag"))], + ids=["flag_first", "ok_first"], + ) + def test_two_boolean_columns(self, project, arguments): + """Both hold; the null rows of either column are read by neither form.""" + assert _times(_marks().where(*arguments)) == [] + assert _times(_marks().where(col("flag"), col("ok"))) == [1] + assert _times(_marks().where(~col("flag"), ~col("ok"))) == [5] + + def test_a_restriction_keeps_the_source_identity(self, project): + source = _marks() + restricted = source.where(~col("flag")) + assert restricted.content_hash() == source.content_hash() + assert restricted.condition == Condition.of(flag=False) + + def test_where_and_filter_read_the_same_rows(self, project): + source = _marks() + for condition in (col("flag"), ~col("flag")): + assert _times(source.where(condition)) == _times(source.filter(condition)) + + def test_a_column_that_is_not_boolean_is_refused(self, project): + with pytest.raises(TypeError, match="bare col"): + _marks().where(col("n")) + + def test_or_is_still_not_pushed_down(self, project): + """``|`` stays refused by ``where`` (a restriction is equalities and ranges); + filter it instead.""" + with pytest.raises(TypeError, match="where takes equalities"): + _marks().where(col("flag") | col("ok")) diff --git a/tests/test_types_condition_tree.py b/tests/test_types_condition_tree.py index 46a1f591e..976c36ba8 100644 --- a/tests/test_types_condition_tree.py +++ b/tests/test_types_condition_tree.py @@ -161,8 +161,9 @@ def test_a_column_reference_is_not_hashable(self): def test_and_with_something_else_is_refused(self): with pytest.raises(TypeError): _ = (col("t") > 1.0) & True # pyright: ignore[reportOperatorIssue] + # A bare col("u") is a condition (col("u") == True, ITL-1777); a string is not. with pytest.raises(TypeError): - _ = (col("t") > 1.0) | col("u") # pyright: ignore[reportOperatorIssue] + _ = (col("t") > 1.0) | "u" # pyright: ignore[reportOperatorIssue] def test_or_and_not_of_the_empty_condition_are_refused(self): with pytest.raises(ValueError, match="every row"):