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/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 new file mode 100644 index 000000000..7f5c0c366 --- /dev/null +++ b/changelog.d/ITL-1296.md @@ -0,0 +1,21 @@ +### 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 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/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/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 58beec3fa..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,50 +901,52 @@ 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 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). 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. + !!! 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 +988,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 @@ -1221,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) | @@ -1233,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 @@ -1345,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 589c57427..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 @@ -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..032294797 --- /dev/null +++ b/docs/dev/design_issues/ITL-1296-PF2.md @@ -0,0 +1,52 @@ +## `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. 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 +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; 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 | `"