From 90fd13e12834b8d7d4020fc2856d1fbc74d3958c Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 21:34:34 -0800 Subject: [PATCH 1/2] fix(filters): PolarsFilter warns on every construction; Filter is the documented filter (ITL-1296) PolarsFilter passes every column through Polars and can change values (a date64 off midnight comes back at midnight). That fault is deferred. Building a PolarsFilter, and loading a saved one (rebuilt or kept read-only), now issues PolarsFilterWarning every time. Filter was probed for the same fault and is exact; the probe is kept as a test. The documentation presents Filter. Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 8 +- CLAUDE.md | 8 +- changelog.d/ITL-1296.md | 20 + docs/api/errors.md | 2 + docs/concepts/operators.md | 44 ++- docs/concepts/sources.md | 2 +- docs/dev/design_issues/ITL-1296-PF2.md | 45 +++ docs/troubleshooting.md | 4 +- docs/tutorial/00-setup.md | 2 +- docs/tutorial/03-operators.md | 22 +- src/orcapod/core/operators/filters.py | 35 +- .../core/sources/spiraldb_table_source.py | 2 +- src/orcapod/errors.py | 19 + src/orcapod/pipeline/graph.py | 8 + src/orcapod/types/condition.py | 5 +- .../integration/test_pipeline_flows.py | 5 + .../integration/test_provenance.py | 5 + .../property/test_operator_algebra.py | 5 + test-specification/unit/test_operators.py | 4 + tests/test_arrays/test_array_operators.py | 4 + tests/test_channels/test_async_execute.py | 4 + tests/test_channels/test_pipeline_example.py | 4 + .../test_record_batch_channels.py | 4 + tests/test_core/alignment/test_operators.py | 4 + tests/test_core/data_tags/test_batch.py | 4 + .../data_tags/test_data_tag_order.py | 4 + .../test_core/data_tags/test_function_pods.py | 4 + tests/test_core/data_tags/test_merge_join.py | 4 + .../data_tags/test_merged_source_info.py | 4 + tests/test_core/data_tags/test_operators.py | 4 + tests/test_core/data_tags/test_tag_by.py | 4 + tests/test_core/operators/test_add_tags.py | 4 + .../operators/test_async_sync_equivalence.py | 3 + .../test_core/operators/test_empty_inputs.py | 4 + .../operators/test_filter_exact_values.py | 350 ++++++++++++++++++ .../operators/test_held_context_keys.py | 4 + .../operators/test_index_pick_arrow_types.py | 4 + .../operators/test_large_normalization.py | 4 + .../operators/test_materialize_source_info.py | 4 + .../operators/test_merge_join_arrow_types.py | 4 + .../operators/test_operator_config.py | 5 + tests/test_core/operators/test_operators.py | 4 + .../test_polars_filter_expression.py | 4 + .../operators/test_polars_filter_warning.py | 246 ++++++++++++ .../operators/test_provisional_operators.py | 4 + .../operators/test_record_batch_execution.py | 21 +- tests/test_core/operators/test_rejoin.py | 3 + .../operators/test_semijoin_tag_keys.py | 4 + .../test_core/operators/test_several_items.py | 11 +- .../operators/test_streaming_rejoin.py | 4 + .../test_side_effect_stream_as_table.py | 4 + tests/test_core/streams/test_explain.py | 3 + .../streams/test_head_and_preview.py | 4 + tests/test_core/streams/test_head_sorting.py | 4 + .../test_pass_through_operator_staleness.py | 4 + .../streams/test_several_items_methods.py | 11 +- .../test_stream_convenience_methods.py | 5 + tests/test_core/test_order_invariance.py | 3 + .../test_pydantic_dataclass_hashing.py | 4 + tests/test_pipeline/test_node_head.py | 4 + .../test_operator_node_async_readback.py | 4 + .../test_operator_node_empty_table_types.py | 4 + tests/test_pipeline/test_rows_on_read.py | 4 + .../test_stream_transport_equivalence.py | 4 + .../test_zero_row_column_order.py | 4 + .../test_zero_row_non_large_inputs.py | 4 + tests/test_torch/test_tensor_operators.py | 4 + 67 files changed, 993 insertions(+), 61 deletions(-) create mode 100644 changelog.d/ITL-1296.md create mode 100644 docs/dev/design_issues/ITL-1296-PF2.md create mode 100644 tests/test_core/operators/test_filter_exact_values.py create mode 100644 tests/test_core/operators/test_polars_filter_warning.py diff --git a/.zed/rules b/.zed/rules index 7b3a9a7be..beb76d466 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1350,7 +1350,13 @@ data. The rules: A row built by `Data` still gives an untyped null the `large_string` type. PolarsFilter is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (arrow_utils.restore_column_types and - restore_schema_nullability). Every other operator takes its values from the input's Arrow + restore_schema_nullability). The round trip changes values (a date64 off midnight comes + back at midnight) and is not fixed (ITL-1296, deferred; developer, November 28, 2026): + building a PolarsFilter issues PolarsFilterWarning every time (not once per process; a + load warns once per saved PolarsFilter node, rebuilt or kept read-only; one helper, + filters.warn_polars_filter_values), + Filter is the filter the user documentation shows, and PolarsFilter is mentioned there + only with that warning. Every other operator takes its values from the input's Arrow arrays (take, a slice, list offsets; Join, SemiJoin, MergeJoin and GroupBy give Polars only prepared keys and row numbers), so its values are the input's, bit for bit. This holds for every operator, also one that passes its rows through unchanged (select, diff --git a/CLAUDE.md b/CLAUDE.md index fa090f2f6..23d483749 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1398,7 +1398,13 @@ data. The rules: A row built by `Data` still gives an untyped null the `large_string` type. `PolarsFilter` is the one operator that still round-trips its columns through Polars; it casts them back to the normalized input types (`arrow_utils.restore_column_types` and - `restore_schema_nullability`). Every other operator takes its values from the input's Arrow + `restore_schema_nullability`). The round trip changes values (a `date64` off midnight comes + back at midnight) and is not fixed (ITL-1296, deferred; developer, November 28, 2026): + building a `PolarsFilter` issues `PolarsFilterWarning` every time (not once per process; a + load warns once per saved `PolarsFilter` node, rebuilt or kept read-only; one helper, + `filters.warn_polars_filter_values`), + `Filter` is the filter the user documentation shows, and `PolarsFilter` is mentioned there + only with that warning. Every other operator takes its values from the input's Arrow arrays (`take`, a slice, list offsets; `Join`, `SemiJoin`, `MergeJoin` and `GroupBy` give Polars only prepared keys and row numbers), so its values are the input's, bit for bit. This holds for every operator, also one that passes its rows through unchanged (select, diff --git a/changelog.d/ITL-1296.md b/changelog.d/ITL-1296.md new file mode 100644 index 000000000..c1b399c57 --- /dev/null +++ b/changelog.d/ITL-1296.md @@ -0,0 +1,20 @@ +### Changed + +- **`PolarsFilter` warns every time one is built; `Filter` is the filter to use** + (ITL-1296). `PolarsFilter` passes every column of its input through Polars, also the + columns its predicates do not read, and Polars does not hold every Arrow type exactly: a + `date64` value that is not at midnight comes back at midnight, with no error. That fault + is not fixed in this release. Building a `PolarsFilter` (the class, or + `stream.polars_filter(...)`) now issues the new `PolarsFilterWarning` (from + `orcapod.errors`) at every construction, in addition to the once-per-process + `ProvisionalHashWarning`; loading a saved job issues it once for each `PolarsFilter` + the job holds, at every load. Use `Filter` (`stream.filter(...)`), which passes every value + through as it is; the documentation now presents it as the filter. To silence the + warning: `warnings.filterwarnings("ignore", category=PolarsFilterWarning)`. No hash, + identity or stored path changes. + +### Known limitations + +- `PolarsFilter` can change the values of the rows it keeps (a `date64` off midnight is + moved to midnight), and a `decimal256` column can make Polars abort the process + (ITL-1296). Use `Filter`. diff --git a/docs/api/errors.md b/docs/api/errors.md index cd53180f1..2008bf91b 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -82,6 +82,8 @@ These exceptions and warnings report problems running pipelines, processing rows ::: orcapod.errors.RejoinDifferingColumnWarning +::: orcapod.errors.PolarsFilterWarning + ::: orcapod.errors.UpstreamFailedError ::: orcapod.errors.EmptyDataAccessError diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 58beec3fa..4a1acf029 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -907,43 +907,41 @@ known for this source kind". The result is an `Explanation` (`orcapod.types`), p whose `text()` is what it prints. The preview of a `Filter` directly over a source shows the same split in one line of its header. -When `filter` cannot say what you need (arithmetic between columns, a string function), use +When `filter` cannot say what you need (arithmetic between columns, a string function), +compute the test as a column in a function pod and filter on that column. `PolarsFilter` +takes such an expression directly, but it is not recommended: see the warning in [PolarsFilter](#polarsfilter). ### PolarsFilter +!!! warning "Not recommended: it can change the values it passes through" + `PolarsFilter` passes every column of its input through Polars, also the columns its + predicates do not read, and Polars does not hold every Arrow type exactly. The known + case: a `date64` value that is not at midnight comes back at midnight, with no error + (ITL-1296, not fixed). Use [`Filter`](#filter), which passes every value through as it + is. Building a `PolarsFilter` (the class, or `stream.polars_filter(...)`) issues + `PolarsFilterWarning` (`orcapod.errors`) every time, and loading a saved job issues it + once for each `PolarsFilter` the job holds. The samples below issue it when they run. + !!! warning "Provisional" `PolarsFilter` is a [provisional operator](#provisional-operators): its identity is not frozen with data context v1 and may change in a later release (ITL-1247). Building one issues `ProvisionalHashWarning` once per process. -Filter rows using Polars expressions: - -```python -import polars as pl -from orcapod.operators import PolarsFilter - -filt = PolarsFilter(predicates=[pl.col("age") > 10]) -filtered = filt.process(source) -for tag, pkt in filtered: - print(f"{tag.as_dict()} -> {pkt.as_dict()}") -# {'subject_id': 'mouse_01'} -> {'age': 12, 'weight': 25.3} -# {'subject_id': 'mouse_03'} -> {'age': 15, 'weight': 27.8} -``` - -You can also filter by exact values using `constraints`: - -```python -filt = PolarsFilter(constraints={"subject_id": "mouse_01"}) -print(filt(source).as_table().to_pylist()) -# [{'subject_id': 'mouse_01', 'age': 12, 'weight': 25.3}] -``` +`PolarsFilter(predicates=[...], constraints={...})`, or `stream.polars_filter(*predicates, +**constraints)`, keeps the rows that satisfy every Polars expression in `predicates` and +equal every value in `constraints`. An equality or a comparison of a column with a value is +written with [`Filter`](#filter) instead: `stream.filter(col("age") > 10)`, +`stream.filter(subject_id="mouse_01")`. An expression predicate is part of the filter's identity, so a filtered stream can feed a join, a function pod or a `PipelineJob`. Two filters written with the same expression share their hashes, even when the expression is spelled differently: ```python +import polars as pl +from orcapod.operators import PolarsFilter + by_operator = PolarsFilter(predicates=[pl.col("age") > 10])(source) by_method = source.polars_filter(pl.col("age").gt(10)) print(by_operator.pipeline_hash() == by_method.pipeline_hash()) @@ -985,7 +983,7 @@ except ValueError as exc: each named column from `T | None` to `T`. `DropNulls()`, with no names, does this for every tag and data column (see [Every column](#every-column) below). Use it when a column is nullable by specification but a function needs a value: a pod whose parameter is a plain `int` refuses an `int | None` -column, and `Filter` or `PolarsFilter` can drop the null rows but leave the type as it was. +column, and `Filter` can drop the null rows but leaves the type as it was. ```python import pyarrow as pa diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 589c57427..f1ee8c291 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -625,7 +625,7 @@ print(Condition.of(day=day, started=started, recorded=recorded)) revisiting the float refusals. SpiralDB cannot compare a `float16` column, so Orcapod reads the rows the other conditions select and compares them itself, by the same rule and before `limit`. To select rows by such values as Orcapod matches them, filter - inside the pipeline (`PolarsFilter`). An infinite value is saved as `{"float": "inf"}` or + inside the pipeline (`Filter`). An infinite value is saved as `{"float": "inf"}` or `{"float": "-inf"}`, since JSON has no such number. - **One restriction per source identity in a pipeline.** Restrictions are equal by statement. On an integer column, `t >= 3` and `t > 2` select the same rows but count as two diff --git a/docs/dev/design_issues/ITL-1296-PF2.md b/docs/dev/design_issues/ITL-1296-PF2.md new file mode 100644 index 000000000..43ae6da57 --- /dev/null +++ b/docs/dev/design_issues/ITL-1296-PF2.md @@ -0,0 +1,45 @@ +## `src/orcapod/core/operators/filters.py` — `PolarsFilter` identity and nullability (ITL-828) + +### PF2 — `PolarsFilter` carries every column through Polars and changes values +**Status:** open +**Severity:** critical +**Issue:** ITL-1296 (related: ITL-1284, ITL-1374) + +`PolarsFilter.unary_static_process` builds a Polars frame of the whole table, filters it +and converts the result back to Arrow, then casts it to the input types. Every column goes +through Polars, also the columns the predicates never read, and Polars does not hold every +Arrow type exactly: a `date64` data column `[1, 86400001]` ms comes back `[0, 86400000]` ms, +with no error, and a `decimal256` column is reported to make Polars panic, which no caller +can catch. A filter must pass the rows it keeps unchanged. + +**Deferred (developer, November 28, 2026):** "defer using polars filter and entirely focus on +filter for the users. For now I'd be even fine for PolarFilter to always throw a warning when +instantiated." The value fault is not fixed. Instead: + +- Building a `PolarsFilter` (the class, or `stream.polars_filter(...)`) issues + `PolarsFilterWarning` (`orcapod.errors`, a `UserWarning`) every time, not once per process: + it names the fault and `Filter` as the operator to use. It is shown at the user's line + (`warning_utils.warn_at_frame`) and is in addition to the once-per-process + `ProvisionalHashWarning`, which is unchanged. The warning enters no identity; no golden + value moves. +- Every route that builds one warns: `PolarsFilter.from_config`, + `serialization.resolve_operator_from_config`, and `PipelineJob.load` / `Pipeline.load`, + once per saved `PolarsFilter` node at every load. A saved filter a load cannot rebuild (a + predicate that is not an expression) is kept read-only and its constructor never runs; the + load warns for it too (`graph.py`, beside the provisional warning of such a node), so + loading is uniform. One helper issues the warning, `filters.warn_polars_filter_values`. + Running or saving a job does not warn. +- Tests that build a `PolarsFilter` for another purpose ignore the warning with a per-file + `pytestmark` and a reason; `tests/test_core/operators/test_polars_filter_warning.py` + asserts it on every route. No pytest configuration ignores it. +- `Filter` (ITL-1374) is the filter the documentation presents. It chooses rows with an + Arrow mask and takes them from the input table (`filter_mask.filter_table`); it was probed + for this fault and is exact. The probe is kept as + `tests/test_core/operators/test_filter_exact_values.py`: a `date64` off midnight, + `time64[ns]` below a microsecond, a float32 signaling NaN, `-0.0`, `decimal128` and + `decimal256` at full precision, logical types, strings and binaries of both widths, lists + and structs, each as tag, data and data-tag, in two table arrangements, on the sync path, + the row channel path and in a job run by either orchestrator. + +Still open: `PolarsFilter` itself (Polars decides which rows are kept, the rows are taken +from the Arrow table), or its removal. diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index fed7b5d4b..be8ca4f50 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -159,7 +159,9 @@ can. Ordinary comparisons such as `pl.col("x") > 1` work everywhere. **Fix.** Use `filter` (`stream.filter(column=value)`, `stream.filter(col("x") > 1)`), which takes equalities, comparisons, `is_in`, `between` and null tests and needs no Polars expression, or compute a boolean column in a function pod and filter on it. See -[Filter](concepts/operators.md#filter) and [PolarsFilter](concepts/operators.md#polarsfilter). +[Filter](concepts/operators.md#filter). `polars_filter` is not recommended: it can change +the values it passes through, and warns every time one is built; see the warning in +[PolarsFilter](concepts/operators.md#polarsfilter). ### `AttributeError: 'PipelineJob' has no attribute 'show_graph'. Available node labels: [...]` diff --git a/docs/tutorial/00-setup.md b/docs/tutorial/00-setup.md index 78d856a87..9515651e2 100644 --- a/docs/tutorial/00-setup.md +++ b/docs/tutorial/00-setup.md @@ -80,7 +80,7 @@ These messages are harmless. - `ProvisionalHashWarning: Filter is provisional: its identity is not frozen ...`, once per Python session for each provisional step you use: `filter`, `group_by`, `batch`, - `MergeJoin`, `polars_filter` and `as_source()` in this tutorial. The step works; what may still + `MergeJoin` and `as_source()` in this tutorial. The step works; what may still change is the identity Orcapod gives it. If a later release changes it, the results of that step and of every step after it are computed again instead of reused; nothing stored is lost or wrong. See [Provisional operators](../concepts/operators.md#provisional-operators). diff --git a/docs/tutorial/03-operators.md b/docs/tutorial/03-operators.md index 1e4eb689d..b1af51cf1 100644 --- a/docs/tutorial/03-operators.md +++ b/docs/tutorial/03-operators.md @@ -143,22 +143,10 @@ print(busy.explain()) # applied after reading: n_spikes > 1200 (Filter) ``` -When `filter` cannot say what you need (arithmetic between columns, a string function), use -`polars_filter` with a [Polars](https://docs.pola.rs/) expression: - -```python -import polars as pl - -fast = units.join(sessions).polars_filter(pl.col("n_spikes") / pl.col("duration_s") > 8) -print(fast.as_table().num_rows) -# 13 -``` - -The expression can use comparisons, arithmetic, `&`, `|`, `~`, `is_in`, `is_between`, -`is_null` and a few string tests. One that calls your own Python code (`map_elements`, -`map_batches`) is refused when the stream is used in a join, a pod or a job; compute such a -test in a function pod. The full list is in -[PolarsFilter](../concepts/operators.md#polarsfilter). +`filter` compares a column with a value or with another column. A test it cannot say +(arithmetic between columns, such as spikes per second, or a string function) is computed +first: write a function pod that returns the test's result as a column (Part 2), then +`filter` on that column. ## Semi-join @@ -315,7 +303,7 @@ Each list holds the first input's value, then the second's. `MergeJoin()(imec1, names. Rename, or use `MergeJoin`, when names clash. - `filter` keeps rows by equality (`column=value`) or by conditions built with `col` (comparisons, `is_in`, `between`, null tests, `&`, `|`, `~`), with each comparison in parentheses. - `polars_filter` takes a Polars expression for anything else. + A test `filter` cannot say is computed as a column by a function pod, then filtered on. - `semi_join` filters one stream by the shared tags of another and adds no columns. - `map_data` and `map_tags` rename columns and keep the rest unless you pass `drop_unmapped=True`. diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index ce01c02b5..0b48a08dd 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -1,4 +1,5 @@ import logging +import sys from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from typing import Any, ClassVar, TYPE_CHECKING, TypeAlias @@ -8,9 +9,11 @@ from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.base import UnaryOperator from orcapod.core.streams import ArrowTableStream +from orcapod.errors import PolarsFilterWarning from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import ColumnConfig, Schema from orcapod.utils import arrow_utils +from orcapod.utils.warning_utils import outside_orcapod_stacklevel, warn_at_frame if TYPE_CHECKING: import numpy as np @@ -35,9 +38,36 @@ def _safe_text(value: object, write: Callable[[object], str]) -> str: return f"<{type(value).__name__}>" -class PolarsFilter(UnaryOperator): +_VALUE_WARNING = ( + "PolarsFilter passes every column through Polars, also the columns its predicates " + "do not read, and can change values of types Polars does not hold exactly (known " + "case: a date64 value that is not at midnight comes back at midnight). It is not " + "recommended: use Filter (stream.filter(...)), which passes every value through as " + "it is." +) +"""The text of ``PolarsFilterWarning`` (ITL-1296).""" + + +def warn_polars_filter_values() -> None: + """Issue ``PolarsFilterWarning``, shown at the first frame outside Orcapod. + + Called every time a ``PolarsFilter`` is built, and by a load for a saved one it keeps + read-only without building it (ITL-1296). Each call has a fresh registry + (``warn_at_frame``), so Python's once-per-line rule hides no repeat. """ - Operator that applies Polars filtering to a stream + caller = sys._getframe(outside_orcapod_stacklevel() - 1) # pyright: ignore[reportPrivateUsage] # as the warnings module does + warn_at_frame(_VALUE_WARNING, PolarsFilterWarning, caller) + + +class PolarsFilter(UnaryOperator): + """Operator that applies Polars filtering to a stream. Not recommended: use ``Filter``. + + Every column of the input passes through Polars, also the columns the predicates do + not read, and Polars does not hold every Arrow type exactly: a ``date64`` value that + is not at midnight comes back at midnight, with no error (ITL-1296). Building a + ``PolarsFilter`` therefore issues ``PolarsFilterWarning``, every time, in addition to + the once-per-process ``ProvisionalHashWarning``. ``Filter`` (``stream.filter(...)``) + chooses rows with an Arrow mask and passes every value through as it is. """ # Data-tags (ITL-1023): handled. @@ -62,6 +92,7 @@ def __init__( self.predicates = tuple(predicates) self.constraints = constraints if constraints is not None else {} super().__init__(**kwargs) + warn_polars_filter_values() def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: if len(self.predicates) == 0 and len(self.constraints) == 0: diff --git a/src/orcapod/core/sources/spiraldb_table_source.py b/src/orcapod/core/sources/spiraldb_table_source.py index 9b4642981..dcce1443f 100644 --- a/src/orcapod/core/sources/spiraldb_table_source.py +++ b/src/orcapod/core/sources/spiraldb_table_source.py @@ -538,7 +538,7 @@ def where( hash, source id, schema and system-tag columns, and every row it reads is the row this source reads, record id included; it adds no step to a pipeline. A pipeline that must select rows as part of what it computes uses an operator - (``SemiJoin``, ``PolarsFilter``) instead. SpiralDB applies the conditions in + (``SemiJoin``, ``Filter``) instead. SpiralDB applies the conditions in the scan, as for the ``where=`` argument: the two are one mechanism, and the conditions are added to any the source already has. Everything else is carried over (the pinned table version, ``limit``, ``max_rows``, tags, data-tags, diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 23f8dd2af..5fa18bf89 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -930,6 +930,25 @@ class SemiJoinIgnoredColumnWarning(UserWarning): """ +class PolarsFilterWarning(UserWarning): + """A ``PolarsFilter`` was built: it can change the values it passes through. + + ``PolarsFilter`` passes every column of its input through Polars, also the columns + its predicates do not read, and Polars does not hold every Arrow type exactly. The + known case: a ``date64`` value that is not at midnight comes back at midnight, with + no error (ITL-1296). ``PolarsFilter`` is not recommended. ``Filter`` + (``stream.filter(...)``) is the operator to use: it chooses rows with an Arrow mask + and passes every value through as it is. + + The warning is issued every time a ``PolarsFilter`` is built (the class, or + ``stream.polars_filter(...)``), not once per process, in addition to the + ``ProvisionalHashWarning`` of a provisional operator. + + To silence it, call ``warnings.filterwarnings("ignore", + category=PolarsFilterWarning)`` after importing Orcapod. + """ + + class UpstreamFailedError(Exception): """An input channel's producer failed before it finished (ITL-1347). diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index baec82ecf..0b58b8f37 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -552,6 +552,14 @@ def load(cls, path: str | Path) -> "Pipeline": saved_name = op_config.get("class_name") if saved_name in PROVISIONAL_OPERATORS: warn_provisional_operator(saved_name) + if saved_name == "PolarsFilter": + # Every load of a saved PolarsFilter warns, also one kept + # read-only, whose constructor never runs (ITL-1296). + from orcapod.core.operators.filters import ( + warn_polars_filter_values, + ) + + warn_polars_filter_values() if operator is not None: from orcapod.logical_types.identifier import ( LogicalTypeIdentifierError, diff --git a/src/orcapod/types/condition.py b/src/orcapod/types/condition.py index a3a418891..b93607743 100644 --- a/src/orcapod/types/condition.py +++ b/src/orcapod/types/condition.py @@ -1312,7 +1312,10 @@ def of( f"a condition is a mapping of column to value, or a condition " f"built with col(...); got {type(argument).__name__}. A mask " "by position is not a condition (row order is not a result); " - "for a Polars expression use polars_filter" + "a Polars expression is not one either: write it with col(...), " + "or compute it as a column in a function pod and filter on that " + "column (polars_filter takes one, but is not recommended: it " + "can change the values it passes through)" ) for column, given in columns.items(): value = _checked_value(column, given) diff --git a/test-specification/integration/test_pipeline_flows.py b/test-specification/integration/test_pipeline_flows.py index 21ab33170..4270af3db 100644 --- a/test-specification/integration/test_pipeline_flows.py +++ b/test-specification/integration/test_pipeline_flows.py @@ -20,6 +20,11 @@ ) from orcapod.core.data_function import PythonDataFunction from orcapod.core.sources import ArrowTableSource +import pytest + +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") # --------------------------------------------------------------------------- diff --git a/test-specification/integration/test_provenance.py b/test-specification/integration/test_provenance.py index e5225da75..474001c3c 100644 --- a/test-specification/integration/test_provenance.py +++ b/test-specification/integration/test_provenance.py @@ -13,6 +13,11 @@ from orcapod.core.operators import Batch, Join, MapTags, PolarsFilter, SelectDataColumns from orcapod.core.sources import ArrowTableSource from orcapod.system_constants import constants +import pytest + +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") # --------------------------------------------------------------------------- diff --git a/test-specification/property/test_operator_algebra.py b/test-specification/property/test_operator_algebra.py index d318cc15d..7bc05241d 100644 --- a/test-specification/property/test_operator_algebra.py +++ b/test-specification/property/test_operator_algebra.py @@ -19,6 +19,11 @@ SelectDataColumns, ) from orcapod.core.streams import ArrowTableStream +import pytest + +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") # --------------------------------------------------------------------------- diff --git a/test-specification/unit/test_operators.py b/test-specification/unit/test_operators.py index 2672ddfff..37b3d5245 100644 --- a/test-specification/unit/test_operators.py +++ b/test-specification/unit/test_operators.py @@ -29,6 +29,10 @@ from orcapod.errors import InputValidationError from orcapod.system_constants import constants +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + # --------------------------------------------------------------------------- # Helpers diff --git a/tests/test_arrays/test_array_operators.py b/tests/test_arrays/test_array_operators.py index 509a15f44..58469f5b2 100644 --- a/tests/test_arrays/test_array_operators.py +++ b/tests/test_arrays/test_array_operators.py @@ -33,6 +33,10 @@ sync_rows, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + NAMES = sorted(ARRAYS) GROUP = {name: f"g{i % 3}" for i, name in enumerate(NAMES)} diff --git a/tests/test_channels/test_async_execute.py b/tests/test_channels/test_async_execute.py index b1477f860..ec91c476a 100644 --- a/tests/test_channels/test_async_execute.py +++ b/tests/test_channels/test_async_execute.py @@ -43,6 +43,10 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.types import PodConfig, PipelineConfig +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + # --------------------------------------------------------------------------- # Helpers # --------------------------------------------------------------------------- diff --git a/tests/test_channels/test_pipeline_example.py b/tests/test_channels/test_pipeline_example.py index e4b1bc2e0..ae70452a9 100644 --- a/tests/test_channels/test_pipeline_example.py +++ b/tests/test_channels/test_pipeline_example.py @@ -35,6 +35,10 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.types import PipelineConfig, PodConfig +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + # --------------------------------------------------------------------------- # Domain functions diff --git a/tests/test_channels/test_record_batch_channels.py b/tests/test_channels/test_record_batch_channels.py index d4416e6db..cceaf6d05 100644 --- a/tests/test_channels/test_record_batch_channels.py +++ b/tests/test_channels/test_record_batch_channels.py @@ -64,6 +64,10 @@ from orcapod.types import Schema from tests.test_channels.test_polling_source import FakeDynamicSource, _batch +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + T = TypeVar("T") ALL = {"system_tags": True, "source": True} TIMEOUT = 5.0 diff --git a/tests/test_core/alignment/test_operators.py b/tests/test_core/alignment/test_operators.py index f9717b888..5a807f55b 100644 --- a/tests/test_core/alignment/test_operators.py +++ b/tests/test_core/alignment/test_operators.py @@ -62,6 +62,10 @@ from .expectations import groups, no_nulls, pairs, rows, semi from .oracle import Origin +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + @dataclass(frozen=True) class OpCase: diff --git a/tests/test_core/data_tags/test_batch.py b/tests/test_core/data_tags/test_batch.py index 02f0dedda..4534035ca 100644 --- a/tests/test_core/data_tags/test_batch.py +++ b/tests/test_core/data_tags/test_batch.py @@ -31,6 +31,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ROWS = [ {"s": "s1", "x": 20, "y": 5}, {"s": "s1", "x": 10, "y": 4}, diff --git a/tests/test_core/data_tags/test_data_tag_order.py b/tests/test_core/data_tags/test_data_tag_order.py index 5e9559ef1..eff729ec4 100644 --- a/tests/test_core/data_tags/test_data_tag_order.py +++ b/tests/test_core/data_tags/test_data_tag_order.py @@ -34,6 +34,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.types import CacheMode +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + JOB = "order" diff --git a/tests/test_core/data_tags/test_function_pods.py b/tests/test_core/data_tags/test_function_pods.py index c6874ba7a..91ec905c0 100644 --- a/tests/test_core/data_tags/test_function_pods.py +++ b/tests/test_core/data_tags/test_function_pods.py @@ -27,6 +27,10 @@ from orcapod.errors import InputValidationError from orcapod.pipeline import PipelineJob +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ROWS = [{"t": 10, "amp": 0.5}, {"t": 20, "amp": 0.25}] diff --git a/tests/test_core/data_tags/test_merge_join.py b/tests/test_core/data_tags/test_merge_join.py index c29dc8fa8..cf86ace2e 100644 --- a/tests/test_core/data_tags/test_merge_join.py +++ b/tests/test_core/data_tags/test_merge_join.py @@ -39,6 +39,10 @@ from orcapod.system_constants import constants from orcapod.utils import arrow_utils +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + JOIN_TOKEN = re.compile(rf"^{JOIN_FOLD_LABEL}:[0-9a-f]{{64}}$") diff --git a/tests/test_core/data_tags/test_merged_source_info.py b/tests/test_core/data_tags/test_merged_source_info.py index 614631f44..c4dde13a1 100644 --- a/tests/test_core/data_tags/test_merged_source_info.py +++ b/tests/test_core/data_tags/test_merged_source_info.py @@ -47,6 +47,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.utils import arrow_utils +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + GROUP_TOKEN = re.compile(rf"^{GROUP_BY_FOLD_LABEL}:[0-9a-f]{{64}}$") JOIN_TOKEN = re.compile(rf"^{JOIN_FOLD_LABEL}:[0-9a-f]{{64}}$") diff --git a/tests/test_core/data_tags/test_operators.py b/tests/test_core/data_tags/test_operators.py index a9a24aa02..a04c42585 100644 --- a/tests/test_core/data_tags/test_operators.py +++ b/tests/test_core/data_tags/test_operators.py @@ -47,6 +47,10 @@ from orcapod.errors import InputValidationError, SemiJoinIgnoredColumnWarning from orcapod.utils import arrow_utils +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + def _ref(rows: Sequence[Mapping[str, Any]], tags: list[str], sid: str, **kw: Any): return op.sources.DictSource(rows, tag_columns=tags, source_id=sid, **kw) diff --git a/tests/test_core/data_tags/test_tag_by.py b/tests/test_core/data_tags/test_tag_by.py index b549b8d11..8218112df 100644 --- a/tests/test_core/data_tags/test_tag_by.py +++ b/tests/test_core/data_tags/test_tag_by.py @@ -36,6 +36,10 @@ from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION, constants from orcapod.types import CacheMode +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ORCHESTRATORS = pytest.mark.parametrize( "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator], diff --git a/tests/test_core/operators/test_add_tags.py b/tests/test_core/operators/test_add_tags.py index f94ec2e14..c76ebead3 100644 --- a/tests/test_core/operators/test_add_tags.py +++ b/tests/test_core/operators/test_add_tags.py @@ -16,6 +16,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import constants +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + def _readings() -> ArrowTableSource: """Tag ``subject``; data ``x`` (int8, nullable) and ``name``.""" diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 72ce1358a..1376833e0 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -73,6 +73,9 @@ pytestmark = [ pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning"), pytest.mark.filterwarnings("ignore::orcapod.errors.RejoinDifferingColumnWarning"), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), ] Row: TypeAlias = tuple[TagProtocol, DataProtocol] diff --git a/tests/test_core/operators/test_empty_inputs.py b/tests/test_core/operators/test_empty_inputs.py index 22970a9f2..f3f4948d5 100644 --- a/tests/test_core/operators/test_empty_inputs.py +++ b/tests/test_core/operators/test_empty_inputs.py @@ -45,6 +45,10 @@ from orcapod.types import SourceInfoValue from orcapod.utils.arrow_utils import normalize_to_large_types +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + INT = pa.int64() STR = pa.large_string() diff --git a/tests/test_core/operators/test_filter_exact_values.py b/tests/test_core/operators/test_filter_exact_values.py new file mode 100644 index 000000000..3fac74db1 --- /dev/null +++ b/tests/test_core/operators/test_filter_exact_values.py @@ -0,0 +1,350 @@ +"""``Filter`` passes every value it keeps bit for bit (ITL-1296). + +``PolarsFilter`` carries every column through Polars and changes some values (a +``date64`` off midnight comes back at midnight). ``Filter`` chooses rows with an Arrow +mask and takes them from the input table, so every column, read by the condition or +not, must come out as it went in. This is the probe of ITL-1296 kept as a test: columns +of the types another representation changes (``date64`` off midnight, ``time64[ns]`` +below a microsecond, a float32 signaling NaN, ``-0.0``, ``decimal128`` and +``decimal256`` at full precision, logical types, strings and binaries of both widths, +lists and structs of them), each as a plain tag, as data and as a data-tag, in two +arrangements of the table, on the sync path, the row channel path and in a job run by +either orchestrator. + +A dictionary-encoded column is not here: no stream holds one (ITL-1264). +""" + +from __future__ import annotations + +import asyncio +import datetime as dt +import decimal +import struct +import uuid +from pathlib import Path +from typing import Any, TypeAlias + +import pyarrow as pa +import pyarrow.compute as pc +import pytest + +from orcapod import PipelineJob, col +from orcapod.channels import Channel +from orcapod.contexts import get_default_type_converter +from orcapod.core.operators import Filter +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import InMemoryArrowDatabase +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.protocols.core_protocols import DataProtocol, StreamProtocol, TagProtocol +from orcapod.types import Condition +from orcapod.utils import arrow_utils + +Row: TypeAlias = tuple[TagProtocol, DataProtocol] +Values: TypeAlias = "pa.Array[Any] | pa.ChunkedArray[Any]" + +N_ROWS = 4 +KEPT = [0, 2, 3] +"""The rows ``n in (10, 30, 40)`` keeps.""" + +# Every column group of a table: source info, system tags and the data context. +EVERYTHING = {"source": True, "system_tags": True, "context": True} + +# A float32 signaling NaN, as its bytes: a Python float would quiet it. +_SIGNALING_NAN = bytes.fromhex("0100807f") + + +def _logical(values: list[Any], python_type: Any) -> pa.Array[Any]: + """A column of ``values`` in Orcapod's logical Arrow type for ``python_type``.""" + return ( + get_default_type_converter() + .python_dicts_to_arrow_table( + [{"v": v} for v in values], python_schema={"v": python_type} + ) + .column("v") + .combine_chunks() + ) + + +def _probed_columns(prefix: str) -> dict[str, pa.Array[Any]]: + """One column of every probed type, named ````.""" + dates = pa.array([1, 86_400_001, 2, 172_800_003], pa.int64()).cast(pa.date64()) + floats32 = pa.Array.from_buffers( + pa.float32(), + N_ROWS, + [None, pa.py_buffer(_SIGNALING_NAN + struct.pack(" tuple[pa.Table, list[str]]: + """The probed table and its tag columns, laid out in one of two arrangements. + + Sixteen tag columns (``n`` and one of every probed type) and sixteen data columns + (``m`` and one of every probed type). ``"reversed"`` reverses the table's columns, + puts the data before the tags and declares the tags in the opposite order. + """ + tags = _probed_columns("t_") + data = _probed_columns("d_") + n = pa.array([10, 20, 30, 40], pa.int64()) + m = pa.array([1, 2, 3, 4], pa.int32()) + if arrangement == "given": + return pa.table({"n": n, **tags, "m": m, **data}), ["n", *tags] + columns = { + **dict(reversed(data.items())), + "m": m, + **dict(reversed(tags.items())), + "n": n, + } + return pa.table(columns), [*reversed(tags), "n"] + + +def _source(arrangement: str, role: str) -> tuple[ArrowTableSource, pa.Table]: + """A source over the probed table; its tags plain (``"tag"``) or data-tags.""" + table, tags = _table(arrangement) + source = ArrowTableSource( + table, + tag_columns=tags, + tag_only_columns=(role == "tag"), + source_id="probe", + ) + return source, table + + +def _filters(table: pa.Table) -> dict[str, Filter]: + """A filter that reads none of the probed columns, and one that reads all of them.""" + keep = Condition.of(col("n").is_in([10, 30, 40])) + reads_all = keep + for name in table.column_names: + if name not in ("n", "m"): + reads_all = reads_all.combined(Condition.of(col(name).is_not_null())) + return { + "reads_another_column": Filter(keep), + "reads_every_column": Filter(reads_all), + } + + +# ── bit-for-bit comparison ────────────────────────────────────────────────── + + +def _differences(actual: Values, expected: Values, where: str) -> list[str]: + """What differs between two columns, floats and temporal values by their bits.""" + a = actual.combine_chunks() if isinstance(actual, pa.ChunkedArray) else actual + b = expected.combine_chunks() if isinstance(expected, pa.ChunkedArray) else expected + if a.type != b.type: + return [f"{where}: type {a.type} is not {b.type}"] + if len(a) != len(b): + return [f"{where}: {len(a)} rows, expected {len(b)}"] + if a.is_valid().to_pylist() != b.is_valid().to_pylist(): + return [f"{where}: validity differs"] + arrow_type = a.type + if isinstance(arrow_type, pa.ExtensionType): + return _differences(a.storage, b.storage, f"{where}") # pyright: ignore[reportAttributeAccessIssue] # an extension array + if pa.types.is_floating(arrow_type): + bits = {2: pa.uint16(), 4: pa.uint32(), 8: pa.uint64()}[arrow_type.byte_width] + # ``take`` copies, so the view reads this array's own values at offset 0. + every = pa.array(range(len(a)), pa.int64()) + a_bits = a.take(every).view(bits).to_pylist() + b_bits = b.take(every).view(bits).to_pylist() + return [] if a_bits == b_bits else [f"{where}: bits {a_bits} are not {b_bits}"] + if ( + pa.types.is_list(arrow_type) + or pa.types.is_large_list(arrow_type) + or pa.types.is_fixed_size_list(arrow_type) + ): + if pc.list_value_length(a).to_pylist() != pc.list_value_length(b).to_pylist(): + return [f"{where}: list lengths differ"] + return _differences(a.flatten(), b.flatten(), f"{where}[]") # pyright: ignore[reportAttributeAccessIssue] # a list array + if pa.types.is_struct(arrow_type): + found: list[str] = [] + for index in range(arrow_type.num_fields): + found += _differences( + a.field(index), # pyright: ignore[reportAttributeAccessIssue] # a struct array + b.field(index), # pyright: ignore[reportAttributeAccessIssue] # a struct array + f"{where}.{arrow_type.field(index).name}", + ) + return found + if pa.types.is_temporal(arrow_type): + counts = pa.int64() if arrow_type.bit_width == 64 else pa.int32() + a_counts, b_counts = a.cast(counts).to_pylist(), b.cast(counts).to_pylist() + return ( + [] if a_counts == b_counts else [f"{where}: {a_counts} are not {b_counts}"] + ) + return [] if a.equals(b) else [f"{where}: values differ"] + + +def _table_differences( + actual: pa.Table, expected: pa.Table, given: pa.Table, kept: list[int] +) -> list[str]: + """What differs between a filter's output and the kept rows of its input. + + ``expected`` is the input stream's own table (every column group); ``given`` is the + table the source was built from, whose user columns the output must equal too (in + their large variants, the one change a stream makes). + """ + found: list[str] = [] + if actual.column_names != expected.column_names: + found.append(f"columns {actual.column_names} are not {expected.column_names}") + if actual.schema != expected.schema: + found.append("schemas differ") + for name in expected.column_names: + if name in actual.column_names: + found += _differences( + actual.column(name), expected.column(name).take(kept), name + ) + for name in given.column_names: + column = given.column(name).combine_chunks() + large = column.cast( + arrow_utils.normalize_to_large_types(column.type, keep_null=True) + ) + found += _differences(actual.column(name), large.take(kept), f"given {name}") + return found + + +# ── the paths ─────────────────────────────────────────────────────────────── + + +def _rows_table(rows: list[Row]) -> pa.Table: + """Rows of the channel path as one table: tags with system tags, then data with + source info (a data-tag once, from the tag).""" + tables: list[pa.Table] = [] + for tag, data in rows: + tag_table = tag.as_table(columns={"system_tags": True}) + data_table = data.as_table(columns={"source": True}) + data_table = data_table.drop_columns( + [n for n in data_table.column_names if n in tag_table.column_names] + ) + tables.append( + pa.Table.from_arrays( + [*tag_table.columns, *data_table.columns], + schema=pa.schema([*tag_table.schema, *data_table.schema]), + ) + ) + return pa.concat_tables(tables) + + +async def _through_channels(op: Filter, source: StreamProtocol) -> list[Row]: + upstream: Channel[Row] = Channel(buffer_size=64) + output: Channel[Row] = Channel(buffer_size=64) + for row in source.iter_data(): + await upstream.writer.send(row) + await upstream.writer.close() + await op.async_execute( + [upstream.reader], + output.writer, + input_pipeline_hashes=[source.pipeline_hash()], + ) + return await output.reader.collect() + + +ARRANGEMENTS = ("given", "reversed") +ROLES = ("tag", "data_tag") +FILTERS = ("reads_another_column", "reads_every_column") + + +@pytest.mark.parametrize("which", FILTERS) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +def test_sync_path_keeps_every_value(arrangement: str, role: str, which: str) -> None: + source, given = _source(arrangement, role) + out = _filters(given)[which](source).as_table(columns=EVERYTHING) + assert out.num_rows == len(KEPT) + expected = source.as_table(columns=EVERYTHING) + assert _table_differences(out, expected, given, KEPT) == [] + + +@pytest.mark.parametrize("which", FILTERS) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +def test_channel_path_keeps_every_value( + arrangement: str, role: str, which: str +) -> None: + """The rows ``async_execute`` passes on are the input's rows, in the form the + channel carries them, and hold the values of the table the source was given.""" + source, given = _source(arrangement, role) + rows = asyncio.run(_through_channels(_filters(given)[which], source)) + assert len(rows) == len(KEPT) + out = _rows_table(rows) + expected = _rows_table(list(source.iter_data())) + assert _table_differences(out, expected, given, KEPT) == [] + + +@pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) +@pytest.mark.parametrize("which", FILTERS) +@pytest.mark.parametrize("role", ROLES) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +def test_job_keeps_every_value( + arrangement: str, role: str, which: str, orchestrator: type | None +) -> None: + source, given = _source(arrangement, role) + job = PipelineJob(name="exact", database=InMemoryArrowDatabase()) + with job: + _ = _filters(given)[which](source, label="kept") + _ = job.run(orchestrator=orchestrator() if orchestrator else None) + out = job.nodes["kept"].as_table(columns=EVERYTHING) + assert out.num_rows == len(KEPT) + expected = source.as_table(columns=EVERYTHING) + # A job node lays its columns out in row order (tags, system tags, data, source + # info), not the source table's: the same columns, compared by name. + assert sorted(out.column_names) == sorted(expected.column_names) + out = out.select(expected.column_names) + assert _table_differences(out, expected, given, KEPT) == [] + + +@pytest.mark.parametrize( + ("condition", "kept"), + [ + (col("d_f64") == 0.0, [0, 1]), + (col("d_f32") == 0.0, [1, 2]), + (col("t_f64") >= 0.0, [0, 1, 2, 3]), + (col("t_f32").is_in([0.0, 2.5]), [1, 2, 3]), + (col("d_date64") >= dt.date(1970, 1, 2), [1, 3]), + (col("t_large_str") != "a", [1, 2, 3]), + (col("d_struct").field("a").is_not_null(), [0, 1, 2, 3]), + ], + ids=str, +) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) +def test_a_condition_on_a_value_keeps_every_value( + arrangement: str, condition: Condition, kept: list[int] +) -> None: + """A condition that compares a probed column's values (a ``-0.0``, a signaling NaN, + a ``date64`` off midnight) changes none of them.""" + source, given = _source(arrangement, "tag") + out = Filter(condition)(source).as_table(columns=EVERYTHING) + expected = source.as_table(columns=EVERYTHING) + assert _table_differences(out, expected, given, kept) == [] diff --git a/tests/test_core/operators/test_held_context_keys.py b/tests/test_core/operators/test_held_context_keys.py index db3106a01..8c86eb185 100644 --- a/tests/test_core/operators/test_held_context_keys.py +++ b/tests/test_core/operators/test_held_context_keys.py @@ -53,6 +53,10 @@ make_source, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ALPHA = "std:v1:test-held-alpha" BETA = "std:v1:test-held-beta" HELD_KEYS = (ALPHA, ALPHA, BETA, BETA, ALPHA, ALPHA) diff --git a/tests/test_core/operators/test_index_pick_arrow_types.py b/tests/test_core/operators/test_index_pick_arrow_types.py index 0a6985609..c939d6001 100644 --- a/tests/test_core/operators/test_index_pick_arrow_types.py +++ b/tests/test_core/operators/test_index_pick_arrow_types.py @@ -53,6 +53,10 @@ from orcapod.types import DataType, DataValue from orcapod.utils.arrow_utils import normalize_schema_to_large_types +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + TAG = "tg" TAG8 = "tg8" TAGS = (TAG, TAG8) diff --git a/tests/test_core/operators/test_large_normalization.py b/tests/test_core/operators/test_large_normalization.py index 4c1ef095d..875a14cce 100644 --- a/tests/test_core/operators/test_large_normalization.py +++ b/tests/test_core/operators/test_large_normalization.py @@ -53,6 +53,10 @@ non_large_columns, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ORCHESTRATORS = { "sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator, diff --git a/tests/test_core/operators/test_materialize_source_info.py b/tests/test_core/operators/test_materialize_source_info.py index 831ca1f36..f415d34db 100644 --- a/tests/test_core/operators/test_materialize_source_info.py +++ b/tests/test_core/operators/test_materialize_source_info.py @@ -48,6 +48,10 @@ from orcapod.types import CacheMode from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + Row = tuple[TagProtocol, DataProtocol] # --------------------------------------------------------------------------- diff --git a/tests/test_core/operators/test_merge_join_arrow_types.py b/tests/test_core/operators/test_merge_join_arrow_types.py index 49945b1e8..7c2cbe7f8 100644 --- a/tests/test_core/operators/test_merge_join_arrow_types.py +++ b/tests/test_core/operators/test_merge_join_arrow_types.py @@ -46,6 +46,10 @@ from .several_items import async_rows +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + SCHEMA_CONFIGS: tuple[dict[str, bool], ...] = ({}, {"system_tags": True}) STRUCT = pa.struct([("a", pa.int8()), ("b", pa.string())]) LARGE_STRUCT = pa.struct([("a", pa.int8()), ("b", pa.large_string())]) diff --git a/tests/test_core/operators/test_operator_config.py b/tests/test_core/operators/test_operator_config.py index c0334b54c..b47fa90bf 100644 --- a/tests/test_core/operators/test_operator_config.py +++ b/tests/test_core/operators/test_operator_config.py @@ -16,6 +16,11 @@ SelectTagColumns, SemiJoin, ) +import pytest + +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") class TestJoinConfig: diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index b7bdcf2ea..7b766e7ac 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -20,6 +20,10 @@ from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + # --------------------------------------------------------------------------- # Fixtures diff --git a/tests/test_core/operators/test_polars_filter_expression.py b/tests/test_core/operators/test_polars_filter_expression.py index 5ef7185a0..64bc8e72f 100644 --- a/tests/test_core/operators/test_polars_filter_expression.py +++ b/tests/test_core/operators/test_polars_filter_expression.py @@ -22,6 +22,10 @@ from orcapod.pipeline import AsyncPipelineOrchestrator, PipelineJob from orcapod.sources import DictSource +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + def _readings() -> DictSource: return DictSource( diff --git a/tests/test_core/operators/test_polars_filter_warning.py b/tests/test_core/operators/test_polars_filter_warning.py new file mode 100644 index 000000000..5cd460334 --- /dev/null +++ b/tests/test_core/operators/test_polars_filter_warning.py @@ -0,0 +1,246 @@ +"""``PolarsFilter`` warns every time one is built (ITL-1296). + +``PolarsFilter`` passes every column through Polars, which changes values of types Polars +does not hold exactly (a ``date64`` off midnight comes back at midnight). Until that is +fixed, building one issues ``PolarsFilterWarning``, at every construction and at every load +of a saved one (rebuilt or kept read-only, once per node), in addition to +the once-per-process ``ProvisionalHashWarning``; ``Filter`` is the operator to use. +""" + +from __future__ import annotations + +import warnings +from pathlib import Path + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import PipelineJob +from orcapod.core.operators import Filter, PolarsFilter +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import PolarsFilterWarning, ProvisionalHashWarning +from orcapod.pipeline.serialization import resolve_operator_from_config +from orcapod.types import col +from orcapod.utils.provisional import reset_provisional_use_warnings + + +def _source() -> ArrowTableSource: + table = pa.table( + { + "session": pa.array(["s1", "s1", "s2"], pa.large_string()), + "unit": pa.array([3, 7, 3], pa.int64()), + "rate": pa.array([4.0, 2.5, 6.1], pa.float64()), + "depth": pa.array([10, 20, 30], pa.int32()), + } + ) + return ArrowTableSource( + table, + tag_columns=["session", "unit"], + tag_only_columns=True, + source_id="units", + ) + + +def _polars_filter_warnings( + caught: list[warnings.WarningMessage], +) -> list[warnings.WarningMessage]: + return [w for w in caught if issubclass(w.category, PolarsFilterWarning)] + + +def test_the_warning_is_a_user_warning() -> None: + assert issubclass(PolarsFilterWarning, UserWarning) + assert not issubclass(PolarsFilterWarning, ProvisionalHashWarning) + + +def test_every_construction_warns() -> None: + """Three filters built on one line give three warnings: the default filter, which + shows a warning once per line, does not hide the second.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + for threshold in (1.0, 2.0, 3.0): + _ = PolarsFilter( + predicates=[pl.col("rate") > threshold, pl.col("depth") < 100], + constraints={"session": "s1", "unit": 3}, + ) + assert len(_polars_filter_warnings(caught)) == 3 + + +def test_the_message_names_the_fault_and_the_operator_to_use() -> None: + with pytest.warns(PolarsFilterWarning) as caught: + _ = PolarsFilter(constraints={"session": "s1", "unit": 3}) + (warning,) = _polars_filter_warnings(list(caught)) + text = str(warning.message) + assert "PolarsFilter" in text + assert "date64" in text and "midnight" in text + assert "not recommended" in text + assert "Filter" in text.replace("PolarsFilter", "") + # Shown at the line that built it. + assert warning.filename == __file__ + + +def test_a_filter_with_no_argument_warns_too() -> None: + with pytest.warns(PolarsFilterWarning): + _ = PolarsFilter() + + +def test_the_stream_method_warns_at_every_call() -> None: + source = _source() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + for session in ("s1", "s2"): + _ = source.polars_filter(pl.col("rate") > 1.0, session=session, unit=3) + found = _polars_filter_warnings(caught) + assert len(found) == 2 + assert all(w.filename == __file__ for w in found) + + +def test_an_error_filter_refuses_the_construction() -> None: + with warnings.catch_warnings(): + warnings.simplefilter("error", PolarsFilterWarning) + with pytest.raises(PolarsFilterWarning): + _ = PolarsFilter(constraints={"session": "s1", "unit": 3}) + + +def test_an_ignore_filter_silences_it() -> None: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + warnings.simplefilter("ignore", PolarsFilterWarning) + _ = PolarsFilter(constraints={"session": "s1", "unit": 3}) + assert not _polars_filter_warnings(caught) + + +def test_the_provisional_warning_stays_once_per_process() -> None: + reset_provisional_use_warnings() + try: + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + _ = PolarsFilter(constraints={"session": "s1", "unit": 3}) + _ = PolarsFilter(constraints={"unit": 3, "session": "s1"}) + provisional = [ + w + for w in caught + if issubclass(w.category, ProvisionalHashWarning) + and "PolarsFilter" in str(w.message) + ] + assert len(provisional) == 1 + assert len(_polars_filter_warnings(caught)) == 2 + finally: + reset_provisional_use_warnings() + + +def test_filter_does_not_warn() -> None: + source = _source() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + _ = Filter(col("rate") > 1.0) + _ = source.filter(col("rate") > 1.0, col("depth") < 100, session="s1", unit=3) + assert not _polars_filter_warnings(caught) + + +def test_the_warning_changes_no_identity() -> None: + """Two filters of one predicate and constraints share an identity, warned or + silenced.""" + source = _source() + with warnings.catch_warnings(): + warnings.simplefilter("ignore", PolarsFilterWarning) + silenced = source.polars_filter(session="s1", unit=3) + with pytest.warns(PolarsFilterWarning): + warned = source.polars_filter(session="s1", unit=3) + assert warned.content_hash() == silenced.content_hash() + assert warned.pipeline_hash() == silenced.pipeline_hash() + + +# ── load routes ───────────────────────────────────────────────────────────── + + +def _count(caught: list[warnings.WarningMessage]) -> int: + return len(_polars_filter_warnings(caught)) + + +def test_from_config_warns_at_every_call() -> None: + with pytest.warns(PolarsFilterWarning): + config = PolarsFilter( + predicates=[pl.col("rate") > 1.0, pl.col("depth") < 100], + constraints={"session": "s1", "unit": 3}, + ).to_config() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + rebuilt = [PolarsFilter.from_config(config) for _ in range(2)] + assert all(isinstance(op, PolarsFilter) for op in rebuilt) + assert _count(caught) == 2 + + +def test_the_operator_resolver_warns_at_every_call() -> None: + with pytest.warns(PolarsFilterWarning): + config = PolarsFilter(constraints={"session": "s1", "unit": 3}).to_config() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + for _ in range(2): + _ = resolve_operator_from_config(config) + assert _count(caught) == 2 + + +def _saved_job(tmp_path: Path, *, rebuildable: bool) -> Path: + """Save a job holding two ``PolarsFilter`` nodes; return the saved file. + + With ``rebuildable`` their predicates are expressions, which a load rebuilds; + otherwise boolean masks, which no config holds: a load keeps such a node read-only. + """ + first: list[object] = ( + [pl.col("rate") > 1.0, pl.col("depth") < 100] + if rebuildable + else [[True, True, False]] + ) + second: list[object] = ( + [pl.col("depth") >= 10] if rebuildable else [[True, False, True]] + ) + job = PipelineJob(name="filtered", database=DeltaTableDatabase(tmp_path / "store")) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", PolarsFilterWarning) + with job: + _ = _source().polars_filter(*first, session="s1", label="first") + _ = _source().polars_filter(*second, unit=3, label="second") + path = tmp_path / "job.json" + job.save(path) + return path + + +@pytest.mark.parametrize("rebuildable", [True, False], ids=["rebuilt", "read_only"]) +def test_every_load_warns_once_per_polars_filter_node( + tmp_path: Path, rebuildable: bool +) -> None: + """A load warns for each saved ``PolarsFilter``, rebuilt or kept read-only, and the + next load warns again.""" + path = _saved_job(tmp_path, rebuildable=rebuildable) + for _ in range(2): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + loaded = PipelineJob.load( + path, database=DeltaTableDatabase(tmp_path / "store") + ) + assert _count(caught) == 2 + assert all(w.filename == __file__ for w in _polars_filter_warnings(caught)) + assert sorted(loaded.nodes) == ["first", "second", "units"] + + +def test_saving_and_running_do_not_warn(tmp_path: Path) -> None: + job = PipelineJob(name="filtered", database=DeltaTableDatabase(tmp_path / "store")) + with pytest.warns(PolarsFilterWarning): + with job: + _ = _source().polars_filter(pl.col("rate") > 1.0, unit=3, label="kept") + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("default") + _ = job.run() + job.save(tmp_path / "job.json") + assert _count(caught) == 0 + + +@pytest.mark.parametrize("rebuildable", [True, False], ids=["rebuilt", "read_only"]) +def test_an_error_filter_refuses_the_load(tmp_path: Path, rebuildable: bool) -> None: + path = _saved_job(tmp_path, rebuildable=rebuildable) + with warnings.catch_warnings(): + warnings.simplefilter("error", PolarsFilterWarning) + with pytest.raises(PolarsFilterWarning): + _ = PipelineJob.load(path, database=DeltaTableDatabase(tmp_path / "store")) diff --git a/tests/test_core/operators/test_provisional_operators.py b/tests/test_core/operators/test_provisional_operators.py index bdb62c23e..423a646df 100644 --- a/tests/test_core/operators/test_provisional_operators.py +++ b/tests/test_core/operators/test_provisional_operators.py @@ -24,6 +24,10 @@ from orcapod.sources import ArrowTableSource from orcapod.utils.provisional import recording_provisional_uses +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + @pytest.fixture(autouse=True) def fresh_process() -> Iterator[None]: diff --git a/tests/test_core/operators/test_record_batch_execution.py b/tests/test_core/operators/test_record_batch_execution.py index f6762c14d..d1987a112 100644 --- a/tests/test_core/operators/test_record_batch_execution.py +++ b/tests/test_core/operators/test_record_batch_execution.py @@ -20,6 +20,7 @@ import asyncio import itertools import math +import warnings from collections.abc import Callable, Sequence from typing import Any @@ -43,7 +44,7 @@ from orcapod.pipeline.job import PipelineJob from orcapod.system_constants import constants from tests.test_core.operators.test_rejoin import other_context # noqa: F401 # the fixture -from orcapod.errors import UpstreamFailedError +from orcapod.errors import PolarsFilterWarning, UpstreamFailedError from orcapod.protocols.core_protocols import StreamProtocol from tests.test_core.operators.test_async_sync_equivalence import ( AFTER_OPERATOR_CASES, @@ -56,6 +57,9 @@ pytestmark = [ pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning"), pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), ] ALL = {"system_tags": True, "source": True} @@ -276,11 +280,16 @@ def test_the_row_by_row_operators_are_exactly_these() -> None: assert declared == ROW_BY_ROW -@pytest.mark.parametrize( - "case", - [case for case in CASES if type(case.make_op()).__name__ in ROW_BY_ROW], - ids=lambda case: case.label, -) +def _row_by_row_cases() -> list[Case]: + """The cases of the row-by-row operators. Each case's operator is built here, when + the tests are collected, where no mark applies: the ``PolarsFilter`` case's warning + (ITL-1296, tested in test_polars_filter_warning.py) is ignored for this block.""" + with warnings.catch_warnings(): + warnings.simplefilter("ignore", PolarsFilterWarning) + return [case for case in CASES if type(case.make_op()).__name__ in ROW_BY_ROW] + + +@pytest.mark.parametrize("case", _row_by_row_cases(), ids=lambda case: case.label) def test_a_row_by_row_operator_sends_each_batch_as_it_arrives(case: Case) -> None: """One result per input record batch, sent before the next input is read. Each one-row input is sent and its result (the sync body over that row alone) is diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index c4bda4a42..44251bf5d 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -51,6 +51,9 @@ pytest.mark.filterwarnings( "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" ), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), ] ROWS = [ diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py index 76a2ad144..e5d324b2d 100644 --- a/tests/test_core/operators/test_semijoin_tag_keys.py +++ b/tests/test_core/operators/test_semijoin_tag_keys.py @@ -37,6 +37,10 @@ sync_rows, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + def left_source() -> ArrowTableSource: """Tag ``id`` 1..3, data ``y`` 1..3 and ``x``.""" diff --git a/tests/test_core/operators/test_several_items.py b/tests/test_core/operators/test_several_items.py index 381f29f7f..4ad1dd5eb 100644 --- a/tests/test_core/operators/test_several_items.py +++ b/tests/test_core/operators/test_several_items.py @@ -91,9 +91,14 @@ # Selecting or dropping the data role of a data-tag warns that the tag is materialized; # that warning is tested in the data-tag tests, not here. -pytestmark = pytest.mark.filterwarnings( - "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" -) +pytestmark = [ + pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" + ), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), +] @dataclass(frozen=True) diff --git a/tests/test_core/operators/test_streaming_rejoin.py b/tests/test_core/operators/test_streaming_rejoin.py index 2a41c4b1a..c517d3e50 100644 --- a/tests/test_core/operators/test_streaming_rejoin.py +++ b/tests/test_core/operators/test_streaming_rejoin.py @@ -53,6 +53,10 @@ assert_same_rows, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + @pytest.fixture(autouse=True) def _quiet_provisional() -> Any: diff --git a/tests/test_core/side_effect_pod/test_side_effect_stream_as_table.py b/tests/test_core/side_effect_pod/test_side_effect_stream_as_table.py index b7fc672e5..67b625c81 100644 --- a/tests/test_core/side_effect_pod/test_side_effect_stream_as_table.py +++ b/tests/test_core/side_effect_pod/test_side_effect_stream_as_table.py @@ -19,6 +19,10 @@ from orcapod.side_effects import SideEffectPod from orcapod.sources import DictSource +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + CONFIGS: list[tuple[str, dict[str, Any]]] = [ ("default", {}), ("meta", {"columns": {"meta": True}}), diff --git a/tests/test_core/streams/test_explain.py b/tests/test_core/streams/test_explain.py index eff5a1b50..54a8fd52a 100644 --- a/tests/test_core/streams/test_explain.py +++ b/tests/test_core/streams/test_explain.py @@ -56,6 +56,9 @@ pytest.mark.filterwarnings( "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" ), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), ] _PROJECT = "explain-sample" diff --git a/tests/test_core/streams/test_head_and_preview.py b/tests/test_core/streams/test_head_and_preview.py index 61bc088be..68e49fd28 100644 --- a/tests/test_core/streams/test_head_and_preview.py +++ b/tests/test_core/streams/test_head_and_preview.py @@ -34,6 +34,10 @@ from orcapod.side_effects import SideEffectPod from orcapod.types import ColumnConfig, Cursor, Schema +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ALL_COLUMNS = ColumnConfig( meta=True, context=True, source=True, system_tags=True, content_hash=True ) diff --git a/tests/test_core/streams/test_head_sorting.py b/tests/test_core/streams/test_head_sorting.py index 4ced8449d..6c242bef9 100644 --- a/tests/test_core/streams/test_head_sorting.py +++ b/tests/test_core/streams/test_head_sorting.py @@ -22,6 +22,10 @@ from orcapod.streams import ViewStatus from orcapod.types import ColumnConfig, Cursor, Schema +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ROWS = 8 # Not in tag order, with the tag order's first rows last. ORDER = [5, 2, 7, 0, 6, 1, 4, 3] diff --git a/tests/test_core/streams/test_pass_through_operator_staleness.py b/tests/test_core/streams/test_pass_through_operator_staleness.py index cc9779885..c9c9f441f 100644 --- a/tests/test_core/streams/test_pass_through_operator_staleness.py +++ b/tests/test_core/streams/test_pass_through_operator_staleness.py @@ -46,6 +46,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.streams import ViewStatus +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + IDS = [3, 1, 4, 0, 2] CALLS: Counter[str] = Counter() diff --git a/tests/test_core/streams/test_several_items_methods.py b/tests/test_core/streams/test_several_items_methods.py index 59f47edfe..d2a163bc5 100644 --- a/tests/test_core/streams/test_several_items_methods.py +++ b/tests/test_core/streams/test_several_items_methods.py @@ -55,9 +55,14 @@ presentation, ) -pytestmark = pytest.mark.filterwarnings( - "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" -) +pytestmark = [ + pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" + ), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), +] # The stream methods are on the stream classes, not on ``StreamProtocol``. Build = Callable[[ArrowTableSource, Sequence[Any]], StreamProtocol] diff --git a/tests/test_core/streams/test_stream_convenience_methods.py b/tests/test_core/streams/test_stream_convenience_methods.py index f61653fa3..c13c5ceec 100644 --- a/tests/test_core/streams/test_stream_convenience_methods.py +++ b/tests/test_core/streams/test_stream_convenience_methods.py @@ -12,6 +12,11 @@ from orcapod.core.operators import MapTags from orcapod.core.sources import ArrowTableSource from orcapod.core.streams import ArrowTableStream +import pytest + +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") # --------------------------------------------------------------------------- diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index 9cdabf77b..a202e7404 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -146,6 +146,9 @@ "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" ), pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), + # PolarsFilter is built here on purpose; the warning of every construction is tested in + # test_polars_filter_warning.py (ITL-1296). + pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning"), ] # (tag order index, layout): the three tag orders (declared, reversed, a rotation) with the diff --git a/tests/test_hashing/test_pydantic_dataclass_hashing.py b/tests/test_hashing/test_pydantic_dataclass_hashing.py index df2d235ff..0817bb05a 100644 --- a/tests/test_hashing/test_pydantic_dataclass_hashing.py +++ b/tests/test_hashing/test_pydantic_dataclass_hashing.py @@ -48,6 +48,10 @@ from orcapod.hashing.arrow_hashers import StarfixArrowHasher from orcapod.types import ContentHash +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + # --------------------------------------------------------------------------- # Shared fixtures diff --git a/tests/test_pipeline/test_node_head.py b/tests/test_pipeline/test_node_head.py index 13f182e19..c01215054 100644 --- a/tests/test_pipeline/test_node_head.py +++ b/tests/test_pipeline/test_node_head.py @@ -28,6 +28,10 @@ from orcapod.streams import ViewStatus from orcapod.types import CacheMode, Schema +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + CALLS: list[int] = [] ORCHESTRATORS = { diff --git a/tests/test_pipeline/test_operator_node_async_readback.py b/tests/test_pipeline/test_operator_node_async_readback.py index 345d738a6..d5d46d733 100644 --- a/tests/test_pipeline/test_operator_node_async_readback.py +++ b/tests/test_pipeline/test_operator_node_async_readback.py @@ -46,6 +46,10 @@ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.types import CacheMode +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ORCHESTRATORS = { "sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator, diff --git a/tests/test_pipeline/test_operator_node_empty_table_types.py b/tests/test_pipeline/test_operator_node_empty_table_types.py index 58bee37ab..ee30cd8ea 100644 --- a/tests/test_pipeline/test_operator_node_empty_table_types.py +++ b/tests/test_pipeline/test_operator_node_empty_table_types.py @@ -44,6 +44,10 @@ from orcapod.side_effects import SideEffectPod from orcapod.types import ColumnConfig +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ORCHESTRATORS = { "sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator, diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py index c9385598e..367ff8bb7 100644 --- a/tests/test_pipeline/test_rows_on_read.py +++ b/tests/test_pipeline/test_rows_on_read.py @@ -31,6 +31,10 @@ _with_source_x, # pyright: ignore[reportPrivateUsage] ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + _UNCONVERTIBLE = pa.large_list(_NESTED) diff --git a/tests/test_pipeline/test_stream_transport_equivalence.py b/tests/test_pipeline/test_stream_transport_equivalence.py index d19ae759c..a814bfbd4 100644 --- a/tests/test_pipeline/test_stream_transport_equivalence.py +++ b/tests/test_pipeline/test_stream_transport_equivalence.py @@ -55,6 +55,10 @@ make_source, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ALL_COLUMNS = { "meta": True, "source": True, diff --git a/tests/test_pipeline/test_zero_row_column_order.py b/tests/test_pipeline/test_zero_row_column_order.py index 30f793f73..98eb83831 100644 --- a/tests/test_pipeline/test_zero_row_column_order.py +++ b/tests/test_pipeline/test_zero_row_column_order.py @@ -58,6 +58,10 @@ from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.types import CacheMode +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + ORCHESTRATORS = { "sync": SyncPipelineOrchestrator, "async": AsyncPipelineOrchestrator, diff --git a/tests/test_pipeline/test_zero_row_non_large_inputs.py b/tests/test_pipeline/test_zero_row_non_large_inputs.py index f3fee0fbe..195376499 100644 --- a/tests/test_pipeline/test_zero_row_non_large_inputs.py +++ b/tests/test_pipeline/test_zero_row_non_large_inputs.py @@ -23,6 +23,10 @@ from orcapod.databases import InMemoryArrowDatabase from orcapod.pipeline.job import PipelineJob +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + NESTED = pa.struct([pa.field("a", pa.string()), pa.field("l", pa.list_(pa.string()))]) diff --git a/tests/test_torch/test_tensor_operators.py b/tests/test_torch/test_tensor_operators.py index 5b431fc1a..393081eae 100644 --- a/tests/test_torch/test_tensor_operators.py +++ b/tests/test_torch/test_tensor_operators.py @@ -35,6 +35,10 @@ assert_tensors_identical, ) +# PolarsFilter is built here on purpose; the warning of every construction is tested in +# test_polars_filter_warning.py (ITL-1296). +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.PolarsFilterWarning") + NAMES = sorted(TENSORS) GROUP = {name: f"g{i % 3}" for i, name in enumerate(NAMES)} From 9e33decb68bf55335f59e426ab7c446bf9c45555 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 22:05:50 -0800 Subject: [PATCH 2/2] test(filters): compare both halves of a data-tag on every path; correct the decimal256 text (ITL-1296) Review of PR 625. The channel comparison dropped the data half of a data-tag; rows are now compared as tag and data tables apart on every path, and tests that carry one column through Polars require every path's comparison to fail. The decimal fixtures fill their declared precision. A decimal256 column makes PolarsFilter raise pyo3's PanicException (a BaseException), not abort: the texts say so and a subprocess test pins it. Every user-doc mention of PolarsFilter says it is not recommended, checked by a docs test. Co-Authored-By: Claude Fable 5.2 --- README.md | 2 +- changelog.d/ITL-1296.md | 5 +- docs/concepts/identity.md | 5 +- docs/concepts/operators.md | 26 +- docs/concepts/sources.md | 2 +- docs/dev/design_issues/ITL-1296-PF2.md | 13 +- docs/reference/golden-hashes.md | 2 +- docs/reference/hashing.md | 13 +- docs/troubleshooting.md | 2 +- src/orcapod/errors.py | 5 +- .../operators/test_filter_exact_values.py | 272 ++++++++++++++---- .../operators/test_polars_filter_warning.py | 62 ++++ .../test_docs/test_polars_filter_mentions.py | 120 ++++++++ 13 files changed, 452 insertions(+), 77 deletions(-) create mode 100644 tests/test_docs/test_polars_filter_mentions.py diff --git a/README.md b/README.md index 261a80eae..8b5dd41b2 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ Orcapod is before version 1.0. In the development version (0.4.0 is next): stored results again, so a hash value released in 0.4.0 will not change in a later release of the same data context; CI checks this. Until 0.4.0 a v1 hash may still change, only by an approved and explained change (0.3.0, which first shipped v1, was withdrawn). This - does not cover a provisional operator (such as `PolarsFilter` and `Filter`): its identity, and every hash + does not cover a provisional operator (such as `Filter` and `GroupBy`): its identity, and every hash downstream of it, may still change in a later release of v1. See [Golden hashes](https://github.com/metamorphic-labs/orcapod-python/blob/main/docs/reference/golden-hashes.md) and diff --git a/changelog.d/ITL-1296.md b/changelog.d/ITL-1296.md index c1b399c57..7f5c0c366 100644 --- a/changelog.d/ITL-1296.md +++ b/changelog.d/ITL-1296.md @@ -16,5 +16,6 @@ ### Known limitations - `PolarsFilter` can change the values of the rows it keeps (a `date64` off midnight is - moved to midnight), and a `decimal256` column can make Polars abort the process - (ITL-1296). Use `Filter`. + moved to midnight), and a `decimal256` column in its input, read by a predicate or not, + makes Polars panic: the filter raises `pyo3_runtime.PanicException`, a `BaseException` + that `except Exception` does not catch (ITL-1296). Use `Filter`. diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index cedf58b29..05b463882 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -274,7 +274,7 @@ hashes: - the order of the names, mapping entries or keywords of an argument that names several: the columns of `select_columns`, `drop_columns`, `drop_nulls` and the other selections, the entries of `map_tags`, `map_data` and `map_columns`, the constraints of - `polars_filter`, the conditions and keywords of `filter` (and the operands of its `&` and + `polars_filter` (not recommended: see [PolarsFilter](operators.md#polarsfilter)), the conditions and keywords of `filter` (and the operands of its `&` and `|` and the values of its `is_in`), `tag_only_columns`, `tags_as_data`; - the order of the inputs of an operator that declares itself commutative (`Join`), and of the inputs of a function pod (for the ordered operators, see the table of orders that @@ -350,7 +350,8 @@ source and stream kind, the function pod forms and a job. Today these cases stil (the test marks each as an expected failure naming its issue); they are being fixed before data context v1 is frozen: -- the order of `polars_filter`'s predicates is in its identity (ITL-1247, undecided); +- the order of `polars_filter`'s predicates is in its identity (ITL-1247, undecided; + `polars_filter` is not recommended: see [PolarsFilter](operators.md#polarsfilter)); - a function pod over data-tags: its content and pipeline hash and its node's stored paths depend on the input's tag order and table layout (ITL-1246); - a stream built directly from a table (`ArrowTableStream`): its content hash depends on diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 4a1acf029..d17760bf9 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -39,8 +39,8 @@ An operator may add a tag, never data. A tag labels rows; it is not a data value [`AddTags`](#addtags) can add tags with constant values while every data column passes through unchanged. -The filters are the operators that read data columns: `Filter` and `PolarsFilter` evaluate -their conditions on values, and `DropNulls` reads only whether a value is present (its +The filters are the operators that read data columns: `Filter` evaluates its condition on +values (as does `PolarsFilter`, which is not recommended: see [PolarsFilter](#polarsfilter)), and `DropNulls` reads only whether a value is present (its validity), never the value. They decide which rows exist; none synthesizes a value. No operator carries its inputs' meta columns: the `__`-prefixed columns, such as a cached @@ -249,7 +249,8 @@ The rules: result's table. A stream reports one data context, and so do the rows it yields one by one (`iter_data`), as for any stream whose table holds rows of several (ITL-1359). Only the default data context ships, so this matters only for a stream built in another one. A known limitation - (ITL-1339): some operators (`PolarsFilter` and `MergeJoin`, likely `Join` and + (ITL-1339): some operators (`MergeJoin` and `PolarsFilter`, which is not recommended + for another reason, see [PolarsFilter](#polarsfilter); likely `Join` and `SemiJoin` too) return their rows in the default data context whatever their input's, so in another data context the rows of a branch through one of them match nothing beside a branch that kept its context. @@ -900,7 +901,8 @@ print(recorded.filter(col("t") >= 1.0, label="late").drop_nulls(["rate"]).explai Every source gets one block, in source-name order, and the steps are listed from the source upward. A join's unmatched rows are listed too (`rows without a match in 'probes' are -dropped (Join)`), as are `SemiJoin`, `MergeJoin`, `Rejoin`, `DropNulls`, `PolarsFilter`, +dropped (Join)`), as are `SemiJoin`, `MergeJoin`, `Rejoin`, `DropNulls`, +`PolarsFilter` (not recommended: see [PolarsFilter](#polarsfilter)), `Batch(drop_partial_batch=True)` and `Pick` or `Index` when a miss drops the row. A derived or cached source cannot say what it reads (it reads rows stored earlier): its block says "not known for this source kind". The result is an `Explanation` (`orcapod.types`), plain data @@ -918,7 +920,10 @@ takes such an expression directly, but it is not recommended: see the warning in `PolarsFilter` passes every column of its input through Polars, also the columns its predicates do not read, and Polars does not hold every Arrow type exactly. The known case: a `date64` value that is not at midnight comes back at midnight, with no error - (ITL-1296, not fixed). Use [`Filter`](#filter), which passes every value through as it + (ITL-1296, not fixed). A `decimal256` column, read by a predicate or not, makes Polars + panic: the filter raises `pyo3_runtime.PanicException`, which is a `BaseException` and not + an `Exception`, so `except Exception` does not catch it (`except BaseException` does), + and no row is returned. Use [`Filter`](#filter), which passes every value through as it is. Building a `PolarsFilter` (the class, or `stream.polars_filter(...)`) issues `PolarsFilterWarning` (`orcapod.errors`) every time, and loading a saved job issues it once for each `PolarsFilter` the job holds. The samples below issue it when they run. @@ -1219,7 +1224,7 @@ November 19, 2026). Each name maps to the issue that decides its identity or out | `MapTags` | its rename rules for data-tags (ITL-1018) | | `MapColumns` | its behaviour with data-tags (ITL-1022) | | `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) | +| `PolarsFilter` (not recommended: see [PolarsFilter](#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; its spelling and literal rule await the developer's decision (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) | @@ -1231,7 +1236,10 @@ column selections (`SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, What you get with a provisional operator: the same results as with any other operator, a warning, and, should a later release change the operator's identity, a recomputation of its steps (and of every step downstream) instead of reuse; nothing stored is lost or wrong. -Building one, directly, through a stream method such as `group_by` or `polars_filter`, or by +One provisional operator has a fault of its own, apart from being provisional: +`PolarsFilter` is not recommended, because it can change the values it passes through (see +[PolarsFilter](#polarsfilter)). +Building one, directly, through a stream method such as `group_by` or `filter`, or by loading a saved job that holds one, issues `orcapod.errors.ProvisionalHashWarning` once per operator per process. It reads, for example, `GroupBy is provisional: its identity is not frozen with data context v1 and may change in a later release. ...` and points to this @@ -1343,7 +1351,9 @@ operators or function pods. Every stream also exposes the operators as methods, which reads well when chaining: `join`, `semi_join`, `batch`, `group_by`, `select_tag_columns`, `select_data_columns`, `drop_tag_columns`, `drop_data_columns`, `select_columns`, `drop_columns`, `map_tags`, -`map_data`, `map_columns`, `add_tags`, `filter`, `polars_filter`, `drop_nulls`, `pick` and `index`. +`map_data`, `map_columns`, `add_tags`, `filter`, `drop_nulls`, `pick` and `index`. There is a `polars_filter` +method too; it is not recommended, because it can change the values it passes through, and it +warns at every call: see [PolarsFilter](#polarsfilter). ```python adults = subjects.join(measurements).filter(col("age") > 10) diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index f1ee8c291..4043c7ffe 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -485,7 +485,7 @@ applied the same condition. `where` refuses float ranges for now (ITL-1477). A restriction is not an operator: -- An operator (`Filter`, `SemiJoin`, `PolarsFilter`) is a step of the pipeline. It is a node of the +- An operator (`Filter`, `SemiJoin`) is a step of the pipeline. It is a node of the graph and part of the pipeline's identity: a pipeline with a filter computes something else than one without, and its nodes have other hashes and other stored tables. - A restriction is attached to the source. It chooses which of the source's rows flow and diff --git a/docs/dev/design_issues/ITL-1296-PF2.md b/docs/dev/design_issues/ITL-1296-PF2.md index 43ae6da57..032294797 100644 --- a/docs/dev/design_issues/ITL-1296-PF2.md +++ b/docs/dev/design_issues/ITL-1296-PF2.md @@ -9,8 +9,12 @@ and converts the result back to Arrow, then casts it to the input types. Every column goes through Polars, also the columns the predicates never read, and Polars does not hold every Arrow type exactly: a `date64` data column `[1, 86400001]` ms comes back `[0, 86400000]` ms, -with no error, and a `decimal256` column is reported to make Polars panic, which no caller -can catch. A filter must pass the rows it keeps unchanged. +with no error. A `decimal256` column, read by a predicate or not, makes Polars panic +("operator does not support primitive `Int256`"): the filter raises +`pyo3_runtime.PanicException`, a `BaseException` that is not an `Exception`, so +`except Exception` does not catch it and `except BaseException` does; the process goes on +and no row is returned (measured in a subprocess, +`test_polars_filter_warning.py::test_a_decimal256_column_raises_a_panic_exception`). A filter must pass the rows it keeps unchanged. **Deferred (developer, November 28, 2026):** "defer using polars filter and entirely focus on filter for the users. For now I'd be even fine for PolarFilter to always throw a warning when @@ -39,7 +43,10 @@ instantiated." The value fault is not fixed. Instead: `time64[ns]` below a microsecond, a float32 signaling NaN, `-0.0`, `decimal128` and `decimal256` at full precision, logical types, strings and binaries of both widths, lists and structs, each as tag, data and data-tag, in two table arrangements, on the sync path, - the row channel path and in a job run by either orchestrator. + the row channel path and in a job run by either orchestrator; the rows handed out one by + one are compared with the tag half and the data half apart (both halves of a data-tag), + and the file's last tests carry one column through Polars and require every path's + comparison to fail. Still open: `PolarsFilter` itself (Polars decides which rows are kept, the rows are taken from the Arrow table), or its removal. diff --git a/docs/reference/golden-hashes.md b/docs/reference/golden-hashes.md index 25a827fa7..8e26952ee 100644 --- a/docs/reference/golden-hashes.md +++ b/docs/reference/golden-hashes.md @@ -205,7 +205,7 @@ rewrites it in place. (`cases.DECLARABLE_PROVISIONAL_SOURCES`). - **Today:** 1218 entries: `pipeline` 1018, `semantic` 58, `datagram` 50, `schema` 40, `torch` 32 and `arrow` 20 (the keys of `data/v1/provisional/*.json`). 475 of them moved out - of the frozen files, values unchanged, before `v1` was frozen: the `PolarsFilter` cases + of the frozen files, values unchanged, before `v1` was frozen: the cases of `PolarsFilter` (an operator that is not recommended) (`polars_filter`, `polars_filter_expr`, `polars_filter_expr_job` and the `semantic` case `polars_expr`, 86 entries) with ITL-1266; the cases of the other provisional operators (229 entries) and of the library value types (128 entries, with the 12 of `GoldenWithArray`) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index e139f34ce..4c9a4af72 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -6,7 +6,7 @@ orcapod-python framework. For conceptual background on the two identity chains Every hash listed here that Orcapod stores or embeds in a name is pinned as a golden value; how released values are protected is described in [Golden Hashes](golden-hashes.md). A release freezes every golden value except those of the provisional operators -(`orcapod.operators.PROVISIONAL_OPERATORS`, such as `PolarsFilter` and `Filter`) and of every step downstream +(`orcapod.operators.PROVISIONAL_OPERATORS`, such as `Filter` and `GroupBy`) and of every step downstream of one: their identity may still change in a later release (see [Provisional operators](../concepts/operators.md#provisional-operators)). @@ -323,7 +323,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | tensor value hash | element digest, flags, strides, class | SHA-256, `torch_tensor_v1` | `torch.Tensor` value hash | `logical_types/torch_type.py:tensor_digest` | | pandas value hash | descriptor, `\0`, `b"arrow_ordered_v1:" + D` | SHA-256, `pandas_dataframe_v1` / `pandas_series_v1` | pandas value hash | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash`, `hashing/labelled_hash.py:labelled_content_hash`, `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` | | Polars value hash | descriptor, `\0`, starfix digest called directly (a step of this algorithm) | SHA-256, `polars_dataframe_v1` / `polars_series_v1` | Polars value hash | `logical_types/polars_type.py:_digest`, `logical_types/polars_type.py:_values_digest` | -| Polars expression hash | the expression's canonical tree | SHA-256 of canonical JSON, `polars_expr_v1` | `PolarsFilter` identity | `hashing/semantic_hashing/polars_expr.py:polars_expr_content_hash` | +| Polars expression hash | the expression's canonical tree | SHA-256 of canonical JSON, `polars_expr_v1` | `PolarsFilter` identity (an operator that is not recommended) | `hashing/semantic_hashing/polars_expr.py:polars_expr_content_hash` | | value handlers with an ignore list | wrap the value digests above | the type's label | top level, nested, Arrow cell | `logical_types/ignore_list.py:IgnoreListHandler.handle`, `logical_types/ignore_list.py:IgnoreListHandler.hash_ignoring` | | parse a stored hash | `"