diff --git a/README.md b/README.md index c400a50d2..8cf325ff0 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,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 (today `PolarsFilter`): its identity, and every hash + does not cover a provisional operator (such as `PolarsFilter` and `Filter`): 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-1402.md b/changelog.d/ITL-1402.md new file mode 100644 index 000000000..56460bbb5 --- /dev/null +++ b/changelog.d/ITL-1402.md @@ -0,0 +1,11 @@ +### Added + +- `stream.explain()` says, for every source a stream reads, what the source applies itself + (its `where` restriction and limit) and which steps drop rows after the rows are read + (ITL-1402): a `filter` over an unrestricted table is shown to read the whole table. It + computes, reads, polls and writes nothing and runs no user code. It returns an + `Explanation` (`orcapod.types`), plain data whose `text()` lists one block per source; + sources, conditions and argument items appear in no given order. Joins' unmatched rows, + `SemiJoin`, `DropNulls`, `PolarsFilter`, a `Batch` dropping its last partial batch and a + `Pick` or `Index` dropping a miss are listed too. The preview of a `filter` directly over + a source shows the same split in one line. diff --git a/docs/api/index.md b/docs/api/index.md index 849c8de10..4cd9f9556 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -25,4 +25,4 @@ Everything else lives in subpackages: | [`orcapod.databases`](databases.md) | Persistent storage backends for computation results | | [`orcapod.nodes`](nodes.md) | Pipeline graph elements, including the DB-backed job nodes | | [`orcapod.streams`](streams.md) | Immutable (Tag, Data) sequences backed by PyArrow tables | -| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash`, `Condition` | +| [`orcapod.types`](types.md) | Core type definitions: `Schema`, `ColumnConfig`, `ContentHash`, `Condition`, `col`, `Explanation` | diff --git a/docs/api/operators.md b/docs/api/operators.md index 17fa2d54f..8da38f324 100644 --- a/docs/api/operators.md +++ b/docs/api/operators.md @@ -40,6 +40,8 @@ Operators perform structural transformations on streams without inspecting or sy ::: orcapod.core.operators.AddTags +::: orcapod.core.operators.Filter + ::: orcapod.core.operators.PolarsFilter ::: orcapod.core.operators.Pick diff --git a/docs/api/types.md b/docs/api/types.md index aea93282d..aef3f1e7a 100644 --- a/docs/api/types.md +++ b/docs/api/types.md @@ -15,3 +15,13 @@ Core type definitions used throughout Orcapod. ::: orcapod.types.ContentHash ::: orcapod.types.Condition + +::: orcapod.types.col + +::: orcapod.types.ColumnRef + +::: orcapod.types.Explanation + +::: orcapod.types.SourceReading + +::: orcapod.types.Step diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md index 3d1997b99..cedf58b29 100644 --- a/docs/concepts/identity.md +++ b/docs/concepts/identity.md @@ -274,7 +274,8 @@ 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`, `tag_only_columns`, `tags_as_data`; + `polars_filter`, 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 count below); diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index d1b407571..4e4dec18a 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -39,9 +39,9 @@ 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: `PolarsFilter` evaluates its predicate -on values, and `DropNulls` reads only whether a value is present (its validity), never the -value. Both decide which rows exist; neither synthesizes a value. +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 +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 function pod's `__computed`, that describe how an input row was produced. An operator's @@ -160,7 +160,9 @@ units = DictSource( ) # Two branches of one stream: a filter in one, a rename in the other. -fast = units.select_data_columns(["rate"]).polars_filter(pl.col("rate") > 3) +from orcapod import col + +fast = units.select_data_columns(["rate"]).filter(col("rate") > 3.0) deep = units.select_data_columns(["depth"]).map_data({"depth": "depth_um"}) rejoined = fast.rejoin(deep) @@ -701,6 +703,194 @@ except InputValidationError as error: A new name already taken by a column that is not renamed is refused too. +### Filter + +!!! warning "Provisional" + `Filter` is a [provisional operator](#provisional-operators): its identity is not frozen + with data context v1 and may change in a later release (ITL-1374). Building one issues + `ProvisionalHashWarning` once per process. + +`stream.filter(...)` (the operator `Filter`) keeps the rows that satisfy a condition. Every +column, value and type passes through unchanged; only rows are dropped, in input order. +Keywords and mappings are equalities, as a source's `where` takes them; every other +condition is built from `col(name)`: + +```python +import pyarrow as pa +from orcapod import col +from orcapod.sources import ArrowTableSource + +recorded = ArrowTableSource( + pa.table( + { + "session": ["s1", "s1", "s1", "s2", "s2", "s3"], + "unit": [3, 7, 9, 3, 7, 3], + "t": [0.5, 1.2, 2.0, 0.7, float("nan"), 3.1], + "rate": [4.0, None, 2.5, 6.1, 0.0, None], + "probe": ["imec0", "imec1", "imec0", "imec1", "imec0", "imec1"], + } + ), + tag_columns=["session", "unit"], + tag_only_columns=True, + source_id="recorded", +) + + +def kept(stream): + """The (session, unit) pairs a stream holds, sorted.""" + return sorted((row["session"], row["unit"]) for row in stream.as_table().to_pylist()) + + +print(kept(recorded.filter(session="s1", probe="imec0"))) +# [('s1', 3), ('s1', 9)] +print(kept(recorded.filter({"session": "s1", "probe": "imec0"}))) +# [('s1', 3), ('s1', 9)] +print(kept(recorded.filter(col("unit").is_in([3, 7]), col("t") < 1.0))) +# [('s1', 3), ('s2', 3)] +print(kept(recorded.filter(col("t").between(0.5, 2.0)))) +# [('s1', 3), ('s1', 7), ('s1', 9), ('s2', 3)] +print(kept(recorded.filter(col("rate").is_null()))) +# [('s1', 7), ('s3', 3)] +print(kept(recorded.filter((col("session") == "s3") | (col("t") < 0.6)))) +# [('s1', 3), ('s3', 3)] +print(kept(recorded.filter(~col("unit").is_in([3, 7])))) +# [('s1', 9)] +``` + +The conditions are: + +| Condition | Written | Column types | +|---|---|---| +| equality | `column=value`, `{column: value}`, `col(c) == v`, `col(c) != v` | bool, integers, floats, strings, binary, dates, timestamps | +| membership | `col(c).is_in([v1, v2, ...])` | the same | +| comparison | `col(c) < v`, `<=`, `>`, `>=` | integers, floats, strings, binary, dates, timestamps | +| range | `col(c).between(low, high)`, both ends included | the same | +| null test | `col(c).is_null()`, `col(c).is_not_null()` | every type | +| struct field | `col(c).field("f")`, then any condition above | a struct column | +| two columns | `col(a) < col(b)` and the other comparisons | two columns of one Arrow type | +| combined | several arguments and keywords (all hold), `a & b`, `a \| b`, `~a` | | + +Write `&`, `|` and `~`, never `and`, `or` and `not`, and put each comparison in parentheses +when you combine it, as in Polars. Python cannot refuse `and` between two conditions: +`(col("t") > 1.0) and (col("t") < 2.0)` silently keeps only the second. A list given as a keyword value is +refused: membership is `col(c).is_in([...])`. + +A condition that no row can satisfy is kept as written and keeps zero rows: Orcapod does not +try to tell a contradiction (there is no general way). Naming one column twice in one call +with two values is refused, as an argument error: + +```python +print(recorded.filter((col("session") == "s1") & (col("session") == "s2")).as_table().num_rows) +# 0 +try: + recorded.filter({"session": "s1"}, session="s2") +except ValueError as error: + print(error) +# column 'session' is named twice in one call, as 's1' in the mapping and as 's2' as a keyword; give it once +``` + +A tag column and a data column are filtered alike. A value must be exactly of its column's +Python type, and fit its Arrow type: `7` is accepted for a `uint32` column, `-1` is not, and +`1` is refused for a float column (write `1.0`). Orcapod converts no value: + +```python +from orcapod.errors import InputValidationError + +try: + recorded.filter(col("t") > 1).as_table() +except InputValidationError as error: + print(error) +# Filter: column 't' holds float, but the value 1 is a int; convert it explicitly: Orcapod converts no value +``` + +**Nulls.** A comparison with a null is unknown, and a row whose condition is unknown is +dropped, as in SQL and Polars. So `col("rate") != 4.0` and `~(col("rate") > 1.0)` both drop +the rows where `rate` is null; to keep them, say so: + +```python +print(kept(recorded.filter(col("rate") != 4.0))) +# [('s1', 9), ('s2', 3), ('s2', 7)] +print(kept(recorded.filter((col("rate") != 4.0) | col("rate").is_null()))) +# [('s1', 7), ('s1', 9), ('s2', 3), ('s2', 7), ('s3', 3)] +``` + +`filter` does not narrow a column's type: after `col("rate").is_not_null()` the column is +still `float | None`. Use [DropNulls](#dropnulls) when a function needs a plain `float`. + +**Floats.** Floats match as Orcapod matches them everywhere: `0.0` equals `-0.0`, a NaN equals +a NaN, and a NaN is greater than every number. So `col("t") >= 1.0` keeps the NaN row: + +```python +print(kept(recorded.filter(col("t") >= 1.0))) +# [('s1', 7), ('s1', 9), ('s2', 7), ('s3', 3)] +``` + +**A field of a struct column.** `col("info").field("kind")` reads the field `kind` of the +struct column `info` (a struct inside a struct too: `.field("a").field("b")`). A null struct +makes its fields null. An unknown field is refused with a message listing the fields the +column has. + +**Identity.** The filter's identity is its condition in a canonical form: the order of the +arguments, of the keywords, of `&` and `|` operands and of the `is_in` values never counts, +and values keep their types (`1`, `1.0` and `True` are three conditions): + +```python +first = recorded.filter(col("unit").is_in([3, 7]), session="s1") +second = recorded.filter({"session": "s1"}, col("unit").is_in([7, 3])) +print(first.pipeline_hash() == second.pipeline_hash()) +# True +``` + +The conditions are checked when the filter is built and when it meets its input, so a filter +that works on a stream works the same inside a `PipelineJob`. + +`head()` of a filter shows, without computing anything, the rows of its input's own `head()` +that match: it may show fewer rows than asked, or none, and says which rows it looked at. +Over a step that has not run (a function pod, for example) it reads not computed, as any +`head()` does: + +```python +# The input's first 3 rows hold t = 0.5, 1.2 and 2.0: two match. +print(recorded.filter(col("t") >= 1.0).head(3).as_table().num_rows) +# 2 +``` + +**`where` and `filter`.** A source that can restrict what it reads (`where`, see +[Restricting a source](sources.md#restricting-a-source-versus-filtering-in-the-pipeline)) takes the same equalities. The two give the +same rows, except on a float column for a NaN or a signed zero (`where` uses the table +system's equality, `filter` Orcapod's: a NaN may match no row under `where` and matches the +NaN rows under `filter`) and on a source with a `limit` (the limit then counts the matching +rows). `where` is not a step of the pipeline: it changes no hash, while `filter` is a +node whose condition enters the identity of every step after it. Explore with `where`; keep +the selection with `filter` when it becomes part of what the pipeline computes. `where` +takes only equalities today and refuses any other condition, pointing to `filter`. + +**What is read, and what is applied after reading.** `stream.explain()` (new in this +release) says, for every source a stream reads, what the source applies itself (its `where` +restriction and limit) and which steps drop rows after the rows are read. A `filter` over an +unrestricted table reads the whole table, and `explain()` says so. It computes, reads, +polls and writes nothing, and runs no code of yours: + +```python +print(recorded.filter(col("t") >= 1.0, label="late").drop_nulls(["rate"]).explain()) +# DynamicPodStream[DropNulls] reads: +# source 'recorded' (ArrowTableSource) +# applied by the source: nothing (the whole table is read) +# applied after reading: t >= 1.0 (Filter[late]); no null in rate (DropNulls) +``` + +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`, +`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 +[PolarsFilter](#polarsfilter). + ### PolarsFilter !!! warning "Provisional" @@ -776,7 +966,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 `PolarsFilter` can drop the null rows but leaves the type as it was. +column, and `Filter` or `PolarsFilter` can drop the null rows but leave the type as it was. ```python import pyarrow as pa @@ -1014,7 +1204,7 @@ November 19, 2026). Each name maps to the issue that decides its identity or out | `Pick`, `Index` | the policy for a miss, which changes the output (ITL-439) | | `PolarsFilter` | whether the order of its predicates belongs to its identity (ITL-1247) | | `TagBy`, `AddTags` | days old, their identities just changed: the review of the tag operators (ITL-1290) | -| `Filter` | new: a row filter over a condition, provisional until its first use has shown what the canonical form of a condition must hold (ITL-1374) | +| `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) | Every other operator is frozen with data context v1: `Join`, `SemiJoin`, `MapData`, the @@ -1136,12 +1326,10 @@ 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`, `polars_filter`, `drop_nulls`, `pick` and `index`. +`map_data`, `map_columns`, `add_tags`, `filter`, `polars_filter`, `drop_nulls`, `pick` and `index`. ```python -import polars as pl - -adults = subjects.join(measurements).polars_filter(pl.col("age") > 10) +adults = subjects.join(measurements).filter(col("age") > 10) for tag, data in adults: print(tag.as_dict(), "->", data.as_dict()) # {'subject_id': 'mouse_01'} -> {'weight': 25.3, 'age': 12} diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 186185fba..d542c963f 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -404,7 +404,7 @@ restriction through two read-only properties: `condition` (the empty `Condition` reads every row) and `row_limit` (`None` without a limit). A restriction is not an operator: -- An operator (`SemiJoin`, `PolarsFilter`) is a step of the pipeline. It is a node of the +- An operator (`Filter`, `SemiJoin`, `PolarsFilter`) 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 @@ -422,6 +422,43 @@ identities and reused by the full run. Use an operator when selecting rows is pa the pipeline computes. Restrict on tag (key) columns where you can; a condition on a data column is allowed. +`where` and `stream.filter` take the same equalities, written the same way, and keep the same +rows (for a float column, `where` uses the table system's own equality for NaN and `-0.0`, +`filter` Orcapod's: see [Filter](operators.md#filter)). One spelling differs: `filter` takes +`label=` (the step's label, as every stream method does), so a column named `label` is written +`filter({"label": "x"})` or `filter(col("label") == "x")`, while `where(label="x")` restricts +that column. Neither takes `None` as a value: both raise `ValueError` and point to +`col(c).is_null()`, a null test that only `filter` takes. The difference is where the +selection lives: + + +```python +from orcapod import col + +# Exploring: the source reads only these rows; no step is added and no hash moves. +explore = events.where(unit_id=106, session_index=2) + +# The pipeline: the same selection as a step, part of every downstream identity. +kept = events.filter(unit_id=106, session_index=2) + +# Anything but equality is a filter; where refuses it and points to filter. +late = events.filter(col("spike_time_us") >= 1_000_000, col("unit_id").is_in([106, 107])) +``` + +A filter directly over a source reads every row the source reads (the whole table, or what +the source's own `where` and `limit` select) and then filters them; its condition is never +pushed into the source. `where` reads only the matching rows. On a large table, keep `where` on the source for speed and put the same +`filter` in the pipeline for its identity: the rows are the same, and the restriction rules +above apply to the source. This holds for equalities on integer, string, bytes, bool, date and +timestamp columns, on a source without a `limit`. With a `limit` it does not: the source +reads the first rows that match the `where`, so the `filter` sees other rows than it would +over the source alone (with `limit=2` and unit ids `[1, 2, 2]`, `filter(unit_id=2)` alone +keeps one row, the `where` and the `filter` together keep two). On a float column it does +not either when the value is a NaN or a signed zero: +`where` matches by the table system's equality (a NaN may match no row), `filter` by +Orcapod's (a NaN matches the NaN rows), so `where` can drop rows the `filter` alone would +keep. For such a value, filter without the `where`. + ```python events = SpiralDBTableSource("my-project-123456", "spike_event", source_id="spikes") diff --git a/docs/reference/golden-hashes.md b/docs/reference/golden-hashes.md index d09a14ee2..25a827fa7 100644 --- a/docs/reference/golden-hashes.md +++ b/docs/reference/golden-hashes.md @@ -203,11 +203,17 @@ rewrites it in place. removed rather than kept provisional, and the tool refuses a case that builds one, declared or not. Of the provisional sources only `DerivedSource` is declarable (`cases.DECLARABLE_PROVISIONAL_SOURCES`). -- **Today:** 475 entries. The `PolarsFilter` cases (`polars_filter`, `polars_filter_expr`, - `polars_filter_expr_job` and the `semantic` case `polars_expr`, 86 entries) moved out of - the frozen files 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`) moved with - ITL-1279 and ITL-1324, and those of `DerivedSource` (32 entries) with ITL-1331. Every move was values unchanged, before `v1` was frozen. +- **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 + (`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`) + with ITL-1279 and ITL-1324, and those of `DerivedSource` (32 entries) with ITL-1331. The + rest were added as provisional from the start, among them the `Rejoin` cases (`rejoin`, + `rejoin_arrangement`, `rejoin_job`, `rejoin_job_async`: 638 entries, ITL-1336 and ITL-1355) + and the `Filter` cases (`pipeline:filter`, `pipeline:filter_job` and + `semantic:filter_condition`: 93 entries, ITL-1382). - **What holds.** Every provisional value is computed and compared on every CI run, so a change nobody intended fails. An intended change needs the developer's approval of the exact list of entries that move, each explained (`--remove`, then `--add`), but no new diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ce12e65d7..2bc0669fe 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`, today `PolarsFilter`) and of every step downstream +(`orcapod.operators.PROVISIONAL_OPERATORS`, such as `PolarsFilter` and `Filter`) and of every step downstream of one: their identity may still change in a later release (see [Provisional operators](../concepts/operators.md#provisional-operators)). diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md index 6579a12e6..9c2cc0051 100644 --- a/docs/troubleshooting.md +++ b/docs/troubleshooting.md @@ -144,9 +144,10 @@ are *list-valued tag columns*, the stream came from `batch`; group before batchi `map_batches`) or uses another expression Orcapod cannot identify. The message lists what it can. Ordinary comparisons such as `pl.col("x") > 1` work everywhere. -**Fix.** Use keyword constraints (`polars_filter(column=value)`) for equality filters, or -compute a boolean column in a function pod and filter on it. See -[PolarsFilter](concepts/operators.md#polarsfilter). +**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). ### `AttributeError: 'PipelineJob' has no attribute 'show_graph'. Available node labels: [...]` diff --git a/docs/tutorial/03-operators.md b/docs/tutorial/03-operators.md index 28237a632..3c843a5df 100644 --- a/docs/tutorial/03-operators.md +++ b/docs/tutorial/03-operators.md @@ -9,7 +9,7 @@ functions. You will: - combine tables with `join` -- keep a subset of rows with `polars_filter` and `semi_join` +- keep a subset of rows with `filter` and `semi_join` - rename columns with `map_data` - see what to do when two tables have a column of the same name @@ -35,7 +35,7 @@ units = CSVSource( ``` Most operators are available as methods on a stream, and that is the form used here. All of -them exist as classes in `orcapod.operators` (`Join`, `PolarsFilter`, ...); see +them exist as classes in `orcapod.operators` (`Join`, `Filter`, ...); see [Operators](../concepts/operators.md). `MergeJoin`, at the end of this page, is used as a class. @@ -87,55 +87,104 @@ print(everything.as_table().num_rows) ## Filter: keep some rows -`polars_filter` keeps the rows that pass a test. The simplest form is equality on one or more +`filter` keeps the rows that satisfy a condition. The simplest form is equality on one or more columns, written as keyword arguments: ```python -knockouts = subjects.polars_filter(genotype="knockout") +knockouts = subjects.filter(genotype="knockout") print(knockouts.as_pandas_df()) # subject_id sex age_weeks genotype # 0 mouse_03 F 11 knockout # 1 mouse_04 M 13 knockout ``` -A filter may test tag columns and data columns alike. Join first, and you can filter on -columns from either table: +A filter tests tag columns and data columns alike. Join first, and you can filter on +columns from either table. Several keywords must all hold: ```python -knockout_units = units.join(subjects).polars_filter(genotype="knockout", probe="imec1") +knockout_units = units.join(subjects).filter(genotype="knockout", probe="imec1") print(knockout_units.as_table().num_rows) # 16 ``` -For anything other than equality, pass a [Polars](https://docs.pola.rs/) expression: +For anything other than equality, name the column with `col` and compare it: ```python -import polars as pl +from orcapod import col -busy = units.polars_filter(pl.col("n_spikes") > 1200) -print(busy.as_pandas_df()) +busy = units.filter(col("n_spikes") > 1200) +print(busy.as_pandas_df().sort_values(unit_tags, ignore_index=True)) # subject_id session probe unit region depth_um n_spikes # 0 mouse_01 s2 imec0 2 V1 920 1221 # 1 mouse_01 s2 imec1 2 CA1 120 1205 # 2 mouse_02 s2 imec1 3 CA1 2360 1233 ``` -The expression becomes part of the filtered stream's identity, so an expression filter can -be used anywhere an equality filter can: in a join, before a function pod, or inside a -`PipelineJob` (Part 5). +`col` offers the comparisons (`==`, `!=`, `<`, `<=`, `>`, `>=`), `is_in` for a set of +values, `between` for a range (both ends included), and `is_null` / `is_not_null`. Give +`filter` several conditions and keywords at once, and every one must hold; combine them with +`|` (or) and `~` (not): + +```python +shallow_s1 = units.filter( + col("probe").is_in(["imec0", "imec1"]), + col("depth_um").between(100, 500), + session="s1", +) +print(shallow_s1.as_table().num_rows) +# 4 +v1_or_busy = units.filter((col("region") == "V1") | (col("n_spikes") > 1200)) +print(v1_or_busy.as_table().num_rows) +# 34 +``` + +The order of the conditions, of the keywords and of the `is_in` values never matters. Write +`&` and `|` between two conditions and `~` before one (`~(col("probe") == "imec0")`), never +`and`, `or` and `not`, and put each comparison in parentheses, as in Polars. + +A value must have its column's type: `n_spikes` holds integers, so `col("n_spikes") > 1200.0` +is refused (`InputValidationError`), and `col("n_spikes") > 1200` is the way to write it. +Orcapod converts no value. + +The filter is a step of the pipeline: its conditions are part of the filtered stream's +identity, so a filtered stream can be used anywhere any other stream can: in a join, before +a function pod, or inside a `PipelineJob` (Part 5). ```python print(busy.join(subjects).as_table().num_rows) # 3 ``` +`filter` reads every row of its input and then keeps the matching ones. `explain()` (new in +this release) shows what each source applies itself and what is applied after reading; it +computes nothing: + +```python +print(busy.explain()) +# DynamicPodStream[Filter] reads: +# source 'units' (CSVSource) +# applied by the source: nothing (the whole table is read) +# 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 +``` + Orcapod has to be able to hash the expression, and it knows the common building blocks: comparisons, arithmetic, `&`, `|`, `~`, `is_in`, `is_between`, `is_null` and a few string tests. An expression that calls your own Python code (`map_elements`, `map_batches`) is refused as soon as Orcapod needs to hash it (in a join, a pod or a job), with an error that names the expression and lists what can be hashed; compute such a test in a function pod -instead. The -full list is in [PolarsFilter](../concepts/operators.md#polarsfilter). +instead. The full list is in [PolarsFilter](../concepts/operators.md#polarsfilter); `filter` +itself is described in [Filter](../concepts/operators.md#filter). One more filter, `drop_nulls`, keeps the rows that have a value in the columns you name. The workshop data has no missing values, so it is not needed here; see @@ -192,7 +241,7 @@ A `join` followed by an equality filter selects the same 32 rows, but also carri columns of `subjects` along: ```python -print(units.join(subjects).polars_filter(genotype="knockout").keys()[1]) +print(units.join(subjects).filter(genotype="knockout").keys()[1]) # ('region', 'depth_um', 'n_spikes', 'sex', 'age_weeks', 'genotype') ``` @@ -237,12 +286,12 @@ cannot keep both under one name. To see this, split the units by probe. Each hal ```python imec0 = ( - units.polars_filter(probe="imec0") + units.filter(probe="imec0") .drop_tag_columns(["probe"]) .select_data_columns(["n_spikes"]) ) imec1 = ( - units.polars_filter(probe="imec1") + units.filter(probe="imec1") .drop_tag_columns(["probe"]) .select_data_columns(["n_spikes"]) ) @@ -303,8 +352,9 @@ with a different content hash. - Operators rearrange streams; they never compute new values. - `join` matches on shared tags, keeps only matching rows, and needs distinct data column names. -- `polars_filter` keeps rows by equality (`column=value`) or by a Polars expression; both - work anywhere in a pipeline. +- `filter` keeps rows by equality (`column=value`) or by conditions built with `col` + (comparisons, `is_in`, `between`, null tests, `&`, `|`, `~`); it is a step of the pipeline. + `polars_filter` takes a Polars expression for anything else. - `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`. @@ -320,7 +370,7 @@ with exactly two data columns: `n_spikes` and `age_weeks`. How many rows does it ```python answer = ( units.join(subjects) - .polars_filter(genotype="knockout", probe="imec1") + .filter(genotype="knockout", probe="imec1") .select_data_columns(["n_spikes", "age_weeks"]) ) print(answer.as_pandas_df().sort_values(unit_tags, ignore_index=True).head(4)) diff --git a/docs/tutorial/04-many-rows-into-one.md b/docs/tutorial/04-many-rows-into-one.md index 4d909ff37..3899d1507 100644 --- a/docs/tutorial/04-many-rows-into-one.md +++ b/docs/tutorial/04-many-rows-into-one.md @@ -263,7 +263,7 @@ filter, then narrow, then `batch()`.) for genotype in ["wildtype", "knockout"]: one_genotype = ( - with_genotype.polars_filter(genotype=genotype) + with_genotype.filter(genotype=genotype) .select_data_columns(["mean_rate_hz"]) .batch() ) diff --git a/docs/tutorial/07-files.md b/docs/tutorial/07-files.md index 55e307622..7520a4055 100644 --- a/docs/tutorial/07-files.md +++ b/docs/tutorial/07-files.md @@ -326,7 +326,7 @@ it. Check your result for `mouse_02, s1, imec1` against `units.csv`. return sum(1 for row in csv.DictReader(f) if row["unit"] == "0") - result = count_unit0.pod(spike_files.polars_filter(subject_id="mouse_02", session="s1")) + result = count_unit0.pod(spike_files.filter(subject_id="mouse_02", session="s1")) print(result.as_pandas_df()) # subject_id session probe n_spikes_unit0 # 0 mouse_02 s1 imec0 321 diff --git a/docs/tutorial/08-inspecting-and-tracing.md b/docs/tutorial/08-inspecting-and-tracing.md index e657f119e..18c3f5dea 100644 --- a/docs/tutorial/08-inspecting-and-tracing.md +++ b/docs/tutorial/08-inspecting-and-tracing.md @@ -289,7 +289,7 @@ Use the source-info column of the `sessions` node. Row 5, counting data rows from 0: the sixth line after the header. Note the plain Polars filter on a table you have already taken out of Orcapod. Inside a - pipeline you would write the same test as `stream.polars_filter(...)` (Part 3). + pipeline you would write the same test as `stream.filter(...)` (Part 3). **3.** Using `as_source()`, compute the mean of the session means per animal (one row per `subject_id`). Reuse `group_by` from Part 4. diff --git a/docs/tutorial/10-where-next.md b/docs/tutorial/10-where-next.md index 3bb6d9373..1bbec5aad 100644 --- a/docs/tutorial/10-where-next.md +++ b/docs/tutorial/10-where-next.md @@ -171,11 +171,13 @@ the job a new name, and run it twice. How many deliveries are there after each r # 4 ``` - You can make the decision in the function, or filter the stream before the sink with an - expression filter (Part 3), which works inside a job like any other operator. Filtering - keeps the sink itself unchanged: + You can make the decision in the function, or filter the stream before the sink with + `filter` (Part 3), which works inside a job like any other operator. Filtering keeps the + sink itself unchanged: ```python + from orcapod import col + delivered_long = [] @@ -188,7 +190,7 @@ the job a new name, and run it twice. How many deliveries are there after each r job = PipelineJob(name="long_announcements", database=database) with job: announce_long( - durations.polars_filter(pl.col("duration_s") > 100), label="announce_long" + durations.filter(col("duration_s") > 100.0), label="announce_long" ) job.run() diff --git a/src/orcapod/contexts/data/v1.json b/src/orcapod/contexts/data/v1.json index 96d57c78a..171af2462 100644 --- a/src/orcapod/contexts/data/v1.json +++ b/src/orcapod/contexts/data/v1.json @@ -265,9 +265,9 @@ "provisional": { "arrow.json": "a44e0f9b4312a2ac5edeedf9f3e35bda43a3ee012bd7c5a1e66f7269eaacd05e", "datagram.json": "8182f8d7dbbdea27ad4dc29175be5a79a8a8d723b0513d6054e0b4d6d2634fd3", - "pipeline.json": "47fa244ae94010db9e884def875449878218d9168e0d09528300ecc727b4e63b", + "pipeline.json": "cbcc65fc797abeb42839700def5bc67b47636d1dd53dd2879127d1b513873179", "schema.json": "56f5e9f0a6acaedfa29c6b78afafabba4b7255fed67923dcf2be0b9294abc65d", - "semantic.json": "a046be33210299869770043468c2ce5fab05ee32125e7e7e7bc6eb66d37a49b5", + "semantic.json": "03c079117e3c05f9e2532445defdc9d110d846e6c6e54a35cdc03b6ea2fa68c4", "torch.json": "4691f15b9b4e2db3fd6fcf99ad06ab28a183c3ac84dc198aa448d06c784fb48a" } }, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 15372f688..65ffcc076 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -54,6 +54,7 @@ ) if TYPE_CHECKING: + from orcapod.types.explanation import Explanation import pyarrow as pa from orcapod.channels import WritableChannel @@ -831,6 +832,16 @@ def node_uri(self) -> tuple[str, ...]: """ return ("source_node", self._name) + def explain(self) -> Explanation: + """Say what the source bound here applies itself (``StreamBase.explain``). + + Returns: + An ``Explanation``; for a slot with no source bound, that it has none. + """ + from orcapod.core.streams.explain import explain + + return explain(self) + @property def producer(self) -> None: """Source nodes have no producer pod — they are root nodes. diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index 879229f58..c4519f94b 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -283,6 +283,15 @@ def to_config(self) -> dict[str, Any]: } return config + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the step drops, for ``explain()``: a last partial batch, if asked.""" + return "a last partial batch is dropped" if self.drop_partial_batch else None + def identity_structure(self) -> Any: self._note_provisional_identity_use() # a direct read is a use (ITL-1279) return (self.__class__.__name__, self.batch_size, self.drop_partial_batch) diff --git a/src/orcapod/core/operators/drop_nulls.py b/src/orcapod/core/operators/drop_nulls.py index 98bb18594..59481c811 100644 --- a/src/orcapod/core/operators/drop_nulls.py +++ b/src/orcapod/core/operators/drop_nulls.py @@ -119,6 +119,17 @@ def __init__( self.columns = tuple(sorted(set(names))) super().__init__(**kwargs) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the step drops, for ``explain()``: rows with a null in its columns.""" + if self.columns is None: + return "no null in any tag or data column" + return f"no null in {', '.join(self.columns)}" + def identity_structure(self) -> Any: """Return the operator's identity: its class name and the set of column names. diff --git a/src/orcapod/core/operators/filter.py b/src/orcapod/core/operators/filter.py index fd7405a1e..9f489ab4a 100644 --- a/src/orcapod/core/operators/filter.py +++ b/src/orcapod/core/operators/filter.py @@ -101,6 +101,15 @@ def condition(self) -> Condition: """The condition every kept row satisfies.""" return self._condition + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the filter keeps, for ``explain()``: its condition's text.""" + return self._condition.canonical_text() + def identity_structure(self) -> Any: """Return the operator's identity: its class name and the canonical condition. diff --git a/src/orcapod/core/operators/filters.py b/src/orcapod/core/operators/filters.py index 1a3a7f23a..435b48a3b 100644 --- a/src/orcapod/core/operators/filters.py +++ b/src/orcapod/core/operators/filters.py @@ -1,5 +1,5 @@ import logging -from collections.abc import Collection, Iterable, Mapping +from collections.abc import Callable, Collection, Iterable, Mapping, Sequence from typing import Any, ClassVar, TYPE_CHECKING, TypeAlias from orcapod.core.data_tags import stream_data_tags @@ -25,6 +25,20 @@ polars_predicate: TypeAlias = "pl_type.IntoExprColumn| Iterable[pl_type.IntoExprColumn]| bool| list[bool]| np.ndarray[Any, Any]" +_SAFE_SCALARS: tuple[type, ...] = (bool, int, float, str, bytes, type(None)) +"""Values whose ``repr`` is the built-in one: written as they are by ``explain()``.""" + + +def _safe_text(value: object, write: Callable[[object], str]) -> str: + """Return ``value`` written by ``write`` when its type's writer is Polars' or the + built-in one (exactly ``pl.Expr`` or a built-in scalar); otherwise ````, + so no user-defined ``__str__`` or ``__repr__`` runs (``explain()`` runs no user code). + """ + if type(value) in _SAFE_SCALARS or type(value) is pl.Expr: + return write(value) + return f"<{type(value).__name__}>" + + class PolarsFilter(UnaryOperator): """ Operator that applies Polars filtering to a stream @@ -174,6 +188,32 @@ def from_config(cls, config: dict[str, Any]) -> "PolarsFilter": constraints = inner.get("constraints") return cls(predicates=predicates, constraints=constraints) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the filter keeps, for ``explain()``: its constraints and predicates as + text, each sorted (display only). + + No user code runs: a Polars expression is written by Polars (``pl.Expr`` + exactly), a constraint value by ``repr`` when it is exactly a built-in scalar, + and anything else by its type name only. The constraints are read only when + they are exactly a ``dict`` with ``str`` names (a mapping of another class could + run its own ``items()``); otherwise they are written as their type name. + """ + constraints = self.constraints + if type(constraints) is dict and all(type(name) is str for name in constraints): + parts = sorted( + f"{name}={_safe_text(value, repr)}" + for name, value in dict.items(constraints) + ) + else: + parts = [f"<{type(constraints).__name__}>"] + parts += sorted(_safe_text(predicate, str) for predicate in self.predicates) + return ", ".join(parts) if parts else None + def identity_structure(self) -> Any: self._note_provisional_identity_use() # a direct read is a use (ITL-1279) return ( diff --git a/src/orcapod/core/operators/index.py b/src/orcapod/core/operators/index.py index 7b2913c82..660a06059 100644 --- a/src/orcapod/core/operators/index.py +++ b/src/orcapod/core/operators/index.py @@ -7,6 +7,7 @@ from collections.abc import Sequence from typing import Any, ClassVar, TYPE_CHECKING, cast +from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -83,6 +84,21 @@ def __init__( self._element_arrow_type_error: str = "" super().__init__(**kwargs) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the step drops, for ``explain()``: rows missing the element, unless a + miss raises.""" + if self.fail_on_miss: + return None + return ( + f"rows whose {plain_repr(self.column)} has no element " + f"{plain_repr(self.i)} are dropped" + ) + def identity_structure(self) -> Any: self._note_provisional_identity_use() # a direct read is a use (ITL-1279) return (self.__class__.__name__, self.column, self.i, self.out) diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index c48254a88..fe8cc812b 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -5,6 +5,7 @@ from collections.abc import Callable, Collection, Mapping, Sequence from typing import Any, ClassVar, TYPE_CHECKING +from orcapod.types.explanation import plain_repr from orcapod.core.operators.meta_columns import ( WithoutMetaWriter, without_input_meta, @@ -1368,6 +1369,19 @@ def _sort_merged_system_tags(merged_sys: dict) -> dict: return merged_sys + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the join drops, for ``explain()``: rows without a match in the others.""" + if not others: + # A join of one input passes every row through. + return None + names = ", ".join(plain_repr(name) for name in others) + return f"rows without a match in {names} are dropped" + def identity_structure(self) -> Any: return self.__class__.__name__ diff --git a/src/orcapod/core/operators/merge_join.py b/src/orcapod/core/operators/merge_join.py index 616b135de..83d911990 100644 --- a/src/orcapod/core/operators/merge_join.py +++ b/src/orcapod/core/operators/merge_join.py @@ -1,5 +1,7 @@ +from collections.abc import Sequence from typing import Any, ClassVar, TYPE_CHECKING, cast +from orcapod.types.explanation import plain_repr from orcapod.core.operators.base import ( BinaryOperator, require_matchable_key, @@ -589,6 +591,16 @@ def binary_static_process( data_tags=data_tag_names(tag_schema, data_schema), ) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the join drops, for ``explain()``: rows without a match in the others.""" + names = ", ".join(plain_repr(name) for name in others) + return f"rows without a match in {names} are dropped" + def identity_structure(self) -> Any: self._note_provisional_identity_use() # a direct read is a use (ITL-1279) return self.__class__.__name__ diff --git a/src/orcapod/core/operators/pick.py b/src/orcapod/core/operators/pick.py index 6b3d28e0a..40aff6309 100644 --- a/src/orcapod/core/operators/pick.py +++ b/src/orcapod/core/operators/pick.py @@ -7,6 +7,7 @@ from collections.abc import Sequence from typing import Any, ClassVar, TYPE_CHECKING, cast +from orcapod.types.explanation import plain_repr from orcapod.core.data_tags import stream_data_tags from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.channels import ReadableChannel, WritableChannel @@ -85,6 +86,22 @@ def __init__( self._value_arrow_type_error: str = "" super().__init__(**kwargs) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the step drops, for ``explain()``: rows missing the key of a ``dict`` + column, unless a miss raises. A struct field is known to exist (checked when the + step is built), so a struct projection drops none.""" + if self.fail_on_miss or self._mode != "map": + return None + return ( + f"rows whose {plain_repr(self.column)} has no key " + f"{plain_repr(self.key)} are dropped" + ) + def identity_structure(self) -> Any: self._note_provisional_identity_use() # a direct read is a use (ITL-1279) # fail_on_miss intentionally excluded — it controls error behaviour, diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index c338c647c..227835e09 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -5,6 +5,7 @@ from collections.abc import AsyncGenerator, AsyncIterator, Collection, Sequence from typing import TYPE_CHECKING, Any, ClassVar, final +from orcapod.types.explanation import plain_repr from orcapod.channels import ChannelClosed, ReadableChannel, WritableChannel from orcapod.core.operators.meta_columns import WithoutMetaWriter from orcapod.core.data_tags import stream_data_tags @@ -465,6 +466,27 @@ def _match_key( values.append(value) return tuple(values) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What the semi-join does, for ``explain()``: the first input keeps the rows + that match the second; the second's rows only choose and do not flow on. + + With no tag column shared by the two inputs (``_match_keys``, read from their + schemas), every row of the first input flows on and the second chooses nothing. + """ + names = ", ".join(plain_repr(name) for name in others) + left, right = inputs + shared = self._match_keys(tuple(left.keys()[0]), tuple(right.keys()[0])) + if position == 0: + return f"rows without a match in {names} are dropped" if shared else None + if not shared: + return f"no tag is shared with {names}: its rows choose nothing and do not flow on" + return f"its rows only choose rows of {names} and do not flow on" + def identity_structure(self) -> Any: return self.__class__.__name__ diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 6263026f0..ac43f9fc3 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +import dataclasses import logging from abc import abstractmethod from collections.abc import Collection, Iterator, Sequence @@ -34,6 +35,7 @@ ) from orcapod.core.streams.view import ( STALE_NOTE, + default_note, ViewStatus, StreamView, head_of, @@ -511,6 +513,29 @@ def _zero_row_input(upstream: StreamProtocol) -> StreamProtocol | None: upstream, ) + def rows_dropped_text( + self, + position: int, + others: Sequence[str], + inputs: Sequence[StreamProtocol], + ) -> str | None: + """What this operator drops of the rows of its input at ``position``, in words, + for ``explain()``; ``None`` when it drops none (the default). + + Read from the operator's own arguments only: nothing is computed or read. + + Args: + position: The input's position among the operator's inputs. + others: The names of the operator's other inputs, sorted. + inputs: The operator's inputs, in order; only their schemas (``keys()``) + may be read. + + Returns: + A phrase (``t >= 1.0``; ``rows without a match in 'probes' are dropped``), + or ``None``. + """ + return None + def head_rows(self, stream: StreamProtocol, table: pa.Table) -> pa.Table | None: """The rows ``head`` may show of this operator over ``stream``, from the rows ``stream``'s own ``head`` shows (``table``), before the result is computed. @@ -1108,17 +1133,22 @@ def head( had_result = self._cached_stream is not None self._update_cache_status() if self._cached_stream is not None and self._cached_time is not None: - return head_of( + view = head_of( self._cached_stream.head(n, columns=config), self, origin="computed" ) - matching = self._matching_head(n, config) - if matching is not None: - return matching - return self._head_without_rows( - config, - ViewStatus.NOT_COMPUTED, - note=STALE_NOTE if had_result else None, - ) + else: + matching = self._matching_head(n, config) + # A view of no rows is falsy (``StreamView.__len__``): compared to None. + view = ( + matching + if matching is not None + else self._head_without_rows( + config, + ViewStatus.NOT_COMPUTED, + note=STALE_NOTE if had_result else None, + ) + ) + return _with_explain_line(view, self) def _matching_head(self, n: int, config: ColumnConfig) -> StreamView | None: """The head an operator shows from its input's head (``head_rows``), or ``None``. @@ -1173,6 +1203,23 @@ def __repr__(self) -> str: ) +def _with_explain_line(view: StreamView, stream: StreamProtocol) -> StreamView: + """Return ``view`` with the one-line split of ``explain()`` added to its header, for + a ``Filter`` directly over a source (ITL-1402); any other view unchanged.""" + from orcapod.core.streams.explain import preview_line + + line = preview_line(stream) + if line is None: + return view + if view.description is not None: + return dataclasses.replace(view, description=f"{view.description}; {line}") + if view.status in (ViewStatus.ROWS, ViewStatus.LOADED_ONLY, ViewStatus.PARTIAL): + note = f"{view.note}; {line}" if view.note else line + else: + note = f"{view.note or default_note(view.status)}; {line}" + return dataclasses.replace(view, note=note) + + def _upstream_state(stream: StreamProtocol) -> tuple[str, object]: """What tells a change of an upstream of an operator stream. diff --git a/src/orcapod/core/sources/base.py b/src/orcapod/core/sources/base.py index 1eed1f022..75d1de6d3 100644 --- a/src/orcapod/core/sources/base.py +++ b/src/orcapod/core/sources/base.py @@ -84,6 +84,12 @@ class RootSource(StreamBase): # (ITL-1019): from format 0.3.0 on such a config always holds it. TAKES_TAG_ONLY_COLUMNS: ClassVar[bool] = False + REPORTS_WHAT_IT_READS: ClassVar[bool] = True + """Whether the source says what it reads (``explain()``, ITL-1402): its restriction + (``condition``, ``row_limit``), and with none, its whole table. ``False`` for a source + that reads rows stored elsewhere (``DerivedSource``, ``CachedSource``): what it reads + depends on what was stored there.""" + PROVISIONAL: ClassVar[bool] = False """Whether the source is provisional: its identity is not frozen (ITL-1314). diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 4be081849..d3018542a 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -86,6 +86,9 @@ class CachedSource(RootSource): HASH_COLUMN_NAME = "_record_hash" + REPORTS_WHAT_IT_READS: ClassVar[bool] = False + """It reads its cache, which holds what earlier reads stored (``explain()``, ITL-1402).""" + # Set once a read has reported the cached rows it skipped. _skipped_rows_reported: bool = False # Set once a cache table found at the older layout has been accounted for. diff --git a/src/orcapod/core/sources/derived_source.py b/src/orcapod/core/sources/derived_source.py index 5b06672d2..dc1ff1daa 100644 --- a/src/orcapod/core/sources/derived_source.py +++ b/src/orcapod/core/sources/derived_source.py @@ -197,6 +197,9 @@ class DerivedSource(RootSource): PROVISIONAL = True """Provisional in data context v1, both forms (ITL-1331, ``PROVISIONAL_SOURCES``).""" + REPORTS_WHAT_IT_READS = False + """It reads the rows stored for its origin (``explain()``, ITL-1402).""" + @staticmethod def _missing_source_id() -> ValueError: """The error for a ``tags_as_data`` source built or loaded without a ``source_id``.""" diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 031478bb4..e05896b63 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -35,6 +35,7 @@ from orcapod.utils.lazy_module import LazyModule if TYPE_CHECKING: + from orcapod.types.explanation import Explanation import pandas as pd import polars as pl import pyarrow as pa @@ -682,6 +683,25 @@ def filter( return Filter(Condition.of(*conditions, **columns))(self, label=label) + def explain(self) -> Explanation: + """Say what each source applies itself, and what is applied after reading. + + For every source this stream reads (through a job's input slot to its bound + source): its own restriction (``where``, ``limit``), or that it reads its whole + table; and the steps above it that drop rows after they are read (a ``Filter``, a + ``DropNulls``, a join's unmatched rows), nearest the source first. New in this + release (ITL-1402). + + Nothing is computed, read, polled or written, and no user code runs: only what the + chain declares is read. + + Returns: + An ``Explanation``: plain data, with ``text()`` (also its ``str``). + """ + from orcapod.core.streams.explain import explain + + return explain(self) + def drop_nulls( self, columns: str | Collection[str] | None = None, diff --git a/src/orcapod/core/streams/explain.py b/src/orcapod/core/streams/explain.py new file mode 100644 index 000000000..beca58d22 --- /dev/null +++ b/src/orcapod/core/streams/explain.py @@ -0,0 +1,258 @@ +"""``stream.explain()``: what each source applies itself, and what is applied after reading. + +A user cannot tell from a pipeline whether a selection is applied by the source (a +``where`` restriction, which reads little) or after the source's rows are read (a +``filter`` step, which on an unrestricted table reads every row). ``explain()`` says which +(ITL-1402, decision 9 of ITL-1374). + +It walks the stream's chain down to its sources and reads only what the chain declares: +each source's restriction (``condition``, ``row_limit``), each operator's own arguments +and the names of the steps. It never computes, reads a row, polls, writes or calls user +code. The result is plain data (``Explanation``) with a text form; the text is the same +whatever order the sources, the inputs or an argument's items were given in. +""" + +from __future__ import annotations + +from collections.abc import Sequence +from typing import TYPE_CHECKING + +from orcapod.types.condition import Condition +from orcapod.types.explanation import Explanation, SourceReading, Step + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import StreamProtocol + + +def stream_name(stream: StreamProtocol) -> str: + """Return how a stream is named in an explanation: ``Kind[label]``.""" + return f"{type(stream).__name__}[{stream.label}]" + + +def _beneath( + stream: StreamProtocol, +) -> tuple[str, tuple[StreamProtocol, ...] | SourceReading]: + """Return what ``stream`` reads: its inputs, or the reading it ends in. + + A job's input slot reads its bound source, a proxy its delegate; a root source, a + cached source and a stream with no producer and no input end the walk. + """ + from orcapod.core.nodes.source_node import SourceJobNode, SourceNodeBase + from orcapod.core.sources.base import RootSource + from orcapod.core.sources.source_proxy import SourceProxy + from orcapod.pipeline.restrictions import source_name + + if isinstance(stream, (SourceNodeBase, SourceProxy)): + # A job's slot reads its bound source, a proxy its delegate; a pipeline's + # ``SourceNode`` declares a slot and never holds a source. + if isinstance(stream, SourceJobNode): + bound = stream.bound_source + elif isinstance(stream, SourceProxy): + bound = stream.delegate + else: + bound = None + if bound is None: + return "unbound", SourceReading( + # A slot by its name, the key a source is bound under; a proxy by its + # label. + name=stream.name + if isinstance(stream, SourceNodeBase) + else stream.label, + kind=type(stream).__name__, + known=False, + bound=False, + condition=Condition(), + limit=None, + steps=(), + ) + return "inputs", (bound,) + if isinstance(stream, RootSource): + return "source", SourceReading( + name=source_name(stream), + kind=type(stream).__name__, + known=stream.REPORTS_WHAT_IT_READS, + bound=True, + condition=stream.condition, + limit=stream.row_limit, + steps=(), + ) + upstreams = tuple(u for u in stream.upstreams if u is not None) + if not upstreams: + # A raw stream: rows held as given, from nowhere it names. + return "source", SourceReading( + name=stream.label, + kind=type(stream).__name__, + known=False, + bound=True, + condition=Condition(), + limit=None, + steps=(), + ) + return "inputs", upstreams + + +_ReadingKey = tuple[str, str, bool, bool, Condition, "int | None"] +"""A source as an explanation tells sources apart: name, kind, whether it says what it +reads, whether it is bound, and its restriction (two restrictions of one table are two +readings).""" + + +def _reading_key(reading: SourceReading) -> _ReadingKey: + return ( + reading.name, + reading.kind, + reading.known, + reading.bound, + reading.condition, + reading.limit, + ) + + +def _sort_key(key: _ReadingKey) -> tuple[str, str, bool, bool, str, int]: + name, kind, known, bound, condition, limit = key + return ( + name, + kind, + known, + bound, + condition.canonical_text(), + -1 if limit is None else limit, + ) + + +# Per source a node reaches: the source's reading, the node's distance from it (the +# shortest path), and the steps on the way, each by the node and text that made it, +# with that node's distance from the source. +_Reach = dict[ + _ReadingKey, tuple[SourceReading, int, dict[tuple[int, str], tuple[int, Step]]] +] + + +def _reach(stream: StreamProtocol, memo: dict[int, _Reach]) -> _Reach: + """Return the sources ``stream`` reads and the steps above each, once per node. + + Each node is expanded once (``memo``), so a graph whose nodes share inputs costs one + visit per node, not one per path. A step is identified by the node that takes it + (and its text, as a ``SemiJoin`` drops differently on each input), so a step reached + by several paths is listed once, at its shortest distance from the source. + """ + known = memo.get(id(stream)) + if known is not None: + return known + kind, found = _beneath(stream) + if isinstance(found, SourceReading): + result: _Reach = {_reading_key(found): (found, 0, {})} + memo[id(stream)] = result + return result + inputs = found + reaches = [_reach(upstream, memo) for upstream in inputs] + producer = stream.producer if kind == "inputs" else None + result = {} + for position, reach in enumerate(reaches): + step = _step_of(stream, producer, position, inputs, reaches) + for key, (reading, distance, steps) in reach.items(): + here = distance + 1 + _, kept, merged = result.get(key, (reading, here, {})) + merged = dict(merged) + for step_key, (step_distance, kept_step) in steps.items(): + previous = merged.get(step_key) + if previous is None or step_distance < previous[0]: + merged[step_key] = (step_distance, kept_step) + if step is not None: + step_key = (id(stream), step.text) + previous = merged.get(step_key) + if previous is None or here < previous[0]: + merged[step_key] = (here, step) + result[key] = (reading, min(kept, here), merged) + memo[id(stream)] = result + return result + + +def _step_of( + stream: StreamProtocol, + producer: object, + position: int, + inputs: Sequence[StreamProtocol], + reaches: Sequence[_Reach], +) -> Step | None: + """Return the step ``stream``'s operator takes on its input at ``position``; the + other inputs are named by the sources they read (sorted, joined).""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + if not isinstance(producer, StaticOutputOperatorPod): + return None + others = sorted( + ", ".join(sorted({reading.name for reading, _, _ in reach.values()})) + for i, reach in enumerate(reaches) + if i != position + ) + text = producer.rows_dropped_text(position, others, inputs) + if text is None: + return None + return Step(operator=type(producer).__name__, label=stream.label, text=text) + + +def explain(stream: StreamProtocol) -> Explanation: + """Return what ``stream``'s sources apply themselves and what is applied after. + + Args: + stream: The stream (a stream, a source or a job node). + + Returns: + The explanation; nothing is computed, read, polled or written. + """ + reach = _reach(stream, {}) + sources = [] + for key in sorted(reach, key=_sort_key): + reading, _, steps = reach[key] + # Nearest the source first; ties in a fixed order. + ordered = sorted( + steps.values(), + key=lambda item: (item[0], item[1].operator, item[1].label, item[1].text), + ) + sources.append( + SourceReading( + name=reading.name, + kind=reading.kind, + known=reading.known, + bound=reading.bound, + condition=reading.condition, + limit=reading.limit, + steps=tuple(step for _, step in ordered), + ) + ) + return Explanation(stream=stream_name(stream), sources=tuple(sources)) + + +def preview_line(stream: StreamProtocol) -> str | None: + """Return the one-line split a preview shows for a ``Filter`` directly over a source. + + ``applied by the source: where session='s1'; after reading: t >= 1.0``, or + ``applied by the source: nothing; after reading: t >= 1.0 (the whole table is + read)``. ``None`` for any other stream. Reads what ``explain()`` reads, nothing more. + + Args: + stream: The stream whose head is shown. + + Returns: + The line, or ``None``. + """ + from orcapod.core.operators.filter import Filter + + producer = stream.producer + upstreams = stream.upstreams + if not isinstance(producer, Filter) or len(upstreams) != 1: + return None + kind, found = _beneath(upstreams[0]) + if kind != "source" or not isinstance(found, SourceReading): + return None + after = producer.condition.canonical_text() + if not found.known: + return f"applied by the source: not known for this source kind; after reading: {after}" + if not found.condition and found.limit is None: + return ( + f"applied by the source: nothing; after reading: {after} " + "(the whole table is read)" + ) + applied = found.lines()[1].removeprefix(" applied by the source: ") + return f"applied by the source: {applied}; after reading: {after}" diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index 0affbe8a0..4864a6590 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -16,6 +16,7 @@ from orcapod.types import ColumnConfig, Condition, Schema if TYPE_CHECKING: + from orcapod.types.explanation import Explanation import pandas as pd import polars as pl import pyarrow as pa @@ -130,6 +131,13 @@ def upstreams(self) -> tuple["StreamProtocol", ...]: """ ... + def explain(self) -> "Explanation": + """ + Say what each source this stream reads applies itself (its restriction, or its + whole table) and which steps drop rows after reading; computes nothing. + """ + ... + def keys( self, *, diff --git a/src/orcapod/types/__init__.py b/src/orcapod/types/__init__.py index 363412827..7ee6e7ac6 100644 --- a/src/orcapod/types/__init__.py +++ b/src/orcapod/types/__init__.py @@ -9,6 +9,8 @@ a raw digest, with convenience conversions to hex, int, UUID, and base64. - ``Condition`` -- the row conditions of a restriction, defined in ``orcapod.types.condition``. + - ``Explanation``, ``SourceReading``, ``Step`` -- what ``stream.explain()`` returns, + defined in ``orcapod.types.explanation``. """ from __future__ import annotations @@ -30,6 +32,11 @@ from orcapod.types.condition import Condition as Condition from orcapod.types.condition import col as col +# Re-exported: what ``stream.explain()`` returns (ITL-1402). +from orcapod.types.explanation import Explanation as Explanation +from orcapod.types.explanation import SourceReading as SourceReading +from orcapod.types.explanation import Step as Step + if TYPE_CHECKING: import pyarrow as pa diff --git a/src/orcapod/types/explanation.py b/src/orcapod/types/explanation.py new file mode 100644 index 000000000..3a86fde29 --- /dev/null +++ b/src/orcapod/types/explanation.py @@ -0,0 +1,134 @@ +"""What ``stream.explain()`` returns (ITL-1402): plain data with a text form. + +``Explanation`` holds, for each source a stream reads, what the source applies itself and +which steps drop rows after reading. Built by ``orcapod.core.streams.explain``; nothing here +computes anything. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from orcapod.types.condition import Condition + + +def plain_repr(value: object) -> str: + """Return ``value`` as ``explain()`` writes a name or a key: by the ``repr`` of its + built-in base type (``str``, ``bytes``, ``int``, ``float``, ``bool``), so a subclass's + own ``__repr__`` never runs; any other value as ````.""" + if isinstance(value, str): + return str.__repr__(value) + if isinstance(value, bytes): + return bytes.__repr__(value) + if isinstance(value, bool): # before int: a bool is an int + return bool.__repr__(value) + if isinstance(value, int): + return int.__repr__(value) + if isinstance(value, float): + return float.__repr__(value) + return f"<{type(value).__name__}>" + + +@dataclass(frozen=True) +class Step: + """A step above a source that drops some of the rows read. + + Attributes: + operator: The operator's class name (``Filter``, ``DropNulls``, ``Join``). + label: The step's label (the operator's name when none was given). + text: What the step keeps or drops, in words (``t >= 1.0``; ``rows without a + match in 'probes' are dropped``). + """ + + operator: str + label: str + text: str + + def describe(self) -> str: + """Return the step as one phrase: ``t >= 1.0 (Filter[kept])``.""" + name = ( + self.operator + if self.label == self.operator + else f"{self.operator}[{self.label}]" + ) + return f"{self.text} ({name})" + + +@dataclass(frozen=True) +class SourceReading: + """One source of a stream: what it applies itself and what is applied after reading. + + Attributes: + name: The source's name (its source id, or the slot's name for an unbound slot). + kind: The source's class name (``SourceJobNode`` for an unbound slot). + known: Whether the source kind says what it reads. A source that reads rows + stored or held elsewhere (a derived or a cached source, a raw stream) does + not: what it reads depends on what was stored there. + bound: ``False`` for a job's input slot with no source bound. + condition: The condition the source applies itself (``where``), empty for none. + limit: The source's row limit, ``None`` for none. + steps: The steps above the source that drop rows of it, nearest the source first. + """ + + name: str + kind: str + known: bool + bound: bool + condition: Condition + limit: int | None + steps: tuple[Step, ...] + + def lines(self) -> list[str]: + """Return the reading as text lines (``Explanation.text``).""" + after = "; ".join(step.describe() for step in self.steps) or "nothing" + if not self.bound: + # The steps are declared: show them although no source is bound yet. + return [ + f"slot {plain_repr(self.name)}: no source bound", + f" applied after reading: {after}", + ] + if not self.known: + applied = "not known for this source kind" + elif self.condition or self.limit is not None: + parts = ( + [f"where {self.condition.canonical_text()}"] if self.condition else [] + ) + if self.limit is not None: + parts.append(f"limit {self.limit}") + applied = ", ".join(parts) + else: + applied = "nothing (the whole table is read)" + return [ + f"source {self.name!r} ({self.kind})", + f" applied by the source: {applied}", + f" applied after reading: {after}", + ] + + +@dataclass(frozen=True) +class Explanation: + """What a stream's sources apply themselves, and what is applied after reading. + + New in this release (ITL-1402). Returned by ``stream.explain()``; plain data, built + without computing, reading, polling or calling user code. + + Attributes: + stream: The explained stream, as ``Kind[label]``. + sources: One reading per source the stream reads, in source-name order. + """ + + stream: str + sources: tuple[SourceReading, ...] + + def text(self) -> str: + """Return the explanation as text: the stream, then one block per source.""" + lines = [f"{self.stream} reads:"] + for reading in self.sources: + lines.extend(f" {line}" for line in reading.lines()) + return "\n".join(lines) + + def __str__(self) -> str: + return self.text() + + def _repr_pretty_(self, printer: object, cycle: bool) -> None: # pyright: ignore[reportUnusedParameter] # IPython's display hook + printer.text(self.text()) # pyright: ignore[reportAttributeAccessIssue] # an IPython pretty printer diff --git a/tests/test_core/operators/test_filter_contradictions.py b/tests/test_core/operators/test_filter_contradictions.py new file mode 100644 index 000000000..a50f10f90 --- /dev/null +++ b/tests/test_core/operators/test_filter_contradictions.py @@ -0,0 +1,150 @@ +"""A contradictory condition is kept and keeps zero rows (developer, 2026-11-22; ITL-1374). + +"If there is no straightforward way to achieve, then the contradictory case should just +be taken as is and result in 0 rows." On a tag, a data column and a data-tag, with +several terms in several orders, on the sync and the async path, and through a saved job. +""" + +from __future__ import annotations + +import itertools +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col +from orcapod.core.operators import Filter +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.types import CacheMode, Condition + +from .several_items import async_rows + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + + +def _units( + tag_only_columns: Any = True, arrangement: str = "given" +) -> ArrowTableSource: + """Tags ``session`` and ``unit``; data ``t`` and ``probe``. With + ``tag_only_columns=["session"]``, ``unit`` is a data-tag. ``arrangement="reversed"`` + declares the tags in the other order and lays the table out backwards.""" + table = pa.table( + { + "session": pa.array(["s1", "s1", "s2", "s2"], pa.large_string()), + "unit": pa.array([3, 7, 3, 7], pa.int64()), + "t": pa.array([0.5, 1.5, 2.5, 3.5], pa.float64()), + "probe": pa.array(["imec0", "imec1", "imec0", "imec1"], pa.large_string()), + } + ) + tags = ["session", "unit"] + if arrangement == "reversed": + table = table.select(list(reversed(table.column_names))) + tags = list(reversed(tags)) + return ArrowTableSource( + table, + tag_columns=tags, + tag_only_columns=tag_only_columns, + source_id="units", + ) + + +# (role, source options, the column, its two values) +_ROLES = [ + ("tag", True, "session", ("s1", "s2")), + ("data", True, "probe", ("imec0", "imec1")), + ("data-tag", ["session"], "unit", (3, 7)), +] + + +def _terms(column: str, values: tuple[object, object]) -> list[Condition]: + """Two equalities that contradict each other, and a term every row satisfies.""" + return [col(column) == values[0], col(column) == values[1], col("t") >= 0.0] + + +@pytest.mark.parametrize("arrangement", ["given", "reversed"]) +@pytest.mark.parametrize( + "role, options, column, values", _ROLES, ids=[r[0] for r in _ROLES] +) +class TestZeroRows: + def test_every_order_builds_one_operator_and_keeps_no_row( + self, role, options, column, values, arrangement + ): + source = _units(options, arrangement) + hashes = set() + for order in itertools.permutations(_terms(column, values)): + filtered = Filter(Condition.of(*order))(source) + table = filtered.as_table() + assert table.num_rows == 0 + assert table.schema == source.as_table().schema + hashes.add(filtered.pipeline_hash().to_string()) + assert len(hashes) == 1 + + def test_the_and_spelling_and_the_method_agree( + self, role, options, column, values, arrangement + ): + source = _units(options, arrangement) + first, second, every = _terms(column, values) + by_and = Filter(first & every & second)(source) + by_method = source.filter(second, every, first) + assert by_and.as_table().num_rows == by_method.as_table().num_rows == 0 + assert by_and.pipeline_hash() == by_method.pipeline_hash() + + def test_async_keeps_no_row(self, role, options, column, values, arrangement): + source = _units(options, arrangement) + for order in (_terms(column, values), list(reversed(_terms(column, values)))): + assert async_rows(Filter(Condition.of(*order)), source) == [] + + def test_each_half_alone_keeps_rows( + self, role, options, column, values, arrangement + ): + """The zero rows come from the contradiction, not from either term.""" + source = _units(options, arrangement) + first, second, every = _terms(column, values) + assert source.filter(first, every).as_table().num_rows == 2 + assert source.filter(second, every).as_table().num_rows == 2 + + +@pytest.mark.parametrize( + "condition", + [ + Condition.of(col("unit").is_in([3]), col("unit").is_in([7])), + Condition.of(col("t") > 3.0, col("t") < 1.0), + Condition.of(col("probe") == "imec0", col("probe").is_null()), + Condition.of(col("unit") == 3, col("unit") > 5), + ], + ids=["disjoint is_in", "empty range", "value and null", "value and comparison"], +) +def test_other_contradictions_keep_no_row(condition): + source = _units() + assert Filter(condition)(source).as_table().num_rows == 0 + assert async_rows(Filter(condition), source) == [] + + +def test_a_saved_job_keeps_the_contradiction(tmp_path: Path): + """Saved and loaded, the contradiction is the same condition and its node stored + zero rows.""" + contradiction = Condition.of(col("session") == "s2", col("t") >= 0.0, session="s1") + database = DeltaTableDatabase(tmp_path / "store") + job = PipelineJob(name="contradiction", database=database) + with job: + _units().filter(contradiction, label="none") + job.nodes["none"].attach_databases( + pipeline_database=database.at("contradiction"), cache_mode=CacheMode.LOG + ) + job.run() + assert job.nodes["none"].as_table().num_rows == 0 + + path = tmp_path / "job.json" + job.save(path) + loaded = PipelineJob.load(path, database=DeltaTableDatabase(tmp_path / "store")) + node, reloaded = job.nodes["none"], loaded.nodes["none"] + assert isinstance(reloaded.producer, Filter) + assert reloaded.producer.condition == contradiction + assert ( + reloaded.producer.condition.canonical_form() == contradiction.canonical_form() + ) + assert reloaded.pipeline_hash() == node.pipeline_hash() + assert reloaded.as_source().as_table().num_rows == 0 diff --git a/tests/test_core/operators/test_filter_pipeline.py b/tests/test_core/operators/test_filter_pipeline.py new file mode 100644 index 000000000..2496fcf90 --- /dev/null +++ b/tests/test_core/operators/test_filter_pipeline.py @@ -0,0 +1,428 @@ +"""``Filter`` as a step of a pipeline (ITL-1382, the section 8 matrix of ITL-1374). + +What ``test_filter.py`` and ``test_filter_mask.py`` do not cover: a saved job holding a +filter of every condition kind, the restricted-aggregation warning, an identity that does +not follow the input's column width, and ``where`` against ``filter`` on one table. +""" + +from __future__ import annotations + +import datetime as dt +import warnings +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col, function_pod +from orcapod.core.operators import Filter +from orcapod.core.sources import ArrowTableSource +from orcapod.databases import DeltaTableDatabase +from orcapod.errors import RestrictedAggregationWarning +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.sources import SpiralDBTableSource +from orcapod.types import CacheMode, Condition +from tests.test_databases import fake_pyspiral + +pytestmark = pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning") + +_AT = dt.datetime(2026, 11, 25, 9, 0, tzinfo=dt.timezone.utc) +_DAY = dt.date(2026, 11, 25) + + +def _recordings() -> ArrowTableSource: + """Two tags, data of several types, a struct column and a NaN.""" + table = pa.table( + { + "session": pa.array(["s1", "s1", "s2", "s2", "s3"], pa.large_string()), + "unit": pa.array([3, 7, 3, 7, 3], pa.uint32()), + "t": pa.array([-0.0, 1.2, float("nan"), 0.5, 3.1], pa.float64()), + "rate": pa.array([4.0, None, 2.5, 6.1, None], pa.float64()), + "at": pa.array([_AT] * 5, pa.timestamp("us", tz="UTC")), + "day": pa.array([_DAY] * 5, pa.date32()), + "info": pa.array( + [ + {"kind": "good", "score": 1}, + {"kind": "noise", "score": 2}, + None, + {"kind": "good", "score": 3}, + {"kind": "mua", "score": 4}, + ], + pa.struct( + [pa.field("kind", pa.large_string()), pa.field("score", pa.int64())] + ), + ), + } + ) + return ArrowTableSource( + table, + tag_columns=["session", "unit"], + tag_only_columns=True, + source_id="recordings", + ) + + +# One condition of every kind, together. +_EVERY_KIND = Condition.of( + (col("t") >= 1.0) | (col("t") == 0.0) | col("rate").is_null(), + ~col("info").field("kind").is_in(["noise", "mua"]), + col("unit").between(3, 7), + col("at") <= _AT, + col("day") == _DAY, + col("rate") != col("t"), + session="s1", +) + + +def _kept(stream: Any) -> list[tuple[str, int]]: + return sorted( + (row["session"], row["unit"]) for row in stream.as_table().to_pylist() + ) + + +class TestSavedJob: + def test_a_saved_job_reloads_the_same_filter(self, tmp_path: Path): + """Every condition kind survives ``save`` and ``load``: same hashes, same rows.""" + store = tmp_path / "store" + database = DeltaTableDatabase(store) + job = PipelineJob(name="filtered", database=database) + with job: + _recordings().filter(_EVERY_KIND, label="kept") + # The job's own database object: job.run() flushes it, so the rows reach disk. + job.nodes["kept"].attach_databases( + pipeline_database=database.at("filtered"), cache_mode=CacheMode.LOG + ) + job.run() + expected = _kept(job.nodes["kept"]) + assert expected == [("s1", 3)] + + path = tmp_path / "job.json" + job.save(path) + assert '":condition"' in path.read_text() + loaded = PipelineJob.load(path, database=DeltaTableDatabase(store)) + + kept, reloaded = job.nodes["kept"], loaded.nodes["kept"] + assert reloaded.pipeline_hash() == kept.pipeline_hash() + assert reloaded.content_hash() == kept.content_hash() + operator = reloaded.producer + assert isinstance(operator, Filter) + assert operator.condition == _EVERY_KIND + assert operator.identity_structure() == kept.producer.identity_structure() + # Everything stored for the node reads back (its run's own view is empty + # before a run in this process, by design). + assert _kept(reloaded.as_source()) == expected + + +class TestRestrictedAggregationWarning: + """A filter is in every downstream identity, so an aggregate after it never warns + (design section 5, F12).""" + + @pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) + def test_a_filter_feeding_group_by_does_not_warn(self, tmp_path, orchestrator): + @function_pod(output_keys="n") + def count(t: list[float | None]) -> int: + return len(t) + + job = PipelineJob(name="grouped", database=DeltaTableDatabase(tmp_path)) + with job: + grouped = ( + _recordings() + .filter(col("rate").is_not_null(), col("unit").is_in([3, 7])) + .select_data_columns(["t"]) + .group_by(["session"], label="by_session") + ) + count.pod(grouped, label="count") + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + job.run(orchestrator=orchestrator() if orchestrator else None) + assert not [ + w for w in caught if issubclass(w.category, RestrictedAggregationWarning) + ] + + +class TestIdentityDoesNotFollowTheInput: + def test_one_literal_on_columns_of_two_widths(self): + """``col("unit") == 7`` is one operator on a ``uint32`` and an ``int64`` column + (the literal enters the identity, not the column's type); the rows agree.""" + + def source(arrow_type: pa.DataType) -> ArrowTableSource: + table = pa.table( + { + "unit": pa.array([3, 7, 9], arrow_type), + "x": pa.array([1.0, 2.0, 3.0]), + } + ) + return ArrowTableSource( + table, tag_columns=["unit"], tag_only_columns=True, source_id="u" + ) + + narrow, wide = source(pa.uint32()), source(pa.int64()) + operator = Filter(Condition.of(unit=7)) + assert ( + operator.identity_structure() + == Filter(col("unit") == 7).identity_structure() + ) + assert operator(narrow).as_table()["x"].to_pylist() == [2.0] + assert operator(wide).as_table()["x"].to_pylist() == [2.0] + # The streams differ by their input's schema only. + assert operator(narrow).pipeline_hash() != operator(wide).pipeline_hash() + + +# --- where and filter on one table ------------------------------------------------- + +_PROJECT = "workshop-sample" +_KEYS = pa.schema( + [pa.field("subject_id", pa.string()), pa.field("timestamp", pa.uint64())] +) + + +@pytest.fixture() +def project(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): + """A fake SpiralDB project holding a 6-row ``event`` table.""" + monkeypatch.setattr(fake_pyspiral, "scan_batch_rows", 2) + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project.create_table("default.event", key_schema=_KEYS).write( + pa.table( + { + "subject_id": ["m1", "m1", "m1", "m2", "m2", "m3"], + "timestamp": pa.array([1, 2, 3, 4, 5, 6], pa.uint64()), + "channel": pa.array([0, 1, 0, 1, 0, 1], pa.int16()), + "note": ["a", "b", "a", "b", "a", "b"], + "reading": pa.array( + [float("nan"), 1.0, float("nan"), -0.0, 0.0, 2.0], pa.float64() + ), + } + ) + ) + yield project + + +def _events() -> SpiralDBTableSource: + return SpiralDBTableSource( + _PROJECT, "event", source_id="events", tag_only_columns=True + ) + + +def _timestamps(stream: Any) -> list[int]: + return sorted(stream.as_table()["timestamp"].to_pylist()) + + +class TestWhereAgainstFilter: + @pytest.mark.parametrize( + "equalities", + [ + {"subject_id": "m1"}, + {"subject_id": "m1", "channel": 0}, + {"channel": 1, "note": "b", "subject_id": "m2"}, + {"note": "b", "subject_id": "m2", "channel": 1}, + ], + ids=["one", "two", "three", "three_reordered"], + ) + def test_the_same_equalities_keep_the_same_rows(self, project, equalities): + """``where(**e)`` and ``filter(**e)`` keep the same rows; only ``filter`` is a + step: ``where`` leaves the source's hashes, ``filter`` makes new ones.""" + events = _events() + restricted = events.where(**equalities) + filtered = events.filter(**equalities) + + assert _timestamps(restricted) == _timestamps(filtered) + assert restricted.content_hash() == events.content_hash() + assert filtered.content_hash() != events.content_hash() + assert filtered.pipeline_hash() != events.pipeline_hash() + + def test_where_then_the_same_filter(self, project): + """The large-table advice: ``where`` for speed, the same ``filter`` for identity.""" + events = _events() + both = events.where(subject_id="m2").filter(subject_id="m2") + assert _timestamps(both) == _timestamps(events.filter(subject_id="m2")) + assert both.pipeline_hash() == events.filter(subject_id="m2").pipeline_hash() + + +# --- Review findings, pinned (developer, 2026-11-22: every finding gets a test) --------- + + +def _limited(limit: int | None = None) -> SpiralDBTableSource: + return SpiralDBTableSource( + _PROJECT, "event", source_id="events", limit=limit, tag_only_columns=True + ) + + +@pytest.mark.parametrize( + "column, value, alone, together", + [ + ("note", "b", [2], [2, 4]), + ("channel", 1, [2], [2, 4]), + ("subject_id", "m2", [], [4, 5]), + ], + ids=["string data", "int16 data", "key column"], +) +def test_a_limit_counts_the_rows_where_matches(project, column, value, alone, together): + """CodeRabbit on PR 498 (sources.md:449, Major) and on PR 493 (spec 465-466): over a + source with ``limit=2``, ``where`` plus the same ``filter`` keeps the first two + matching rows, the ``filter`` alone only the matches among the first two rows read.""" + assert _timestamps(_limited(2).filter(**{column: value})) == alone + assert _timestamps( + _limited(2).where(**{column: value}).filter(**{column: value}) + ) == (together) + assert _timestamps(_limited().filter(**{column: value})) == _timestamps( + _limited().where(**{column: value}).filter(**{column: value}) + ) + + +@pytest.mark.parametrize( + "restriction, condition, expected", + [ + ({"subject_id": "m1"}, Condition.of(channel=0), [1, 3]), + ({"note": "b"}, Condition.of(col("timestamp") >= 4), [4, 6]), + ({"subject_id": "m2", "channel": 0}, Condition.of(note="a"), [5]), + ], + ids=["key restriction", "data restriction", "two restrictions"], +) +def test_a_filter_reads_what_the_source_selects( + project, restriction, condition, expected +): + """CodeRabbit on PR 498 (sources.md:446): a filter over a restricted source sees only + the rows the source's ``where`` selects, and its condition is not pushed into it.""" + source = _events().where(**restriction) + filtered = source.filter(condition) + assert _timestamps(filtered) == expected + assert source.condition == Condition.of(restriction) # nothing was pushed + + +@pytest.mark.parametrize( + "value, alone, with_where", + [ + (float("nan"), [1, 3], []), + (-0.0, [4, 5], [4, 5]), + (2.0, [6], [6]), + ], + ids=["NaN", "signed zero", "ordinary float"], +) +def test_where_and_filter_on_a_float_column(project, value, alone, with_where): + """CodeRabbit on PR 493 (spec 483, Major) and PR 498 (sources.md:447, operators.md:861): + ``filter`` matches floats by Orcapod's rule (NaN equals NaN); ``where`` by the table + system's equality (here IEEE: a NaN matches no row), so ``where`` plus ``filter`` can + keep fewer rows than the ``filter`` alone, and only for a NaN.""" + assert _timestamps(_events().filter(reading=value)) == alone + assert ( + _timestamps(_events().where(reading=value).filter(reading=value)) == with_where + ) + + +@pytest.mark.parametrize( + "condition", + [ + (col("subject_id") == "m1") & (col("subject_id") == "m2"), + Condition.of(col("channel") == 1, channel=0), + Condition.of(col("note").is_in(["a"]), col("note").is_in(["b"])), + ], + ids=["two key values", "two data values", "disjoint memberships"], +) +@pytest.mark.parametrize("restricted", [False, True], ids=["plain", "where-restricted"]) +def test_a_contradiction_over_a_spiral_source_never_raises( + project, condition, restricted +): + """CodeRabbit on PR 493 (spec 491, pushdown): a valid filter whose condition holds two + values for one column keeps zero rows over a SpiralDB source, restricted or not, + and never raises (version 1 pushes nothing).""" + source = _events().where(subject_id="m1") if restricted else _events() + assert _timestamps(source.filter(condition)) == [] + + +@pytest.mark.parametrize("orchestrator", [None, AsyncPipelineOrchestrator]) +def test_a_filter_after_a_where_still_warns_before_an_aggregate( + project, tmp_path, orchestrator +): + """CodeRabbit on PR 493 (spec 440): a ``Filter`` does not clear the + ``RestrictedAggregationWarning`` of a ``where``-restricted source upstream of it.""" + + @function_pod(output_keys="n") + def count(channel: list[int | None]) -> int: + return len(channel) + + job = PipelineJob( + name="restricted", database=DeltaTableDatabase(tmp_path / "store") + ) + with job: + grouped = ( + SpiralDBTableSource( + _PROJECT, "event", source_id="events", tag_only_columns=True + ) + .where(note="b") + .filter(col("channel") >= 0) + .select_data_columns(["channel"]) + .group_by(["subject_id"], label="by_subject") + ) + count.pod(grouped, label="count") + with pytest.warns(RestrictedAggregationWarning): + job.run(orchestrator=orchestrator() if orchestrator else None) + + +def _narrow(arrow_type: pa.DataType, values: list[object]) -> ArrowTableSource: + return ArrowTableSource( + pa.table( + {"k": pa.array([1, 2], pa.int64()), "x": pa.array(values, arrow_type)} + ), + tag_columns=["k"], + tag_only_columns=True, + source_id="narrow", + ) + + +_UNFIT = [ + (pa.int8(), [1, 2], 300), + (pa.uint32(), [1, 2], -1), + ( + pa.timestamp("us", tz="UTC"), + [dt.datetime(2026, 1, 1, tzinfo=dt.timezone.utc)] * 2, + dt.datetime(2026, 1, 1), + ), + ( + pa.timestamp("s"), + [dt.datetime(2026, 1, 1)] * 2, + dt.datetime(2026, 1, 1, 0, 0, 0, 1), + ), +] +_UNFIT_IDS = ["int8 range", "uint32 sign", "naive on zoned", "below the unit"] + + +@pytest.mark.parametrize("arrow_type, values, literal", _UNFIT, ids=_UNFIT_IDS) +class TestArrowChecksRunWhenApplied: + """CodeRabbit on PR 493 (spec 259): the Arrow-level checks (range, sign, zone, unit) + run when the filter meets its input, the same in a job and outside one.""" + + def test_outside_a_job(self, arrow_type, values, literal): + from orcapod.errors import InputValidationError + + filtered = _narrow(arrow_type, values).filter(x=literal) # builds + with pytest.raises(InputValidationError, match="'x'"): + filtered.as_table() + + def test_in_a_job(self, tmp_path, arrow_type, values, literal): + from orcapod.errors import InputValidationError + + job = PipelineJob(name="unfit", database=DeltaTableDatabase(tmp_path / "store")) + with job: + _narrow(arrow_type, values).filter(x=literal, label="unfit") # builds + with pytest.raises(InputValidationError, match="'x'"): + job.run() + + +@pytest.mark.parametrize("value", ["x", "y"]) +def test_a_column_named_label(value): + """CodeRabbit on PR 498 (sources.md:425): ``label=`` is the step's label, so a column + named ``label`` is filtered through a mapping or ``col``.""" + source = ArrowTableSource( + pa.table({"k": [1, 2], "label": ["x", "y"], "v": [1.0, 2.0]}), + tag_columns=["k"], + tag_only_columns=True, + source_id="labelled", + ) + by_mapping = source.filter({"label": value}) + by_col = source.filter(col("label") == value) + assert by_mapping.as_table()["label"].to_pylist() == [value] + assert by_mapping.pipeline_hash() == by_col.pipeline_hash() + with pytest.raises(ValueError, match="at least one"): + source.filter(label=value) diff --git a/tests/test_core/streams/test_explain.py b/tests/test_core/streams/test_explain.py new file mode 100644 index 000000000..b01da2f09 --- /dev/null +++ b/tests/test_core/streams/test_explain.py @@ -0,0 +1,679 @@ +"""``stream.explain()`` (ITL-1402): what each source applies, what is applied after reading. + +The cases of section 5 of the Filter design (``docs/dev/specs/itl-1374-filter.md``): +a restricted source under a filter, an unrestricted one, a filter below an operator or +function pod, several sources through a join, a job node; and that nothing is computed, +read, polled or written, and no user code runs. +""" + +from __future__ import annotations + +import dataclasses +from collections.abc import Iterator, Mapping +import itertools +from pathlib import Path +from typing import Any + +import polars as pl +import pyarrow as pa +import pytest + +from orcapod import PipelineJob, col, function_pod +from orcapod.core.nodes.source_node import SourceNode +from orcapod.core.operators import ( + DropNulls, + Pick, + Batch, + Filter, + GroupBy, + Index, + Join, + MergeJoin, + PolarsFilter, + SemiJoin, +) +from orcapod.core.sources import ArrowTableSource, DictSource +from orcapod.core.sources.cached_source import CachedSource +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.sources import SpiralDBTableSource +from orcapod.types import Condition, Explanation, SourceReading, Step +from tests.test_databases import fake_pyspiral + +pytestmark = [ + pytest.mark.filterwarnings("ignore::orcapod.errors.ProvisionalHashWarning"), + pytest.mark.filterwarnings( + "ignore::orcapod.core.data_tags.DataTagMaterializationWarning" + ), +] + +_PROJECT = "explain-sample" + + +def _units(source_id: str = "units") -> ArrowTableSource: + table = pa.table( + { + "session": pa.array(["s1", "s1", "s2"], pa.large_string()), + "unit": pa.array([3, 7, 3], pa.int64()), + "t": pa.array([0.5, 1.2, 2.0], pa.float64()), + "rate": pa.array([4.0, None, 2.5], pa.float64()), + } + ) + return ArrowTableSource( + table, + tag_columns=["session", "unit"], + tag_only_columns=True, + source_id=source_id, + ) + + +def _probes(source_id: str = "probes") -> ArrowTableSource: + table = pa.table( + { + "session": pa.array(["s1", "s2"], pa.large_string()), + "probe": pa.array(["imec0", "imec1"], pa.large_string()), + } + ) + return ArrowTableSource( + table, tag_columns=["session"], tag_only_columns=True, source_id=source_id + ) + + +@pytest.fixture() +def spiral(tmp_path: Path): + """A fake SpiralDB project with an ``event`` table; ``scan_log`` records reads.""" + keys = pa.schema( + [pa.field("subject_id", pa.string()), pa.field("timestamp", pa.uint64())] + ) + with fake_pyspiral.install(tmp_path / "spiral"): + project = fake_pyspiral.FakeSpiral().project(_PROJECT) + project.create_table("default.event", key_schema=keys).write( + pa.table( + { + "subject_id": ["m1", "m1", "m2"], + "timestamp": pa.array([1, 2, 3], pa.uint64()), + "amplitude": pa.array([0.5, 1.5, 2.5], pa.float64()), + } + ) + ) + fake_pyspiral.scan_log.clear() + yield project + fake_pyspiral.scan_log.clear() + + +def _event(**kwargs: Any) -> SpiralDBTableSource: + return SpiralDBTableSource(_PROJECT, "event", **kwargs) + + +class TestSectionFiveCases: + def test_a_restricted_source_under_a_filter(self, spiral): + source = _event().where(subject_id="m1") + stream = source.filter(col("amplitude") >= 1.0, label="loud") + fake_pyspiral.scan_log.clear() + text = stream.explain().text() + assert fake_pyspiral.scan_log == [] # nothing read + assert text == ( + "DynamicPodStream[loud] reads:\n" + f" source {source.source_id!r} (SpiralDBTableSource)\n" + " applied by the source: where subject_id='m1'\n" + " applied after reading: amplitude >= 1.0 (Filter[loud])" + ) + + def test_a_limit_is_applied_by_the_source(self, spiral): + source = _event(limit=2) + reading = source.filter(col("amplitude") >= 1.0).explain().sources[0] + assert reading.limit == 2 + assert reading.lines()[1] == " applied by the source: limit 2" + + def test_an_unrestricted_source_reads_its_whole_table(self): + stream = _units().filter(col("t") >= 1.0, label="late") + assert stream.explain().text() == ( + "DynamicPodStream[late] reads:\n" + " source 'units' (ArrowTableSource)\n" + " applied by the source: nothing (the whole table is read)\n" + " applied after reading: t >= 1.0 (Filter[late])" + ) + + def test_a_filter_below_an_operator_and_a_function_pod(self): + calls: list[int] = [] + + @function_pod(output_keys="doubled") + def double(t: float | None) -> float: + calls.append(1) + return 2 * (t or 0.0) + + filtered = _units().filter(col("t") >= 1.0, label="late") + stream = GroupBy("session")(double.pod(filtered.select_data_columns(["t"]))) + text = stream.explain().text() + assert calls == [] # no user code ran + assert text.splitlines()[1:] == [ + " source 'units' (ArrowTableSource)", + " applied by the source: nothing (the whole table is read)", + " applied after reading: t >= 1.0 (Filter[late])", + ] + + def test_several_sources_through_a_join(self): + stream = Join()(_units().filter(col("t") >= 1.0, label="late"), _probes()) + assert stream.explain().text().splitlines()[1:] == [ + " source 'probes' (ArrowTableSource)", + " applied by the source: nothing (the whole table is read)", + " applied after reading: rows without a match in 'units' are dropped (Join)", + " source 'units' (ArrowTableSource)", + " applied by the source: nothing (the whole table is read)", + " applied after reading: t >= 1.0 (Filter[late]); rows without a match " + "in 'probes' are dropped (Join)", + ] + + def test_a_job_node_walks_its_slot_to_the_bound_source(self): + job = PipelineJob(name="explain", database=InMemoryArrowDatabase()) + with job: + _units().filter(col("t") >= 1.0, label="late").drop_nulls( + ["rate", "t"], label="clean" + ) + text = job.nodes["clean"].explain().text() + assert text.splitlines()[1:] == [ + " source 'units' (ArrowTableSource)", + " applied by the source: nothing (the whole table is read)", + " applied after reading: t >= 1.0 (Filter[late]); no null in rate, t " + "(DropNulls[clean])", + ] + + def test_an_unbound_slot(self): + tag_schema, data_schema = _units().output_schema() + slot = SourceNode(name="units", tag_schema=tag_schema, data_schema=data_schema) + job = PipelineJob(name="unbound", database=InMemoryArrowDatabase()) + with job: + Filter(col("t") >= 1.0)(slot, label="late") + reading = job.nodes["late"].explain().sources[0] + assert not reading.bound + assert reading.lines() == [ + "slot 'units': no source bound", + " applied after reading: t >= 1.0 (Filter[late])", + ] + + +class TestSourcesThatCannotSay: + def test_a_cached_source(self): + cached = CachedSource(_units(), cache_database=InMemoryArrowDatabase()) + reading = cached.filter(col("t") >= 1.0).explain().sources[0] + assert not reading.known + assert reading.lines()[1] == ( + " applied by the source: not known for this source kind" + ) + + def test_a_raw_stream(self): + table = pa.table({"k": [1, 2], "v": [3, 4]}) + stream = Filter(col("v") > 3)(ArrowTableStream(table, tag_columns=["k"])) + reading = stream.explain().sources[0] + assert reading.kind == "ArrowTableStream" + assert not reading.known + + +class TestStepsThatDropRows: + def test_drop_nulls_names_in_name_order_and_the_no_argument_form(self): + named = _units().drop_nulls(["t", "rate"]).explain().sources[0].steps + assert [s.text for s in named] == ["no null in rate, t"] + every = _units().drop_nulls().explain().sources[0].steps + assert [s.text for s in every] == ["no null in any tag or data column"] + + def test_polars_filter_in_no_given_order(self): + a = PolarsFilter(predicates=[pl.col("t") > 1, pl.col("unit") == 3]) + b = PolarsFilter(predicates=[pl.col("unit") == 3, pl.col("t") > 1]) + assert a(_units()).explain().text() == b(_units()).explain().text() + + def test_semi_join_both_sides(self): + stream = SemiJoin()(_units(), _probes()) + by_name = {r.name: r for r in stream.explain().sources} + assert [s.text for s in by_name["units"].steps] == [ + "rows without a match in 'probes' are dropped" + ] + assert [s.text for s in by_name["probes"].steps] == [ + "its rows only choose rows of 'units' and do not flow on" + ] + + def test_merge_join(self): + stream = MergeJoin()(_units(), _probes()) + texts = {r.name: [s.text for s in r.steps] for r in stream.explain().sources} + assert texts["units"] == ["rows without a match in 'probes' are dropped"] + + def test_batch_drops_rows_only_when_asked(self): + assert _units().batch(2).explain().sources[0].steps == () + steps = Batch(2, drop_partial_batch=True)(_units()).explain().sources[0].steps + assert [s.text for s in steps] == ["a last partial batch is dropped"] + + def test_index_drops_rows_on_a_miss_unless_a_miss_raises(self): + table = pa.table( + {"k": [1, 2], "xs": [[1, 2], [3]]}, + schema=pa.schema( + [ + pa.field("k", pa.int64()), + pa.field("xs", pa.large_list(pa.int64()), nullable=False), + ] + ), + ) + source = ArrowTableSource( + table, tag_columns=["k"], tag_only_columns=True, source_id="lists" + ) + steps = Index("xs", 1)(source).explain().sources[0].steps + assert [s.text for s in steps] == [ + "rows whose 'xs' has no element 1 are dropped" + ] + assert ( + Index("xs", 1, fail_on_miss=True)(source).explain().sources[0].steps == () + ) + + def test_operators_that_drop_no_rows_are_not_listed(self): + stream = _units().select_data_columns(["t"]).map_tags({"unit": "u"}) + assert stream.explain().sources[0].steps == () + + +class TestNoOrderCounts: + def test_conditions_and_operands_in_any_order(self): + terms = [col("t") >= 1.0, col("unit").is_in([7, 3]), col("rate").is_not_null()] + texts = { + _units().filter(*order, label="f").explain().text() + for order in itertools.permutations(terms) + } + texts.add( + _units() + .filter((col("unit").is_in([3, 7])) & terms[2] & terms[0], label="f") + .explain() + .text() + ) + assert len(texts) == 1 + + def test_join_inputs_and_source_names_in_any_order(self): + texts = { + Join()(*order).explain().text().split("\n", 1)[1] + for order in itertools.permutations((_units(), _probes())) + } + assert len(texts) == 1 + + +class TestPlainData: + def test_fields_and_text(self): + explanation = _units().filter(col("t") >= 1.0).explain() + assert isinstance(explanation, Explanation) + assert str(explanation) == explanation.text() + (reading,) = explanation.sources + assert isinstance(reading, SourceReading) + assert reading.condition == Condition() + assert reading.limit is None + assert reading.steps == ( + Step(operator="Filter", label="Filter", text="t >= 1.0"), + ) + with pytest.raises(dataclasses.FrozenInstanceError): + reading.name = "x" # pyright: ignore[reportAttributeAccessIssue] + + def test_equal_pipelines_explain_equally(self): + assert ( + _units().filter(session="s1").explain() + == _units().filter(session="s1").explain() + ) + + +class TestPreview: + def test_a_filter_over_an_unrestricted_source(self): + header = _units().filter(col("t") >= 1.0).head().header() + assert header.endswith( + "applied by the source: nothing; after reading: t >= 1.0 " + "(the whole table is read)" + ) + + def test_a_filter_over_a_restricted_source(self, spiral): + stream = _event().where(subject_id="m1").filter(col("amplitude") >= 1.0) + assert ( + stream.head() + .header() + .endswith( + "applied by the source: where subject_id='m1'; after reading: " + "amplitude >= 1.0" + ) + ) + + def test_once_computed_the_line_stays(self): + stream = _units().filter(col("t") >= 1.0) + stream.run() + assert stream.head().header().endswith("(the whole table is read)") + + def test_no_line_elsewhere(self): + assert "applied by the source" not in _units().drop_nulls().head().header() + two_steps = _units().select_data_columns(["t"]).filter(col("t") >= 1.0) + assert "applied by the source" not in two_steps.head().header() + + +def test_explaining_a_job_writes_and_computes_nothing(): + database = InMemoryArrowDatabase() + job = PipelineJob(name="quiet", database=database) + with job: + _units().filter(col("t") >= 1.0, label="late") + for node in job.nodes.values(): + node.explain() + assert list(database.list_table_paths()) == [] + assert job.nodes["late"].head().status.value == "not_computed" + + +class TestReviewOfPr503: + """CodeRabbit's review of PR 503: each finding as a test.""" + + def test_a_pipelines_source_node_reads_as_unbound(self): + tag_schema, data_schema = _units().output_schema() + slot = SourceNode(name="units", tag_schema=tag_schema, data_schema=data_schema) + (reading,) = Filter(col("t") >= 1.0)(slot).explain().sources + assert not reading.bound + assert reading.lines() == [ + "slot 'units': no source bound", + " applied after reading: t >= 1.0 (Filter)", + ] + + @pytest.mark.parametrize( + ("first", "second", "expected"), + [ + ( + {"where": {"subject_id": "m1"}}, + {"where": {"subject_id": "m2"}}, + ["where subject_id='m1'", "where subject_id='m2'"], + ), + ( + {"where": {"subject_id": "m1"}}, + {}, + ["nothing (the whole table is read)", "where subject_id='m1'"], + ), + ({"limit": 1}, {"limit": 2}, ["limit 1", "limit 2"]), + ], + ids=["two_conditions", "condition_and_none", "two_limits"], + ) + def test_two_restrictions_of_one_table_are_two_readings( + self, spiral, first, second, expected + ): + def build(restriction: dict[str, Any]) -> SpiralDBTableSource: + source = ( + _event(limit=restriction["limit"]) + if "limit" in restriction + else _event() + ) + if "where" in restriction: + source = source.where(**restriction["where"]) + return source + + stream = SemiJoin()(build(first), build(second)) + applied = sorted( + r.lines()[1].removeprefix(" applied by the source: ") + for r in stream.explain().sources + ) + assert applied == expected + + @pytest.mark.parametrize( + "combine", + [ + lambda late: SemiJoin()(late, late.select_data_columns(["t"])), + lambda late: SemiJoin()( + late, late.select_data_columns(["t", "rate"]).select_data_columns(["t"]) + ), + lambda late: MergeJoin()( + late.select_data_columns(["t"]), late.select_data_columns(["rate"]) + ), + ], + ids=["semijoin_depths_0_1", "semijoin_depths_0_2", "merge_join_two_branches"], + ) + def test_a_step_reached_by_two_paths_is_listed_once(self, combine): + late = _units().filter(col("t") >= 1.0, label="late") + (reading,) = combine(late).explain().sources + assert [s.label for s in reading.steps].count("late") == 1 + + def test_shared_inputs_cost_one_visit_per_node(self): + stream = _units().filter(col("t") >= 1.0) + for _ in range(40): # 2**40 paths, 40 nodes + stream = SemiJoin()(stream, stream) + (reading,) = stream.explain().sources + assert reading.steps[0].operator == "Filter" + + def test_explain_is_on_every_stream_type(self): + # Through a parameter typed StreamProtocol: basedpyright checks the protocol + # declares explain() (it narrows an annotated variable to the value's class). + def explained(stream: StreamProtocol) -> Explanation: + return stream.explain() + + assert explained(_units().filter(col("t") >= 1.0)).sources[0].name == "units" + + +class _Loud(str): + """A ``str`` subclass whose ``__str__`` and ``__repr__`` are user code.""" + + def __str__(self) -> str: + raise AssertionError("explain() ran user code") + + def __repr__(self) -> str: + raise AssertionError("explain() ran user code") + + +class _LoudInt(int): + """An ``int`` subclass whose ``__repr__`` is user code.""" + + def __repr__(self) -> str: + raise AssertionError("explain() ran user code") + + +class _LoudObject: + """An object whose ``__str__`` and ``__repr__`` are user code.""" + + def __str__(self) -> str: + raise AssertionError("explain() ran user code") + + def __repr__(self) -> str: + raise AssertionError("explain() ran user code") + + +class _LoudDict(dict[str, object]): + """A ``dict`` subclass whose ``items()`` is user code.""" + + def items(self): # pyright: ignore[reportIncompatibleMethodOverride] # raises on purpose + raise AssertionError("explain() ran user code") + + +class _LoudMapping(Mapping[str, object]): + """A mapping whose every access is user code.""" + + def __getitem__(self, key: str) -> object: + raise AssertionError("explain() ran user code") + + def __iter__(self) -> Iterator[str]: + raise AssertionError("explain() ran user code") + + def __len__(self) -> int: + raise AssertionError("explain() ran user code") + + +class TestSecondReviewOfPr503: + """CodeRabbit's second review of PR 503.""" + + def test_polars_filter_text_runs_no_user_code(self): + op = PolarsFilter( + predicates=[pl.col("t") > 1, _Loud("t > 1")], + constraints={"session": _Loud("s1"), "unit": 3}, + ) + (step,) = op(_units()).explain().sources[0].steps + assert ( + step.text == 'session=<_Loud>, unit=3, <_Loud>, [(col("t")) > (dyn int: 1)]' + ) + + @pytest.mark.parametrize( + ("value", "shown"), + [ + (_Loud("s1"), "<_Loud>"), + (_LoudInt(3), "<_LoudInt>"), + (_LoudObject(), "<_LoudObject>"), + ("s1", "'s1'"), + (3, "3"), + (2.5, "2.5"), + (True, "True"), + (b"x", "b'x'"), + (None, "None"), + ], + ids=[ + "str_subclass", + "int_subclass", + "object", + "str", + "int", + "float", + "bool", + "bytes", + "none", + ], + ) + def test_a_constraint_value_is_written_only_by_a_builtin_repr(self, value, shown): + op = PolarsFilter(constraints={"session": value}) + assert op.rows_dropped_text(0, [], []) == f"session={shown}" + + @pytest.mark.parametrize( + ("predicate", "shown"), + [ + (_Loud("t > 1"), "<_Loud>"), + (_LoudObject(), "<_LoudObject>"), + ([True, False], ""), + ], + ids=["str_subclass", "object", "mask"], + ) + def test_a_predicate_is_written_only_by_polars(self, predicate, shown): + assert ( + PolarsFilter(predicates=[predicate]).rows_dropped_text(0, [], []) == shown + ) + + @pytest.mark.parametrize( + "constraints", + [_LoudDict(session="s1"), _LoudMapping(), {_Loud("session"): "s1"}], + ids=["dict_subclass", "mapping", "str_subclass_name"], + ) + def test_constraints_are_read_only_as_an_exact_dict(self, constraints): + op = PolarsFilter(constraints=constraints) + name = type(constraints).__name__ + assert op.rows_dropped_text(0, [], []) == f"<{name}>" + + def test_a_dict_pick_lists_its_misses(self): + source = DictSource( + [{"k": 1, "m": {"a": 1}}, {"k": 2, "m": {"b": 2}}], + tag_columns=["k"], + data_schema={"k": int, "m": dict[str, int]}, + tag_only_columns=True, + source_id="maps", + ) + (step,) = source.pick("m", "a").explain().sources[0].steps + assert step.text == "rows whose 'm' has no key 'a' are dropped" + + def test_a_slot_is_named_by_its_name_not_its_label(self): + tag_schema, data_schema = _units().output_schema() + slot = SourceNode( + name="units", tag_schema=tag_schema, data_schema=data_schema, label="shown" + ) + (reading,) = Filter(col("t") >= 1.0)(slot).explain().sources + assert reading.name == "units" + + +class _LoudName(str): + """A ``str`` subclass whose ``__repr__`` is user code.""" + + def __repr__(self) -> str: + raise AssertionError("explain() ran user code") + + +class _LoudIndex(int): + """An ``int`` subclass whose ``__repr__`` is user code.""" + + def __repr__(self) -> str: + raise AssertionError("explain() ran user code") + + +class TestReviewOfPr498: + """CodeRabbit's review of PR 498 at cb3e3e1c, where explain() is now reviewed.""" + + def test_a_join_of_one_input_drops_no_row(self): + assert Join()(_units()).explain().sources[0].steps == () + two = Join()(_units(), _probes()).explain().sources + assert all(len(r.steps) == 1 for r in two) + + @pytest.mark.parametrize( + ("make", "text"), + [ + ( + lambda: Pick(_LoudName("m"), _LoudName("a")), + "rows whose 'm' has no key 'a' are dropped", + ), + ( + lambda: Index(_LoudName("xs"), _LoudIndex(1)), + "rows whose 'xs' has no element 1 are dropped", + ), + ], + ids=["pick_str_subclasses", "index_subclasses"], + ) + def test_names_and_keys_are_written_without_user_code(self, make, text): + op = make() + op._mode = "map" # pyright: ignore[reportAttributeAccessIssue] # Pick's dict mode, as validation sets it + assert op.rows_dropped_text(0, [], []) == text + + @pytest.mark.parametrize( + ("other_tags", "left", "right"), + [ + ( + ["session"], + ["rows without a match in 'probes' are dropped"], + ["its rows only choose rows of 'units' and do not flow on"], + ), + ( + [], + [], + [ + "no tag is shared with 'units': its rows choose nothing and do not flow on" + ], + ), + ], + ids=["shared_tag", "no_shared_tag"], + ) + def test_a_semi_join_drops_rows_only_on_a_shared_tag(self, other_tags, left, right): + table = pa.table( + { + "probe_session": pa.array(["s1", "s2"], pa.large_string()), + "probe": pa.array(["imec0", "imec1"], pa.large_string()), + } + ) + if other_tags: + table = table.rename_columns(["session", "probe"]) + probes = ArrowTableSource( + table, + tag_columns=other_tags or ["probe_session"], + tag_only_columns=True, + source_id="probes", + ) + by_name = {r.name: r for r in SemiJoin()(_units(), probes).explain().sources} + assert [s.text for s in by_name["units"].steps] == left + assert [s.text for s in by_name["probes"].steps] == right + + def test_an_unbound_slot_keeps_its_steps_in_the_text(self): + tag_schema, data_schema = _units().output_schema() + slot = SourceNode(name="units", tag_schema=tag_schema, data_schema=data_schema) + text = str(_units_filter_over(slot).explain()) + assert "slot 'units': no source bound" in text + assert ( + "applied after reading: t >= 1.0 (Filter); no null in rate (DropNulls)" + in text + ) + + +def _units_filter_over(stream): + return DropNulls("rate")(Filter(col("t") >= 1.0)(stream)) + + +class TestSecondReviewOfPr498: + """CodeRabbit's review of PR 498 at ce5371ab.""" + + @pytest.mark.parametrize( + ("name", "shown"), + [(_LoudName("units"), "'units'"), ("units", "'units'")], + ids=["str_subclass", "str"], + ) + def test_a_slot_name_is_written_without_user_code(self, name, shown): + tag_schema, data_schema = _units().output_schema() + slot = SourceNode(name=name, tag_schema=tag_schema, data_schema=data_schema) + text = str(Filter(col("t") >= 1.0)(slot).explain()) + assert f"slot {shown}: no source bound" in text diff --git a/tests/test_hashing/golden/cases.py b/tests/test_hashing/golden/cases.py index 8a9398bed..d1758477a 100644 --- a/tests/test_hashing/golden/cases.py +++ b/tests/test_hashing/golden/cases.py @@ -2616,6 +2616,112 @@ def pipeline_polars_filter_expr_job() -> dict[str, Any]: return out +def _filter_conditions() -> dict[str, Any]: + """Build one representative ``Filter`` condition of each kind, keyed by name.""" + from datetime import date, datetime, timezone + + from orcapod.types import Condition, col + + return { + "eq_keyword": Condition.of(cohort="a"), + "eq_int": col("x") == 5, + "eq_float": col("x") == 0.5, + "eq_bool": col("x") == True, # noqa: E712 # the value True is the case + "eq_negative_zero": col("x") == -0.0, + "eq_nan": col("x") == float("nan"), + "ne_string": col("s") != "abc", + "lt_bytes": col("b") < b"\x01", + "le_date": col("d") <= date(2024, 12, 31), + "gt_datetime_aware": col("t") > datetime(2024, 1, 1, tzinfo=timezone.utc), + "ge_datetime_naive": col("t") >= datetime(2024, 1, 1, 9, 30), + "is_in_ints": col("x").is_in([3, 7]), + "between_floats": col("x").between(0.5, 2.0), + "is_null": col("x").is_null(), + "is_not_null": col("x").is_not_null(), + "struct_field": col("info").field("kind") == "a", + "column_operand": col("a") < col("b"), + "or": (col("s") == "a") | (col("x") < 0.5), + "not": ~col("x").is_in([3, 7]), + "several": Condition.of(col("x") > 0, col("s").is_in(["a", "b"]), cohort="a"), + } + + +# Only Filter puts a condition's canonical form into an identity, so these hashes are as +# provisional as Filter is (ITL-1374), although the case builds no operator. +@case("semantic", "filter_condition", provisional=("Filter",)) +def semantic_filter_conditions() -> dict[str, Any]: + """Record the semantic hash of each representative condition's canonical form.""" + hasher = _ctx().semantic_hasher + return { + k: hasher.hash_object(c.canonical_form()).to_string() + for k, c in _filter_conditions().items() + } + + +@case("pipeline", "filter", provisional=("Filter",)) +def pipeline_filter() -> dict[str, Any]: + """Record filter streams: an equality, several terms, and or / not.""" + from orcapod.types import col + + out = _prefixed("keyword", stream_summary(_grouped().filter(cohort="a"))) + out.update( + _prefixed( + "terms", + stream_summary( + _grouped().filter( + col("weight") > 20.0, col("subject").is_in(["s1", "s3"]) + ) + ), + ) + ) + out.update( + _prefixed( + "tree", + stream_summary( + _grouped().filter((col("cohort") == "b") | ~(col("weight") >= 22.0)) + ), + ) + ) + return out + + +@case("pipeline", "filter_job", provisional=("Filter",)) +def pipeline_filter_job() -> dict[str, Any]: + """Record a job with a filter upstream of a join and a function pod.""" + from orcapod import PipelineJob + from orcapod.databases import InMemoryArrowDatabase + from orcapod.operators import Join + from orcapod.types import col + + db = InMemoryArrowDatabase() + job = PipelineJob(name="golden_filter_step_job", database=db) + with job: + older = _subjects().filter(col("age") > 3, label="older") + joined = Join(label="joined")(older, _scans()) + golden_adjust.pod(joined, label="adjust") + job.run() + + out: dict[str, Any] = {} + for label in sorted(job.nodes): + out.update(_prefixed(f"node[{label}]", stream_summary(job.nodes[label]))) + paths = sorted(db.list_sources()) + out["table_paths"] = ["/".join(p) for p in paths] + for path in paths: + name = "/".join(path) + records = db.get_all_records(path, record_id_column="__golden_record_id") + assert records is not None + if "__input_data_hash" in records.column_names and "_result" in path: + # Result-table record ids are UUIDv7 (volatile); pin the lookup key instead. + out[f"table[{name}].input_data_hashes"] = sorted( + _jsonable(v) for v in records.column("__input_data_hash").to_pylist() + ) + else: + out[f"table[{name}].record_ids"] = sorted( + _jsonable(v) for v in records.column("__golden_record_id").to_pylist() + ) + return out + + REJOIN_ROWS = [ { "cohort": "a", diff --git a/tests/test_hashing/golden/data/v1/provisional/pipeline.json b/tests/test_hashing/golden/data/v1/provisional/pipeline.json index 6d42a94ad..780427e9b 100644 --- a/tests/test_hashing/golden/data/v1/provisional/pipeline.json +++ b/tests/test_hashing/golden/data/v1/provisional/pipeline.json @@ -51,6 +51,114 @@ ], "default_source_ids.as_source[function_node].source_id": "derived:semantic_v1:7b37c93054a760ba9d60aceaae030ee2969beef3c900ecbf708fdd47e22d1f04", "default_source_ids.as_source[operator_node].source_id": "derived:semantic_v1:c34547483156c17c378a359200d07f15ccb5c1009651b21571d156027d5d6107", + "filter.keyword.content_hash": "semantic_v1:e2d9164d19767ee3cefae25201299495d6101f420d19503f07acca1663eef2e6", + "filter.keyword.pipeline_hash": "semantic_v1:502dbd4f7c834033377ef48af654bbae4e4f9d3262bfd5c0a1bafc46ab7dcf53", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "row_0", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "cohorts", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s1\"}].data_hash": "arrow_v1:000002c734791b7452bb2affc60031491e7541bb53fb971cf3ef8b9af919eb0bf1f56e", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s2\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "row_1", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s2\"}]._tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "cohorts", + "filter.keyword.row[{\"cohort\":\"a\",\"subject\":\"s2\"}].data_hash": "arrow_v1:00000252e4f32a133cd6a8813f816e08b6bde1cdb467baa95d026fc41c5672b6b98110", + "filter.keyword.system_tag_columns": [ + "_tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192", + "_tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192" + ], + "filter.terms.content_hash": "semantic_v1:6f7f1a8acb164dd524bf3e6275177c2b9a7bbcaa01011aa3a59246fd70ec6a5e", + "filter.terms.pipeline_hash": "semantic_v1:88a56dc2d23890062f13a955b2cdf4d48f509217241ca2901659144f14ad7083", + "filter.terms.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "row_0", + "filter.terms.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "cohorts", + "filter.terms.row[{\"cohort\":\"a\",\"subject\":\"s1\"}].data_hash": "arrow_v1:000002c734791b7452bb2affc60031491e7541bb53fb971cf3ef8b9af919eb0bf1f56e", + "filter.terms.system_tag_columns": [ + "_tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192", + "_tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192" + ], + "filter.tree.content_hash": "semantic_v1:eeacecd8a9281bdca3e9b30f0adf06cd5df580e27ca9798a7992dc92baa1269f", + "filter.tree.pipeline_hash": "semantic_v1:5f3708a20b6c8847675f9fb6e510a4dd7354803d49da81a02c03d0b68deb8203", + "filter.tree.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "row_0", + "filter.tree.row[{\"cohort\":\"a\",\"subject\":\"s1\"}]._tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "cohorts", + "filter.tree.row[{\"cohort\":\"a\",\"subject\":\"s1\"}].data_hash": "arrow_v1:000002c734791b7452bb2affc60031491e7541bb53fb971cf3ef8b9af919eb0bf1f56e", + "filter.tree.row[{\"cohort\":\"b\",\"subject\":\"s3\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "row_2", + "filter.tree.row[{\"cohort\":\"b\",\"subject\":\"s3\"}]._tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "cohorts", + "filter.tree.row[{\"cohort\":\"b\",\"subject\":\"s3\"}].data_hash": "arrow_v1:0000025f33a2f5bf3e956edfb7ca628b6871f52b7bbf788d5a3774ddffe300d7d4aff5", + "filter.tree.system_tag_columns": [ + "_tag_source_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192", + "_tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192" + ], + "filter_job.node[adjust].content_hash": "semantic_v1:5f3c8e5be360cbc96b6a091cb818d563005546677d85671b5ed8a54b1bb9c141", + "filter_job.node[adjust].pipeline_hash": "semantic_v1:1b55d0d2cce6651fc52aed3a13227619ae3ba68ecd21f99ebfde5d68e56f4fa2", + "filter_job.node[adjust].row[{\"subject\":\"s2\"}]._tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0": "row_1", + "filter_job.node[adjust].row[{\"subject\":\"s2\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1": "row_1", + "filter_job.node[adjust].row[{\"subject\":\"s2\"}]._tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0": "scans", + "filter_job.node[adjust].row[{\"subject\":\"s2\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1": "subjects", + "filter_job.node[adjust].row[{\"subject\":\"s2\"}].data_hash": "arrow_v1:0000023565098d1a88ecd75dbc8ddc4900dc8304e066dc0c889114a2a41e2fe495fc30", + "filter_job.node[adjust].system_tag_columns": [ + "_tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0", + "_tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0", + "_tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1", + "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1" + ], + "filter_job.node[joined].content_hash": "semantic_v1:d6f4cf4023915629dfe1d999e9d751c2854cce66b385e47b40061562a59f8364", + "filter_job.node[joined].pipeline_hash": "semantic_v1:60e0cbd067981a11e617fbe1267b4f2d5a111f26c6f9aec8b11f42825c86d5fe", + "filter_job.node[joined].row[{\"subject\":\"s2\"}]._tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0": "row_1", + "filter_job.node[joined].row[{\"subject\":\"s2\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1": "row_1", + "filter_job.node[joined].row[{\"subject\":\"s2\"}]._tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0": "scans", + "filter_job.node[joined].row[{\"subject\":\"s2\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1": "subjects", + "filter_job.node[joined].row[{\"subject\":\"s2\"}].data_hash": "arrow_v1:0000026b8369e60be10e43dd72a0be4e8d93a992f827cd6baab33909331dcdaeea8b64", + "filter_job.node[joined].system_tag_columns": [ + "_tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0", + "_tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4:0", + "_tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1", + "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc::57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63:1" + ], + "filter_job.node[older].content_hash": "semantic_v1:f82ae9dedfd2b0a03a9b5f7ac8b185f24f686bdf0ffb1206800c4829804e8763", + "filter_job.node[older].pipeline_hash": "semantic_v1:57d91b55ecd554430bf88083b7c81a30ac5255c9eecaf8a08f43185350e3bb63", + "filter_job.node[older].row[{\"subject\":\"s2\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "row_1", + "filter_job.node[older].row[{\"subject\":\"s2\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "subjects", + "filter_job.node[older].row[{\"subject\":\"s2\"}].data_hash": "arrow_v1:000002338ce8710f5ecb156a72c8446651adb7b0c21635d0aa92d298f09da56faed0f8", + "filter_job.node[older].row[{\"subject\":\"s3\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "row_2", + "filter_job.node[older].row[{\"subject\":\"s3\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "subjects", + "filter_job.node[older].row[{\"subject\":\"s3\"}].data_hash": "arrow_v1:0000023401f1ce40c8cfdd6e4f343d7ffdcd51c1f0521f44cf6030e27e1ca0da154616", + "filter_job.node[older].system_tag_columns": [ + "_tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc", + "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc" + ], + "filter_job.node[scans].content_hash": "semantic_v1:064d30fae9656480dcc8a84b1d0b402bd5b9108ad77991934f37539899c055d1", + "filter_job.node[scans].pipeline_hash": "semantic_v1:47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4", + "filter_job.node[scans].row[{\"subject\":\"s1\"}]._tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4": "row_0", + "filter_job.node[scans].row[{\"subject\":\"s1\"}]._tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4": "scans", + "filter_job.node[scans].row[{\"subject\":\"s1\"}].data_hash": "arrow_v1:000002ef2b37a1979bd734849c241456c50e96644db0ba5a7b25ecb84cee278e6686f2", + "filter_job.node[scans].row[{\"subject\":\"s2\"}]._tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4": "row_1", + "filter_job.node[scans].row[{\"subject\":\"s2\"}]._tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4": "scans", + "filter_job.node[scans].row[{\"subject\":\"s2\"}].data_hash": "arrow_v1:00000210b14e22145ce1d5f71e190ade4ca03ba523ad98d8749ea7beef3c15dd749c20", + "filter_job.node[scans].system_tag_columns": [ + "_tag_source_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4", + "_tag_record_id::47b9cffa37406b8ead8ec58fd3c2b95ff5454980c20022379d8d62dd6f044fd4" + ], + "filter_job.node[subjects].content_hash": "semantic_v1:747a4d3d3f9e073009880257daf4929acfdd109760c02e89f410589cd285893a", + "filter_job.node[subjects].pipeline_hash": "semantic_v1:65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc", + "filter_job.node[subjects].row[{\"subject\":\"s1\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "row_0", + "filter_job.node[subjects].row[{\"subject\":\"s1\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "subjects", + "filter_job.node[subjects].row[{\"subject\":\"s1\"}].data_hash": "arrow_v1:000002d1c5b49de38ef6efc552c2a47b8ab59dd267f8eb55d91814edee99b1b52acc65", + "filter_job.node[subjects].row[{\"subject\":\"s2\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "row_1", + "filter_job.node[subjects].row[{\"subject\":\"s2\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "subjects", + "filter_job.node[subjects].row[{\"subject\":\"s2\"}].data_hash": "arrow_v1:000002338ce8710f5ecb156a72c8446651adb7b0c21635d0aa92d298f09da56faed0f8", + "filter_job.node[subjects].row[{\"subject\":\"s3\"}]._tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "row_2", + "filter_job.node[subjects].row[{\"subject\":\"s3\"}]._tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc": "subjects", + "filter_job.node[subjects].row[{\"subject\":\"s3\"}].data_hash": "arrow_v1:0000023401f1ce40c8cfdd6e4f343d7ffdcd51c1f0521f44cf6030e27e1ca0da154616", + "filter_job.node[subjects].system_tag_columns": [ + "_tag_source_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc", + "_tag_record_id::65dce1d2f45e53ee8ca443ce84a42415855cb65e9aaf39fec732bfce77d818fc" + ], + "filter_job.table[golden_filter_step_job/_result/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/rev1/rdb_v1].input_data_hashes": [ + "arrow_v1:0000026b8369e60be10e43dd72a0be4e8d93a992f827cd6baab33909331dcdaeea8b64" + ], + "filter_job.table[golden_filter_step_job/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/schema:1b55d0d2cce6651fc52aed3a13227619ae3ba68ecd21f99ebfde5d68e56f4fa2/pdb_v1].record_ids": [ + "arrow_v1:0000020ff0c14f17479c11afea028ae9f68e6d6288c3ef0940b15054bf72c4773c3b36" + ], + "filter_job.table_paths": [ + "golden_filter_step_job/_result/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/rev1/rdb_v1", + "golden_filter_step_job/golden_adjust/dff0617f9fe7bc2e6d071f4da43376bf59044ed9929bcce9812e9917bc95d39c/v0/python.function.v1/schema:1b55d0d2cce6651fc52aed3a13227619ae3ba68ecd21f99ebfde5d68e56f4fa2/pdb_v1" + ], "group_by.content_hash": "semantic_v1:7e6b6e3d8289d803f1cb1a7d0e912105e2591d3216140eacab1a197d39f4a637", "group_by.pipeline_hash": "semantic_v1:562c181244bf34d6d60fd1d00cae54a85855ea2d0a50a5354a388bd441370c20", "group_by.row[{\"cohort\":\"a\"}]._tag_record_id::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192::d568cb5cf0644ff50a49f2af3cb5b806e93678cbecc5999c5a8dd525ea07f192": "group_v1:9be3abf473e589e83e5229ad28484593860af85bd0d2592ca879add89a656125", diff --git a/tests/test_hashing/golden/data/v1/provisional/semantic.json b/tests/test_hashing/golden/data/v1/provisional/semantic.json index 4c6acc249..786f6b4e1 100644 --- a/tests/test_hashing/golden/data/v1/provisional/semantic.json +++ b/tests/test_hashing/golden/data/v1/provisional/semantic.json @@ -1,4 +1,24 @@ { + "filter_condition.between_floats": "semantic_v1:33396d9bd6bb6d3d24866d850a824f813ec4e4e8be05701ffc742baa0bcf2b66", + "filter_condition.column_operand": "semantic_v1:872ad1f34eb5c59ee138eacaf739cd49cfcb0112c3f2e128fd691c3585834ea0", + "filter_condition.eq_bool": "semantic_v1:8a345333440f7ed2baaf81cd0ed0529dffc003d595820add57c969b4a8e61739", + "filter_condition.eq_float": "semantic_v1:850076ef494ea06059859a26d8a7589b235ac0aa58c5dfd3344dbdb47862cf04", + "filter_condition.eq_int": "semantic_v1:3c22ccf287d4413c5625d778afe60a49139d8e13854d616538cb306861de5ecf", + "filter_condition.eq_keyword": "semantic_v1:ad7a2fcc1144b8f4456a9b796899e71ee4f8a6fb0131d05a2001e68321704382", + "filter_condition.eq_nan": "semantic_v1:f5d7f0be2a4e74e42c89c4d832e292a761e435b1bb1112aa9e1b078deb5a807f", + "filter_condition.eq_negative_zero": "semantic_v1:5d32b7b0f34bb51ecfe677c6c43393ff0d7b4dcfc083e23a43d77cb75b4e0912", + "filter_condition.ge_datetime_naive": "semantic_v1:807bfd2da597091314467d4dfd6f5f644de8b46c39007de72bbf90a8d8b89760", + "filter_condition.gt_datetime_aware": "semantic_v1:aa1d81d396033259645a995b2d490a4a89c2e4668ee224c874ab22c7204632c7", + "filter_condition.is_in_ints": "semantic_v1:b1b8616bdbeb770caf056e3ceb65b4b5bad4cc044fbac44ed4b252a8b2e95075", + "filter_condition.is_not_null": "semantic_v1:1d9870a5d898b82ec948991ca476f350e239f66cef42b4b3f240cd7fa0499bc3", + "filter_condition.is_null": "semantic_v1:3f02393ff4c6752e25bf458241da3182e092219c32be27136da58ab3b916bdfe", + "filter_condition.le_date": "semantic_v1:3b04a42fedc6b36cc2d40cb77f03b3c6814062d4e3054750012976091965b755", + "filter_condition.lt_bytes": "semantic_v1:abab9c65371e36250ca4db542145d1006ca8b575b6fbca85f5d038bc8389389d", + "filter_condition.ne_string": "semantic_v1:360ad148b2cd1e7bddfe2f8fcc453fe828fa73fa9787ba6cc0a687201eb0372e", + "filter_condition.not": "semantic_v1:4f4fccd0023d23cd447ae1fa931d3bb2c41cb080e4d72bedd85b12868616b07f", + "filter_condition.or": "semantic_v1:c6f7c11875cb029a95b31527e7772eb869d80a749b4a9230ae2631d0e6dfdeb5", + "filter_condition.several": "semantic_v1:17afe1ae038a88843ff1ea5749d76179e08a220f5186f6125d5011c430685db4", + "filter_condition.struct_field": "semantic_v1:61a53045be33e2bd27c095920a4986d656582bc41e9202984bad24fc2640586e", "polars_expr.and_two_columns": "polars_expr_v1:f8d1228cb5a4f9ca281f2918acc70ac9067052301c4784ec205ed71d6648afd7", "polars_expr.eq_string": "polars_expr_v1:64fbdf549ede833eed74ee19dd1884292576534c215bfdb2521ce16df514132a", "polars_expr.gt_datetime_utc": "polars_expr_v1:b791db9b35617d6296304cc8eda154da2fe7049565b9d0e209c9a39ac731b603", diff --git a/tests/test_hashing/golden/test_golden_store.py b/tests/test_hashing/golden/test_golden_store.py index bd4af5864..bf4a8a616 100644 --- a/tests/test_hashing/golden/test_golden_store.py +++ b/tests/test_hashing/golden/test_golden_store.py @@ -1386,7 +1386,8 @@ def test_the_repository_cases_declare_exactly_the_measured_cases() -> None: """The cases that depend on a provisional operator, source or library value type, measured for ITL-1266, ITL-1279, ITL-1324 and ITL-1331 (docs/dev/scripts/itl_1279/measure_relocation.py), plus the two canonical schema - form cases of ITL-640 and the ``Rejoin`` cases of ITL-1336, and no other. A split case is + form cases of ITL-640, the ``Rejoin`` cases of ITL-1336 and the ``Filter`` cases of + ITL-1382, and no other. A split case is listed once: its provisional part. No case declares a ``PollingSource`` (ITL-1314).""" declared = { (group, name): names @@ -1438,6 +1439,10 @@ def test_the_repository_cases_declare_exactly_the_measured_cases() -> None: # Rejoin, pinned once PR 454 and PR 456 had set the golden files (ITL-1336). ("pipeline", "rejoin"): ("PolarsFilter", "Rejoin"), ("pipeline", "rejoin_job"): ("Rejoin",), + # Filter (ITL-1374, ITL-1382): a condition's canonical form, filter streams, a job. + ("semantic", "filter_condition"): ("Filter",), + ("pipeline", "filter"): ("Filter",), + ("pipeline", "filter_job"): ("Filter",), ("pipeline", "rejoin_job_async"): ("Rejoin",), ("pipeline", "rejoin_arrangement"): ("Rejoin",), }