From 428de6ad134d8f0632cb37d3031e2e3a5a9667df Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 23:30:33 -0800 Subject: [PATCH 1/4] feat(operators): Rejoin matches on every shared column and never refuses on data (ITL-1355) Rejoin is now an inner join on every column its inputs share: the system-tag columns, a tag several inputs have, the source info of a shared data-tag and the data context, compared as Join compares keys (NaN equals NaN, -0.0 equals 0.0). A null system tag matches nothing; in any other shared column a null equals a null. A row that matches nothing is left out. The four refusals that read the rows are gone: two rows of one origin row, a null system tag, rows of different data contexts, and a shared column that differs bit for bit. Rows of one origin row that differ in another shared column are left out and named by the new RejoinDifferingColumnWarning, once per operator and set of columns. System tags are assumed unique; repeated ones pair in row order, each row at most once. A shared column keeps the values of the first input that has it, in the canonical input order (pipeline hash; argument order on equal hashes). Rows are matched on the system tags first, as before, and those pairs are then filtered, so every input Rejoin accepted before gives the same rows in the same order, with the same values, types and hashes. Refusals read from the inputs' columns stay: system-tag column names, a shared column's Arrow type, overlapping data columns. Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 33 +- CLAUDE.md | 33 +- changelog.d/ITL-1355.md | 27 + docs/concepts/operators.md | 69 ++- src/orcapod/core/operators/rejoin.py | 360 +++++++---- src/orcapod/core/streams/base.py | 8 +- src/orcapod/errors.py | 16 + .../operators/test_async_sync_equivalence.py | 77 ++- tests/test_core/operators/test_rejoin.py | 584 ++++++++++++++---- 9 files changed, 926 insertions(+), 281 deletions(-) create mode 100644 changelog.d/ITL-1355.md diff --git a/.zed/rules b/.zed/rules index 74bb0a724..6671e0f11 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1490,17 +1490,28 @@ data. The rules: - Join requires non-overlapping data columns; raises InputValidationError on collision. - `Rejoin` (provisional, developer, November 21, 2026, ITL-1336) is the operator a diamond (one stream split into branches, then put back together) is expected to use; `Join` is - unchanged and still extends every input's system-tag names. Rejoin matches EVERY system-tag - column and keeps those columns unchanged (a result row has its origin row's provenance): - every input that states its system-tag columns states the same ones (a branch through - `Join`, `GroupBy` or `Batch` is refused); an input that states none is checked on its table - when computed. At most one row per origin row in each input (a first rule, refused naming the - input and the values); a null system-tag value is refused; a shared user tag, and every - system tag Polars matched, must agree on matched rows bit for bit (so the result never - follows argument order); the inputs' rows must share one data context, read from the - rows, which the result keeps (rows of another are refused; some operators return rows - in the default context, ITL-1339); data columns disjoint; N-ary and commutative; identity - `"Rejoin"`; async is the barrier, which rebuilds each input in its rows' data context. + unchanged and still extends every input's system-tag names. Rejoin keeps the system-tag + columns unchanged (a result row has its origin row's provenance): every input that states + its system-tag columns states the same ones (a branch through `Join`, `GroupBy` or `Batch` + is refused); an input that states none is checked on its table when computed. It is an + inner join on EVERY column its inputs share (developer, November 22, 2026, ITL-1355): the + system tags, a shared user tag, a shared data-tag's source info and the data context, + with `Join`'s equality (NaN equals NaN, `-0.0` equals `0.0`); a null system tag matches + nothing, a null in any other shared column equals a null (on purpose unlike `Join`, + where a null tag key matches nothing). Rejoin never refuses on what + rows hold, only on what the inputs' columns show (system-tag names, a shared column's + Arrow type, disjoint data columns): a row that matches nothing is left out, and rows of + one origin row that differ in another shared column raise `RejoinDifferingColumnWarning` + once per operator and set of columns. System tags are assumed unique (no check reads the + rows; repeated ones pair in row order, arrival order on the async path, each row at most + once). A shared column keeps the + values of the first input that has it, in the canonical input order (by pipeline hash; + equal hashes stay in argument order, which only the bits of equal floats can follow). The + rows are matched on the system tags first, as before ITL-1355, and the pairs filtered, so + inputs whose shared columns agree give the same rows in the same order. The result's data + context is read from its rows (some operators return rows in the default context, + ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which + rebuilds each input in its rows' data context. - `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars decides which rows match, and every output column is taken from the input tables by row number (`take`), so every value is the input's, bit for bit (they used to carry every column diff --git a/CLAUDE.md b/CLAUDE.md index a60459f2e..2d8577912 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1534,17 +1534,28 @@ data. The rules: - Join requires non-overlapping data columns; raises `InputValidationError` on collision. - `Rejoin` (provisional, developer, November 21, 2026, ITL-1336) is the operator a diamond (one stream split into branches, then put back together) is expected to use; `Join` is - unchanged and still extends every input's system-tag names. Rejoin matches EVERY system-tag - column and keeps those columns unchanged (a result row has its origin row's provenance): - every input that states its system-tag columns states the same ones (a branch through - `Join`, `GroupBy` or `Batch` is refused); an input that states none is checked on its table - when computed. At most one row per origin row in each input (a first rule, refused naming the - input and the values); a null system-tag value is refused; a shared user tag, and every - system tag Polars matched, must agree on matched rows bit for bit (so the result never - follows argument order); the inputs' rows must share one data context, read from the - rows, which the result keeps (rows of another are refused; some operators return rows - in the default context, ITL-1339); data columns disjoint; N-ary and commutative; identity - `"Rejoin"`; async is the barrier, which rebuilds each input in its rows' data context. + unchanged and still extends every input's system-tag names. Rejoin keeps the system-tag + columns unchanged (a result row has its origin row's provenance): every input that states + its system-tag columns states the same ones (a branch through `Join`, `GroupBy` or `Batch` + is refused); an input that states none is checked on its table when computed. It is an + inner join on EVERY column its inputs share (developer, November 22, 2026, ITL-1355): the + system tags, a shared user tag, a shared data-tag's source info and the data context, + with `Join`'s equality (NaN equals NaN, `-0.0` equals `0.0`); a null system tag matches + nothing, a null in any other shared column equals a null (on purpose unlike `Join`, + where a null tag key matches nothing). Rejoin never refuses on what + rows hold, only on what the inputs' columns show (system-tag names, a shared column's + Arrow type, disjoint data columns): a row that matches nothing is left out, and rows of + one origin row that differ in another shared column raise `RejoinDifferingColumnWarning` + once per operator and set of columns. System tags are assumed unique (no check reads the + rows; repeated ones pair in row order, arrival order on the async path, each row at most + once). A shared column keeps the + values of the first input that has it, in the canonical input order (by pipeline hash; + equal hashes stay in argument order, which only the bits of equal floats can follow). The + rows are matched on the system tags first, as before ITL-1355, and the pairs filtered, so + inputs whose shared columns agree give the same rows in the same order. The result's data + context is read from its rows (some operators return rows in the default context, + ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which + rebuilds each input in its rows' data context. - `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars decides which rows match, and every output column is taken from the input tables by row number (`take`), so every value is the input's, bit for bit (they used to carry every column diff --git a/changelog.d/ITL-1355.md b/changelog.d/ITL-1355.md new file mode 100644 index 000000000..48a55c30a --- /dev/null +++ b/changelog.d/ITL-1355.md @@ -0,0 +1,27 @@ +### Changed + +- **`Rejoin` matches rows on every column its inputs share and no longer refuses on what + rows hold** (ITL-1355). It is an inner join on the system-tag columns, a tag several + inputs have, the source info of a shared data-tag and the data context, compared as + `Join` compares its keys (NaN equals NaN, `-0.0` equals `0.0`; a null system tag matches + nothing, a null in any other shared column equals a null). A row that matches nothing is + left out. Behaviour change: inputs that `Rejoin` refused with `InputValidationError` now + give fewer rows instead: + - a shared tag, or a shared data-tag's source info, that differs on rows of one origin + row: those rows are left out, and a new `RejoinDifferingColumnWarning` (from + `orcapod.errors`) names the columns, once per operator and set of columns; + - rows of different data contexts: they match nothing (the same warning names the data + context), and each result row keeps its own data context; + - a null in a system-tag column: the row matches nothing; + - equal values in different bits (`-0.0` and `0.0`, NaNs of different payloads): they + match, and the shared column keeps the values of the first input that has it, in + Rejoin's canonical input order (by pipeline hash; inputs with equal pipeline hashes + stay in argument order); + - an input holding two rows of one origin row: no longer checked. System tags are + assumed unique, as every source makes them; repeated ones pair in row order, each row + at most once. + + `Rejoin` still refuses what the inputs' columns show: system-tag columns that differ or + are absent, a shared column whose Arrow type differs, overlapping data columns. For every + input it accepted before, the result is unchanged: the same rows in the same order, the + same values, types and hashes. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 46cd64c99..9bef3d055 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -208,24 +208,40 @@ The rules: input whose schema states none (a raw stream without system tags, or a node of a loaded job downstream of a function node, whose saved schema holds none) is checked when the rejoin is computed, on its rows, by the same rule. -- **One row per origin row.** Rows are matched on every system-tag column. A first rule, - deliberate and open to relaxing later: each input holds at most one row of an origin row, - so pairing is one to one; an input with two rows of one origin row is refused, naming the - input and the system-tag values. No operator that keeps system tags duplicates rows today. -- **Shared tags agree, bit for bit.** A user tag present in several inputs must hold the - same value on matched rows, bit for bit (`-0.0` is not `0.0`, NaNs of different payloads - differ), so the result never depends on the order of the inputs; otherwise Rejoin refuses, - naming the tag. A tag of one input only is kept. -- **Provenance is never null, and exact.** An input with a null in a system-tag column is - refused, naming the column. Matched system-tag values are compared bit for bit too, like - shared tags. -- **One data context.** The inputs' rows must be of one data context; the result keeps - it, and rows of different data contexts are refused. Only the default data context +- **An inner join on every shared column.** Rows are put together when they are equal in + every column the inputs share: every system-tag column (so they come from one origin + row), a user tag several inputs have, the source info of a data-tag several inputs have, + and the data context. A row that matches nothing is left out. Rejoin refuses nothing for + what the rows hold: its only refusals are read from the inputs' columns (their system-tag + columns, a shared column's Arrow type, overlapping data columns). +- **Join's equality.** Values are compared as `Join` compares its keys: NaN equals NaN and + `-0.0` equals `0.0`. A null system tag matches nothing, because provenance is never null. + In any other shared column a null equals a null: two rows of one origin row that both hold + no value agree. That differs from `Join` on purpose, where a null tag key matches nothing. +- **A changed shared column is a non-match.** When two branches hold different values in a + shared column on rows of one origin row (two branches each add a tag `run` with different + values, or change a tag's value), those rows are left out, and Rejoin names the columns in + a `RejoinDifferingColumnWarning` (from `orcapod.errors`), once per operator and set of + columns. To keep the rows, drop or rename the column in one branch before the rejoin + (`drop_tag_columns`, `map_tags`). +- **Unique system tags.** System tags are assumed unique in each input, as every source + makes them, so each row matches at most once; nothing reads the rows to check it. Should + an input repeat an origin row, each row still matches at most once: among the rows equal + in every shared column, the first of one input pairs with the first of the other, the + second with the second, in row order (on the async path, the order the rows arrived in). +- **The first input's values.** A shared column is kept once, with the values of the first + input that has it. Rejoin takes its inputs in a canonical order, by pipeline hash, so the + result does not follow the order of the arguments; inputs with equal pipeline hashes (two + branches of the same structure) stay in argument order. Only the bits of values that are + equal but not identical (`-0.0` and `0.0`, NaNs of different payloads) can follow it: no + row, hash or identity does. A tag of one input only is kept. +- **Data contexts.** The data context is one of the shared columns: rows of different data + contexts match nothing, and each result row keeps its own. Only the default data context ships, so this matters only for a stream built in another one. A known limitation (ITL-1339): some operators (`PolarsFilter` and `MergeJoin`, likely `Join` and `SemiJoin` too) return their rows in the default data context whatever their input's, - so in another data context a branch through one of them is refused beside a branch - that kept its context. + so in another data context the rows of a branch through one of them match nothing + beside a branch that kept its context. - **Data columns are disjoint**, as in `Join`; a data-tag present in several inputs is one column. - **Different sources give nothing.** Two sources with the same schema have the same @@ -241,6 +257,27 @@ print(units.select_data_columns(["rate"]).rejoin(other.select_data_columns(["dep # 0 ``` +Two branches that set a shared tag to different values match nothing, with the warning: + +```python +import warnings + +from orcapod.errors import RejoinDifferingColumnWarning + +first_run = units.select_data_columns(["rate"]).add_tags(run=1) +second_run = units.select_data_columns(["depth"]).add_tags(run=2) +with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + print(first_run.rejoin(second_run).as_table().num_rows) +print([w.category.__name__ for w in caught if w.category is RejoinDifferingColumnWarning]) +# 0 +# ['RejoinDifferingColumnWarning'] + +same_run = units.select_data_columns(["depth"]).add_tags(run=1) +print(first_run.rejoin(same_run).as_table().num_rows) +# 3 +``` + !!! note "Provisional" `Rejoin` is a provisional operator (ITL-1336): building one issues a `ProvisionalHashWarning`, and its identity, so the hashes and stored paths of its @@ -968,7 +1005,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) | -| `Rejoin` | new: puts the branches of one stream back together by matching system tags (ITL-1336) | +| `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 column selections (`SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index f4911d843..e66fde8f5 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -9,11 +9,17 @@ keeps those columns unchanged: a result row has its origin row's provenance, and stacked diamonds keep a constant number of system-tag columns. +It is an inner join on every column its inputs share (developer, November 22, 2026, +ITL-1355): the system tags, a tag several inputs have, the source info of a shared +data-tag and the data context. Rows that match nothing are left out; nothing is refused +for what the rows hold. + Provisional (``PROVISIONAL_OPERATORS``): its identity is not frozen with data context v1. """ from __future__ import annotations +import warnings from collections.abc import Collection, Sequence from typing import TYPE_CHECKING, Any, ClassVar @@ -31,7 +37,7 @@ ) from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream -from orcapod.errors import InputValidationError +from orcapod.errors import InputValidationError, RejoinDifferingColumnWarning from orcapod.protocols.core_protocols import ( DataProtocol, StreamProtocol, @@ -41,6 +47,7 @@ from orcapod.types import ColumnConfig, ContentHash, Schema from orcapod.utils import arrow_utils, schema_utils from orcapod.utils.lazy_module import LazyModule +from orcapod.utils.warning_utils import outside_orcapod_stacklevel if TYPE_CHECKING: import polars as pl @@ -49,9 +56,11 @@ pa = LazyModule("pyarrow") pl = LazyModule("polars") -# Row-number columns of the frames Polars matches; never a key (keys are system tags). +# Row-number columns of the frames Polars matches, and the column that names a group of +# pairs; never a key (keys are columns of the inputs, and no input column starts so). _LEFT_ROW = "__rejoin_left_row" _RIGHT_ROW = "__rejoin_right_row" +_GROUP = "__rejoin_group" def _system_tag_names(stream: StreamProtocol) -> list[str]: @@ -62,47 +71,86 @@ def _system_tag_names(stream: StreamProtocol) -> list[str]: ) -_FLOAT_BITS = {16: "uint16", 32: "uint32", 64: "uint64"} - +def _agreeing( + pairs: "pl.DataFrame", + left: "pa.Table", + right: "pa.Table", + keys: Sequence[str], + names: Sequence[str], +) -> "pl.DataFrame": + """Keep the pairs of rows that also hold equal values in ``names``. -def _bits(array: "pa.Array[Any]") -> "pa.Array[Any]": - """An array whose equality is bit for bit: each float as its integer bits. + Equality is that of ``Join``'s keys (the prepared columns of ``arrow_keys``, matched + by Polars: NaN equals NaN, ``-0.0`` equals ``0.0``), except that here a null equals + a null (in ``Join`` a null key matches nothing): two rows of one origin row that + both hold no value in a column agree on it. - ``-0.0`` and ``0.0``, or two NaNs of different payloads, are then different values; - every other type already compares exactly. Lists, fixed-size lists and structs are - rebuilt over their converted children, with their own validity. + Args: + pairs: Row numbers of matched rows, ``_LEFT_ROW`` and ``_RIGHT_ROW``. + left: The table ``_LEFT_ROW`` numbers. + right: The table ``_RIGHT_ROW`` numbers. + keys: The columns the pairs already match on (the system tags). + names: The other shared columns to compare. + + Returns: + The pairs that agree on ``names``, in the order of ``pairs``. """ - arrow_type = array.type - if pa.types.is_floating(arrow_type): - return array.view(getattr(pa, _FLOAT_BITS[arrow_type.bit_width])()) - if isinstance(array, pa.ExtensionArray): - return _bits(array.storage) - mask = array.is_null() if array.null_count else None - if isinstance(array, pa.ListArray): - return pa.ListArray.from_arrays(array.offsets, _bits(array.values), mask=mask) - if isinstance(array, pa.LargeListArray): - return pa.LargeListArray.from_arrays( - array.offsets, _bits(array.values), mask=mask - ) - if isinstance(array, pa.FixedSizeListArray): - return pa.FixedSizeListArray.from_arrays( - _bits(array.values), arrow_type.list_size, mask=mask - ) - if isinstance(array, pa.StructArray): - children = [_bits(array.field(i)) for i in range(arrow_type.num_fields)] - names = [arrow_type.field(i).name for i in range(arrow_type.num_fields)] - return pa.StructArray.from_arrays(children, names=names, mask=mask) - return array + columns = [*keys, *names] + agreeing = polars_key_frame(left, columns, _LEFT_ROW).join( + polars_key_frame(right, columns, _RIGHT_ROW), + on=columns, + how="inner", + nulls_equal=True, + ) + return pairs.join( + agreeing.select(_LEFT_ROW, _RIGHT_ROW), + on=[_LEFT_ROW, _RIGHT_ROW], + how="semi", + maintain_order="left", + ) -def _same_bits(left: "pa.Array[Any]", right: "pa.Array[Any]") -> bool: - """Whether two arrays of one type hold the same value, bit for bit, on every row. +def _each_row_once(pairs: "pl.DataFrame") -> "pl.DataFrame": + """Keep each row in at most one pair. - The matched rows of a rejoin come from one origin row, so a column they share holds - one value; equal values in different bits (``-0.0`` and ``0.0``) mean a branch - changed it, and the rejoin would otherwise keep one input's bits by argument order. + System tags are assumed unique in each input (developer, November 22, 2026, + ITL-1355), so every row is in one pair already and ``pairs`` is returned as it is. + If an input does repeat an origin row, the rows of one origin row that agree pair + every left row with every right row; of those, the first left row keeps the first + right row, the second the second, and so on in row order (the order the rows + arrived in, on the async path), and the rows left over match nothing. + + Args: + pairs: Row numbers of the rows that match and agree on every shared column. + + Returns: + The pairs to put together, in the order of ``pairs``. """ - return _bits(left).equals(_bits(right)) + left_rows, right_rows = pairs.get_column(_LEFT_ROW), pairs.get_column(_RIGHT_ROW) + if not (left_rows.is_duplicated().any() or right_rows.is_duplicated().any()): + return pairs + # The pairs of one such group share their right rows: its smallest names it. + group = pl.col(_RIGHT_ROW).min().over(_LEFT_ROW) + return ( + pairs.with_columns(group.alias(_GROUP)) + .filter( + pl.col(_LEFT_ROW).rank("dense").over(_GROUP) + == pl.col(_RIGHT_ROW).rank("dense").over(_GROUP) + ) + .drop(_GROUP) + ) + + +def _described(name: str, shared_tags: Collection[str]) -> str: + """How a warning names a shared column that is not a system tag.""" + if name in shared_tags: + return f"tag {name!r}" + if name == constants.CONTEXT_KEY: + return "the data context" + if name.startswith(constants.SOURCE_PREFIX): + tag = name.removeprefix(constants.SOURCE_PREFIX) + return f"the source info of data-tag {tag!r}" + return f"column {name!r}" def _require_same_system_tags(names: Sequence[Sequence[str]]) -> None: @@ -140,17 +188,37 @@ class Rejoin(Join): The inputs must share their system-tag columns: the same names, which they have when each branch went through operators that keep system tags (filters, column selection and renaming, ``AddTags``, function pods) and no ``Join``, ``GroupBy`` or ``Batch``. - Rows are matched on every system-tag column, so each result row pairs the rows of the - branches that come from one origin row, at most one per input: an input holding two - rows of one origin row is refused. That is a deliberate first rule, which no operator - that keeps system tags breaks today; it can be relaxed later if a branch may duplicate - rows. A user tag in several inputs must have the same value on matched rows, bit for - bit (so the result never depends on the order of the inputs); a tag of one input is - kept. Provenance is never null: an input with a null system-tag value is refused; - matched system-tag values are compared bit for bit too. The inputs share one data - context, which the result keeps; inputs of different data contexts are refused. Data columns must be disjoint, as in ``Join``, and a data-tag in several inputs is - one column. The result keeps the common system-tag columns unchanged. + one column. These are the only refusals: each is read from the inputs' columns, + none from their rows. + + Rejoin is an inner join on every column its inputs share (developer, November 22, + 2026, ITL-1355): the system-tag columns, a user tag several inputs have, the source + info of a shared data-tag and the data context. A result row puts together the rows + of the branches that come from one origin row and are equal in all of them; a row + that matches nothing is left out. So a tag two branches set to different values, or + rows of different data contexts, give no row: a non-match, not an error. Equality is + ``Join``'s: NaN equals NaN and ``-0.0`` equals ``0.0``. A null system tag matches + nothing (provenance is never null). In any other shared column a null equals a + null, on purpose unlike ``Join``, where a null tag key matches nothing: two rows of + one origin row that both hold no value in a column agree on it. When rows of one + origin row (their system tags match) differ in another shared column, a + ``RejoinDifferingColumnWarning`` names the columns, once per operator and set of + columns. + + System tags are assumed unique in each input, as every source makes them, so each + row matches at most once; no check reads the rows for it. Should an input repeat an + origin row, each row still matches at most once: among the rows equal in every + shared column, the first of one input pairs with the first of the other, the second + with the second, in row order (the order the rows arrived in, on the async path). + + A shared column is kept once, with the values of the first input that has it. The + inputs are taken in a canonical order, by pipeline hash, so the result does not + follow the order of the arguments; inputs with equal pipeline hashes (two branches + of the same structure) stay in argument order. Only the bits of values that are + equal but not identical (``-0.0`` and ``0.0``, NaNs of different payloads) can + follow it; no row, hash or identity does. A tag of one input is kept. The result + keeps the common system-tag columns unchanged, and its rows' data context. Inputs from two different sources with the same schema share their system-tag column names but no value: their rejoin is empty, not an error. To combine different rows @@ -232,14 +300,16 @@ def output_schema( return tag_schema, data_schema def static_process(self, *streams: StreamProtocol) -> StreamProtocol: - """Rejoin the streams on their system-tag columns. + """Rejoin the streams on every column they share. Raises: - InputValidationError: If the inputs cannot be rejoined or are of different - data contexts, an input holds two rows of one origin row, a shared - column (a system tag, a tag, a shared data-tag's source info, the data - context) differs bit for bit on matched rows, or a shared tag's Arrow - type differs. + InputValidationError: If the inputs' system-tag columns differ or are + absent, or a shared column's Arrow type differs or cannot be matched. + Never for what the rows hold. + + Warns: + RejoinDifferingColumnWarning: Once per operator and set of columns, when + rows of one origin row differ in another shared column (ITL-1355). """ if len(streams) == 1: return without_input_meta(streams[0], streams) @@ -275,51 +345,21 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: for name in tables[0].column_names if name.startswith(constants.SYSTEM_TAG_PREFIX) ) - # The rows of one origin row carry one data context: so must the inputs. It - # is read from the rows, which carry it, never from what a stream reports (an - # operator's lazy stream reports its pod's context, ITL-1339). - context_keys = sorted( - { - # The context column is text and never null. - str(key) - for table in tables - for key in table.column(constants.CONTEXT_KEY).unique().to_pylist() - } - ) - if len(context_keys) > 1: - raise InputValidationError( - f"Rejoin: the inputs' rows are of different data contexts " - f"{context_keys}; rejoined rows must share one (a branch through some " - "operators comes back in the default data context: ITL-1339)" - ) - data_context = ( - context_keys[0] if context_keys else ordered_streams[0].data_context_key - ) - for stream, table in zip(ordered_streams, tables): - for name in keys: - if table.column(name).null_count: - raise InputValidationError( - f"Rejoin: input {stream} has a null in system-tag column " - f"{name!r}; provenance is never null, so the input is refused" - ) - frame = polars_key_frame(table, keys) - duplicated = frame.is_duplicated() - if duplicated.any(): - # The system-tag values are text (a source id and a record id): name them. - values = dict(zip(keys, frame.filter(duplicated).row(0))) - raise InputValidationError( - f"Rejoin: input {stream} holds two rows of one origin row, the " - f"system-tag values {values}; a first rule pairs at most one row per " - "origin row in each input, so such rows are refused (to be relaxed if " - "a branch may duplicate rows)" - ) table = tables[0] user_tags = set(ordered_streams[0].keys()[0]) + differing: set[str] = set() for next_table, next_stream in zip(tables[1:], ordered_streams[1:]): next_tags = set(next_stream.keys()[0]) - table = self._rejoin_pair(table, next_table, keys, user_tags & next_tags) + table, differed = self._rejoin_pair( + table, next_table, keys, user_tags & next_tags + ) + differing.update( + _described(name, user_tags & next_tags) for name in differed + ) user_tags |= next_tags + if differing: + self._warn_differing_once(tuple(sorted(differing))) # Lay the columns out as Join does: tags, data, then the hidden columns. tag_order = list(tag_schema.keys()) @@ -334,8 +374,66 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: result_table, tag_columns=tuple(tag_order), data_tags=data_tag_names(tag_schema, data_schema), - data_context=data_context, + data_context=self._rows_data_context(result_table, tables) + or ordered_streams[0].data_context_key, + ) + + @staticmethod + def _rows_data_context( + result: "pa.Table", inputs: Sequence["pa.Table"] + ) -> str | None: + """The data context the result's rows are of, read from the rows. + + It is read from the rows, which carry it, never from what a stream reports (an + operator's lazy stream reports its pod's context, ITL-1339). Matched rows are + of one data context each, so a result usually has one; with no result row it is + the inputs' rows' own. Should rows of several remain (inputs that each hold rows + of several data contexts), the stream takes the first key in text order: every + row still carries its own in the data context column. + + Args: + result: The rejoined rows. + inputs: The inputs' rows. + + Returns: + The data context key, or ``None`` when no input has a row. + """ + for tables in ([result], inputs): + found = { + # The context column is text and never null. + str(key) + for table in tables + for key in table.column(constants.CONTEXT_KEY).unique().to_pylist() + } + if found: + return min(found) + return None + + def _warn_differing_once(self, described: tuple[str, ...]) -> None: + """Issue ``RejoinDifferingColumnWarning`` once per set of differing columns. + + Args: + described: The differing columns, each as the warning names it, sorted. + """ + warned: set[tuple[str, ...]] | None = getattr(self, "_warned_differing", None) + if warned is None: + warned = set() + self._warned_differing: set[tuple[str, ...]] = warned + if described in warned: + return + # Recorded only once the warning is issued: under an error filter it raises, + # and a retry must raise again. + warnings.warn( + "Rejoin left out rows that come from one origin row (their system tags " + + f"match) and differ in {', '.join(described)}. Rejoin puts rows together " + + "only when every column its inputs share is equal; a branch changed " + + "this one. To keep the rows, drop or rename the column in one branch " + + "before the rejoin (drop_tag_columns, map_tags); to silence this, filter " + + "orcapod.errors.RejoinDifferingColumnWarning.", + RejoinDifferingColumnWarning, + stacklevel=outside_orcapod_stacklevel(), ) + warned.add(described) def _rejoin_pair( self, @@ -343,14 +441,15 @@ def _rejoin_pair( right: "pa.Table", keys: Sequence[str], shared_tags: Collection[str], - ) -> "pa.Table": - """Pair the rows of two tables of one origin, by their system-tag columns. + ) -> tuple["pa.Table", list[str]]: + """Pair the rows of two tables that are equal in every column both have. Every output value is taken from ``left`` or ``right`` by row number; Polars - only decides which rows match (``arrow_keys``). A column both tables have (a - system tag, a shared tag, a shared data-tag's source info, the data context) is - kept once, from ``left``, after checking that the matched rows hold the same - bits. + only decides which rows match (``arrow_keys``). The rows are first matched on + the system tags, as they always were (so inputs whose shared columns all agree + give the same rows in the same order as before ITL-1355), and of those pairs + only the ones that agree on every other shared column are kept (``_agreeing``). + A column both tables have is kept once, from ``left``. Args: left: The rows rejoined so far. @@ -359,23 +458,47 @@ def _rejoin_pair( shared_tags: The user tags of both tables. Returns: - The paired rows. + The paired rows, and the shared columns (other than system tags) in which + rows of one origin row differ. Raises: - InputValidationError: If a shared tag or a shared column differs on matched - rows, or a shared tag's Arrow type differs. + InputValidationError: If a shared column's Arrow type differs, or has no + rule for matching rows. """ - for name in sorted(shared_tags): - tag_type = require_shared_arrow_type( + # Every column both tables have besides the system tags: the shared tags, the + # source info of a shared data-tag, the data context. + others = [ + name + for name in right.column_names + if name in left.column_names and name not in keys + ] + for name in sorted(others): + shared_type = require_shared_arrow_type( "Rejoin", name, arrow_utils.column_arrow_type(left.schema, name), arrow_utils.column_arrow_type(right.schema, name), ) - require_matchable_key("Rejoin", name, tag_type) - pairs = polars_key_frame(left, keys, _LEFT_ROW).join( + require_matchable_key("Rejoin", name, shared_type) + matched = polars_key_frame(left, keys, _LEFT_ROW).join( polars_key_frame(right, keys, _RIGHT_ROW), on=list(keys), how="inner" ) + # Nothing matched, or nothing else is shared: there is nothing to compare. + pairs = ( + _agreeing(matched, left, right, keys, others) + if others and matched.height + else matched + ) + differed = ( + [ + name + for name in others + if _agreeing(matched, left, right, keys, [name]).height < matched.height + ] + if pairs.height < matched.height + else [] + ) + pairs = _each_row_once(pairs) left_rows = pairs.get_column(_LEFT_ROW).to_arrow() right_rows = pairs.get_column(_RIGHT_ROW).to_arrow() names: list[str] = [] @@ -384,33 +507,14 @@ def _rejoin_pair( names.append(name) arrays.append(left.column(name).combine_chunks().take(left_rows)) for name in right.column_names: - right_values = right.column(name).combine_chunks().take(right_rows) if name not in left.column_names: names.append(name) - arrays.append(right_values) - continue - # Polars matched the system tags by equality; they too must be the same - # bits (a float system tag of -0.0 matches 0.0). - left_values = arrays[names.index(name)] - if not _same_bits(left_values, right_values): - if name in shared_tags: - what = f"tag {name!r}" - elif name in keys: - what = f"system tag {name!r}" - elif name == constants.CONTEXT_KEY: - what = f"the data context column {name!r}" - else: - what = f"column {name!r} (a shared data-tag's source info)" - raise InputValidationError( - f"Rejoin: {what} has different values on rows of one origin row in " - "two inputs (compared bit for bit: -0.0 is not 0.0, NaNs of " - "different payloads differ); a branch changed it, so the rows cannot " - "be put back together (rename it in one branch, or use Join)" - ) + arrays.append(right.column(name).combine_chunks().take(right_rows)) table = pa.Table.from_arrays(arrays, names=names) table = arrow_utils.restore_schema_nullability(table, left.schema, right.schema) - return self._shared_key_nullability( - table, left.schema, right.schema, shared_tags + return ( + self._shared_key_nullability(table, left.schema, right.schema, shared_tags), + differed, ) async def async_execute( diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index f5dbc5e61..a076f31b3 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -412,9 +412,11 @@ def rejoin( """Put this stream back together with other branches of one stream. Pairs the rows that come from the same origin row, by matching every system-tag - column, and keeps those columns unchanged (``Rejoin``, provisional). For a - diamond (one stream split into branches, then put back together); to combine - different rows on their tags, use ``join``. + column, and keeps those columns unchanged (``Rejoin``, provisional). Rows must + also be equal in every other column the streams share (a tag several have, the + data context); a row that matches nothing is left out. For a diamond (one + stream split into branches, then put back together); to combine different rows + on their tags, use ``join``. Args: *other_streams: The other branches, one or more. diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 5ae3a904b..6d063e6d3 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -780,6 +780,22 @@ class SemiJoinIgnoredColumnWarning(UserWarning): """ +class RejoinDifferingColumnWarning(UserWarning): + """``Rejoin`` dropped rows of one origin row because a shared column differed. + + ``Rejoin`` puts rows together when every column its inputs share is equal: the + system tags, a tag several inputs have, the source info of a shared data-tag and + the data context (ITL-1355). Rows that come from one origin row (their system tags + match) and differ in another shared column are not put together: they are left out + of the result. A branch changed that column, which is rarely meant, so this warning + names such columns, once per operator and set of columns. + + To keep the rows, drop or rename the column in one branch before the rejoin + (``drop_tag_columns``, ``map_tags``). To silence the warning, call + ``warnings.filterwarnings("ignore", category=RejoinDifferingColumnWarning)``. + """ + + class EmptyDataAccessError(Exception): """Raised when a payload-access method is called on an ``EmptyData`` instance. diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index 02fe34ccb..ed87a8f66 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -66,9 +66,12 @@ # The ``semijoin_shared_data_column`` case shares a data column name on purpose; SemiJoin # warns that it is not a match key (ITL-1088), which is tested in test_semijoin_tag_keys. -pytestmark = pytest.mark.filterwarnings( - "ignore::orcapod.errors.SemiJoinIgnoredColumnWarning" -) +# The ``rejoin_differing_*`` cases change a shared tag in one branch on purpose; Rejoin +# warns that such rows are left out (ITL-1355), which is tested in test_rejoin. +pytestmark = [ + pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning"), + pytest.mark.filterwarnings("ignore::orcapod.errors.RejoinDifferingColumnWarning"), +] Row: TypeAlias = tuple[TagProtocol, DataProtocol] Column: TypeAlias = "pa.Array[Any] | pa.ChunkedArray[Any]" @@ -452,7 +455,75 @@ def _branches( return tuple(source.select_data_columns([*data_tags, *names]) for names in data) +def _changed_branches( + *branches: tuple[Sequence[str], dict[str, Column]], +) -> tuple[StreamProtocol, ...]: + """Branches of ``source_a`` built by hand, some with a shared tag changed (ITL-1355). + + Each branch has the source's tags ``k`` and ``ta``, its system tags and the named + data columns; ``changed`` replaces tag columns by name. Rejoin leaves out the rows + of one origin row that differ in a shared column. + """ + origin = source_a().as_table(columns={"system_tags": True}) + system_tags = [name for name in origin.column_names if name.startswith("_tag")] + streams: list[StreamProtocol] = [] + for data, changed in branches: + table = origin + for name, values in changed.items(): + index = table.column_names.index(name) + table = table.set_column(index, table.schema.field(index), values) + streams.append( + ArrowTableStream( + table.select(["k", "ta", *data, *system_tags]), tag_columns=["k", "ta"] + ) + ) + return tuple(streams) + + +def _float_tag_branch(values: Sequence[float], data: str) -> ArrowTableStream: + """A branch whose shared tag ``f`` is a float, with data column ``data`` (ITL-1355).""" + table = pa.table( + { + "k": pa.array([1, 2, 3], pa.int16()), + "f": pa.array(values, pa.float64()), + data: pa.array([10, 20, 30], pa.int32()), + "_tag_source_id::x": pa.array(["s", "s", "s"], pa.large_string()), + "_tag_record_id::x": pa.array(["r1", "r2", "r3"], pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k", "f"]) + + CASES = [ + # Rejoin leaves out rows of one origin row that differ in a shared column; equal + # floats of different bits match (ITL-1355). A null system tag is not here: rows + # holding one cannot be rebuilt into a table by the barrier of any operator (their + # system-tag field is nullable, the other rows' is not), before Rejoin sees them; + # the sync path is tested in test_rejoin. + Case( + "rejoin_differing_tag", + Rejoin, + lambda: _changed_branches( + (("i8", "s"), {}), (("l8", "nul"), {"ta": pa.array([5, 9, 6], pa.int8())}) + ), + ), + Case( + "rejoin_3_differing_tags", + Rejoin, + lambda: _changed_branches( + (("i8",), {}), + (("s", "p"), {"ta": pa.array([5, 9, 6], pa.int8())}), + (("l8",), {"k": pa.array([1, 2, 4], pa.int16())}), + ), + ), + Case( + "rejoin_equal_floats_of_different_bits", + Rejoin, + lambda: ( + _float_tag_branch([0.0, float("nan"), 1.5], "x"), + _float_tag_branch([-0.0, -float("nan"), 1.5], "y"), + ), + ), # Rejoin: the branches of one source put back together (ITL-1336), over many narrow # types, with plain tags and with data-tags, two and three inputs. Case( diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index d4b2265a9..1d9684921 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -5,6 +5,12 @@ number of system-tag columns stays constant however many diamonds are stacked, where ``Join`` (unchanged) doubles them. The sources here have two tags and several data columns; diamonds go through filters, renames, ``AddTags`` and function pods. + +Rejoin is an inner join on every column its inputs share (ITL-1355): the system tags, a +tag several inputs have, a shared data-tag's source info and the data context, compared +as ``Join`` compares keys. It refuses only what the inputs' columns show; rows that match +nothing are left out, and a ``RejoinDifferingColumnWarning`` names the shared columns in +which rows of one origin row differ. """ from __future__ import annotations @@ -12,7 +18,10 @@ import asyncio import dataclasses import itertools +import math +import struct import warnings +from collections.abc import Sequence from pathlib import Path from typing import Any, cast @@ -26,7 +35,11 @@ from orcapod.core.sources import DictSource from orcapod.core.streams import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import InputValidationError, ProvisionalHashWarning +from orcapod.errors import ( + InputValidationError, + ProvisionalHashWarning, + RejoinDifferingColumnWarning, +) from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.pipeline.job import PipelineJob from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -257,15 +270,14 @@ def test_inputs_without_system_tags_are_refused() -> None: _ = stream.as_table() -def test_a_shared_tag_that_differs_is_refused() -> None: - """Two branches that each add tag ``run``, with different values: refused, naming it.""" - source = _source() - a = source.select_data_columns(["rate"]).add_tags(run=1) - b = source.select_data_columns(["depth"]).add_tags(run=2) - with pytest.raises(InputValidationError, match="tag 'run' has different values"): - _ = a.rejoin(b).as_table() - same = source.select_data_columns(["depth"]).add_tags(run=1) - assert {row["run"] for row in _user_rows(a.rejoin(same))} == {1} +def test_a_shared_tags_type_that_differs_is_refused() -> None: + """A tag two inputs have in different Arrow types is refused, naming it and both + types: the inputs' columns show it, before any row is matched.""" + origin = _origin() + a = _branch(origin, ["rate"]) + b = _branch(origin, ["depth"], unit=pa.array(range(8), pa.int32())) + with pytest.raises(InputValidationError, match="Arrow type of column 'unit'"): + _ = Rejoin()(a, b).as_table() def test_overlapping_data_columns_are_refused() -> None: @@ -276,28 +288,6 @@ def test_overlapping_data_columns_are_refused() -> None: ) -def test_two_rows_of_one_origin_row_in_one_input_are_refused() -> None: - """A first rule: at most one row per origin row in each input; the error names the - input and the system-tag values.""" - source = _source() - table = source.as_table(columns={"system_tags": True}).select( - ["subject", "unit", "rate"] + [name for name in _system_tags(source)] - ) - doubled = pa.concat_tables([table, table.slice(0, 1)]) - duplicated = ArrowTableStream(doubled, tag_columns=["subject", "unit"]) - other = ArrowTableStream( - source.as_table(columns={"system_tags": True}).select( - ["subject", "unit", "depth"] + _system_tags(source) - ), - tag_columns=["subject", "unit"], - ) - with pytest.raises(InputValidationError) as caught: - _ = Rejoin()(duplicated, other).as_table() - message = str(caught.value) - assert "holds two rows of one origin row" in message - assert "units" in message # the source id among the system-tag values - - def test_two_sources_with_one_schema_rejoin_to_nothing() -> None: """Same schema, different source ids: eligible (same system-tag column names), but no origin row is shared, so the result is empty, not an error.""" @@ -416,31 +406,6 @@ def test_join_is_unchanged() -> None: # --------------------------------------------------------------------------- -def test_a_null_in_a_system_tag_is_refused() -> None: - """Provenance is never null: an input with a null in a system-tag column is refused, - naming the column, instead of silently losing the row (the reviewer's case).""" - source = _source() - full = source.as_table(columns={"system_tags": True}) - names = _system_tags(source) - source_id = next(name for name in names if "source_id" in name) - values = full.column(source_id).to_pylist() - nulled = full.set_column( - full.schema.get_field_index(source_id), - pa.field(source_id, pa.large_string(), nullable=True), - pa.array([None, None, *values[2:]], pa.large_string()), - ) - a = ArrowTableStream( - nulled.select(["subject", "unit", "rate", *names]), - tag_columns=["subject", "unit"], - ) - b = ArrowTableStream( - nulled.select(["subject", "unit", "depth", *names]), - tag_columns=["subject", "unit"], - ) - with pytest.raises(InputValidationError, match="null in system-tag column"): - _ = Rejoin()(a, b).as_table() - - def _tied(k: list[float]) -> ArrowTableStream: """A raw stream with data-tags ``k`` (float) and ``g``, and fixed system tags.""" table = pa.table( @@ -454,26 +419,6 @@ def _tied(k: list[float]) -> ArrowTableStream: return ArrowTableStream(table, tag_columns=["k", "g"], data_tags=["k", "g"]) -@pytest.mark.parametrize( - ("left", "right"), - [([0.0, 0.0], [-0.0, -0.0]), ([float("nan")] * 2, [-float("nan")] * 2)], - ids=["signed_zero", "nan_payload"], -) -def test_equal_values_in_different_bits_are_refused_in_both_orders( - left: list[float], right: list[float] -) -> None: - """Inputs with equal pipeline hashes keep the caller's order; a shared tag equal in - value but not in bits would make the output's bits follow it. Refused in both - orders, naming the tag (the reviewer's case).""" - a, b = _tied(left), _tied(right) - assert a.pipeline_hash() == b.pipeline_hash() - for inputs in ((a, b), (b, a)): - with pytest.raises(InputValidationError, match="tag 'k' has different values"): - _ = Rejoin()(*inputs).as_table() - same = Rejoin()(a, _tied(left)).as_table() - assert same.num_rows == 2 - - def test_stated_system_tags_are_compared_even_beside_an_input_that_states_none() -> ( None ): @@ -501,18 +446,6 @@ def _float_provenance(origin: list[float], data: str) -> ArrowTableStream: return ArrowTableStream(table, tag_columns=["g"], system_tag_columns=["origin"]) -def test_system_tags_matched_by_equality_must_be_the_same_bits() -> None: - """Polars matches -0.0 with 0.0; a system tag matched that way is refused, in - both argument orders, naming the system tag (CodeRabbit on PR 472).""" - a = _float_provenance([0.0, 1.0], "x") - b = _float_provenance([-0.0, 1.0], "y") - for inputs in ((a, b), (b, a)): - with pytest.raises(InputValidationError, match="system tag '_tag_origin'"): - _ = Rejoin()(*inputs).as_table() - same = Rejoin()(a, _float_provenance([0.0, 1.0], "y")).as_table() - assert same.num_rows == 2 - - OTHER_CONTEXT = "std:v1:test-other" @@ -595,18 +528,6 @@ async def run() -> list[Any]: assert {data.data_context_key for _, data in rows} == {OTHER_CONTEXT} -def test_inputs_of_different_data_contexts_are_refused( - other_context: contexts.DataContext, -) -> None: - """Rows of one origin row carry one data context: inputs that do not are refused, - naming both keys, in either argument order.""" - a = _in_context(other_context, "x") - b = _in_context(contexts.get_default_context(), "y") - for inputs in ((a, b), (b, a)): - with pytest.raises(InputValidationError, match="different data contexts"): - _ = Rejoin()(*inputs).as_table() - - def _wide_in_context(context: contexts.DataContext) -> ArrowTableStream: """A raw stream of ``context``: tags ``g`` and ``h``, data ``w``, ``x``, ``y``, ``z``, one system tag.""" @@ -699,14 +620,459 @@ async def run(streams: tuple[Any, ...]) -> list[Any]: assert {data.data_context_key for _, data in rows} == {OTHER_CONTEXT}, name -def test_rows_of_different_data_contexts_are_refused_whatever_the_streams_report( +# --------------------------------------------------------------------------- +# Rows that match nothing are left out (ITL-1355) +# --------------------------------------------------------------------------- + + +def _origin() -> pa.Table: + """The source's rows with their system tags.""" + return _source().as_table(columns={"system_tags": True}) + + +def _branch( + origin: pa.Table, + data: Sequence[str], + *, + tags: Sequence[str] = ("subject", "unit"), + data_tags: Sequence[str] = (), + **columns: Any, +) -> ArrowTableStream: + """A branch of ``origin`` built by hand: its system tags, the named tags and data. + + ``columns`` replaces or adds columns (a tag a branch changed, a tag it added, the + source info of a data-tag, the data context column). + """ + table = origin + for name, values in columns.items(): + array = values if isinstance(values, pa.Array) else pa.array(values) + if name in table.column_names: + table = table.set_column(table.column_names.index(name), name, array) + else: + table = table.append_column(name, array) + system_tags = [ + name + for name in origin.column_names + if name.startswith(constants.SYSTEM_TAG_PREFIX) + ] + hidden = [ + name + for name in table.column_names + if name.startswith(constants.SOURCE_PREFIX) or name == constants.CONTEXT_KEY + ] + return ArrowTableStream( + table.select([*tags, *data, *system_tags, *hidden]), + tag_columns=list(tags), + data_tags=list(data_tags), + ) + + +def _rejoined(*inputs: Any) -> tuple[Any, list[str]]: + """The rejoin of ``inputs`` computed, and its ``RejoinDifferingColumnWarning``s.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + stream = Rejoin()(*inputs) + _ = stream.as_table() + return stream, [ + str(w.message) + for w in caught + if issubclass(w.category, RejoinDifferingColumnWarning) + ] + + +def _units(stream: Any) -> list[int]: + return sorted(stream.as_table().column("unit").to_pylist()) + + +def test_a_shared_tag_that_differs_matches_nothing() -> None: + """Two branches that each add tag ``run``, with different values: no row is put + together, nothing is refused, and one warning names the tag. With the same value + the rows are put together and nothing warns.""" + source = _source() + a = source.select_data_columns(["rate"]).add_tags(run=1) + b = source.select_data_columns(["depth"]).add_tags(run=2) + for inputs in ((a, b), (b, a)): + result, warned = _rejoined(*inputs) + assert result.as_table().num_rows == 0 + assert set(result.as_table().column_names) == { + "subject", + "unit", + "run", + "rate", + "depth", + } + assert len(warned) == 1 and "tag 'run'" in warned[0] + same = source.select_data_columns(["depth"]).add_tags(run=1) + result, warned = _rejoined(a, same) + assert {row["run"] for row in _user_rows(result)} == {1} + assert len(_user_rows(result)) == 8 and not warned + + +def test_several_shared_tags_several_inputs_in_every_order() -> None: + """Three branches sharing ``subject``, ``unit`` and, two by two, the added tags + ``run``, ``site`` and ``day``: a row is put together only when every column two + inputs share is equal, whatever the order of the inputs.""" + origin = _origin() + run_a = [1, 1, 1, 1, 2, 2, 2, 2] + run_b = [1, 1, 9, 1, 2, 2, 2, 2] # unit 2 differs from a + site_a = ["x"] * 8 + site_c = ["x", "y", "x", "x", "x", "x", "x", "x"] # unit 1 differs from a + day_b = [5, 5, 5, 5, 5, 5, 7, 5] + day_c = [5, 5, 5, 5, 5, 5, 5, 5] # unit 6 differs from b + a = _branch( + origin, + ["rate"], + tags=["subject", "unit", "run", "site"], + run=run_a, + site=site_a, + ) + b = _branch( + origin, ["depth"], tags=["day", "run", "unit", "subject"], run=run_b, day=day_b + ) + c = _branch( + origin, + ["area"], + tags=["site", "subject", "day", "unit"], + site=site_c, + day=day_c, + ) + results = [] + for order in itertools.permutations((a, b, c)): + result, warned = _rejoined(*order) + assert _units(result) == [0, 3, 4, 5, 7] + assert len(warned) == 1 + assert any(f"tag {name!r}" in warned[0] for name in ("run", "site", "day")) + results.append(result) + first = results[0] + assert all(row["site"] == "x" and row["day"] == 5 for row in _user_rows(first)) + for result in results[1:]: + assert _user_rows(result) == _user_rows(first) + assert result.keys() == first.keys() + assert result.pipeline_hash() == first.pipeline_hash() + assert _system_tags(first) == _system_tags(_source()) + # Two of them, in both orders: only the columns those two share count. + for pair, kept in ( + ((a, b), [0, 1, 3, 4, 5, 6, 7]), + ((b, c), [0, 1, 2, 3, 4, 5, 7]), + ): + for order in (pair, pair[::-1]): + assert _units(_rejoined(*order)[0]) == kept + + +def test_a_null_in_a_system_tag_matches_nothing() -> None: + """Provenance is never null: rows with a null in a system-tag column match nothing + and are left out, in both inputs; the other rows are put together. Nothing is + refused and nothing warns (no shared column differs).""" + origin = _origin() + source_id = next(name for name in _system_tags(_source()) if "source_id" in name) + values = origin.column(source_id).to_pylist() + nulled: dict[str, Any] = { + source_id: pa.array([None, None, *values[2:]], pa.large_string()) + } + a = _branch(origin, ["rate"], **nulled) + b = _branch(origin, ["depth"], **nulled) + whole = _branch(origin, ["area"]) + for inputs in ((a, b), (b, a), (a, whole), (whole, a), (a, whole, b)): + result, warned = _rejoined(*inputs) + assert _units(result) == [2, 3, 4, 5, 6, 7] + assert not warned + + +def test_a_null_in_another_shared_column_equals_a_null() -> None: + """Only a system tag's null matches nothing. Rows of one origin row that both hold + no value in a shared tag, or in a shared data-tag's source info, are put together.""" + origin = _origin() + holes = pa.array( + ["s0", None, "s2", None, "s1", "s2", "s0", "s1"], pa.large_string() + ) + a = _branch(origin, ["rate"], subject=holes) + b = _branch(origin, ["depth"], subject=holes) + result, warned = _rejoined(a, b) + assert _units(result) == list(range(8)) and not warned + assert result.as_table().column("subject").to_pylist() == holes.to_pylist() + # A null against a value differs. + c = _branch(origin, ["depth"]) + result, warned = _rejoined(a, c) + assert _units(result) == [0, 2, 4, 5, 6, 7] + assert len(warned) == 1 and "tag 'subject'" in warned[0] + # A raw stream's data-tag has no source info at all: null on both sides. + tied = Rejoin()(_tied([1.0, 2.0]), _tied([1.0, 2.0])).as_table() + assert tied.num_rows == 2 + + +def test_a_shared_data_tags_source_info_that_differs_matches_nothing() -> None: + """A data-tag in two inputs is one column with one source info: rows of one origin + row whose tokens differ are left out, and the warning names the data-tag.""" + origin = _origin() + tokens = [f"units::row_{i}::unit" for i in range(8)] + changed = [*tokens[:6], "elsewhere::row_6::unit", None] + a = _branch(origin, ["rate"], data_tags=["unit"], _source_unit=tokens) + b = _branch(origin, ["depth"], data_tags=["unit"], _source_unit=changed) + for inputs in ((a, b), (b, a)): + result, warned = _rejoined(*inputs) + assert _units(result) == [0, 1, 2, 3, 4, 5] + assert len(warned) == 1 + assert "the source info of data-tag 'unit'" in warned[0] + result, warned = _rejoined( + a, _branch(origin, ["depth"], data_tags=["unit"], _source_unit=tokens) + ) + assert _units(result) == list(range(8)) and not warned + + +def test_an_input_that_repeats_an_origin_row_pairs_each_row_once() -> None: + """System tags are assumed unique, so nothing reads the rows for it. Should an + input repeat an origin row, each row still matches at most once: the repeats pair + with the other input's in row order, and a row left over matches nothing.""" + origin = _origin() + twice = pa.concat_tables([origin, origin.slice(0, 1)]) + left = _branch( + twice, ["rate"], rate=pa.array([*origin.column("rate").to_pylist(), 100.0]) + ) + once = _branch(origin, ["depth"]) + for inputs in ((left, once), (once, left)): + result, warned = _rejoined(*inputs) + assert _units(result) == list(range(8)) and not warned + rates = {row["unit"]: row["rate"] for row in result.as_table().to_pylist()} + assert rates[0] == 0.0 # the first of the two rows; the other matches nothing + right = _branch( + twice, ["depth"], depth=pa.array([*origin.column("depth").to_pylist(), 1000]) + ) + result, warned = _rejoined(left, right) + rows = [ + (row["rate"], row["depth"]) + for row in result.as_table().to_pylist() + if row["unit"] == 0 + ] + assert sorted(rows) == [(0.0, 0), (100.0, 1000)] and not warned + assert result.as_table().num_rows == 9 + + +# --------------------------------------------------------------------------- +# Equality is Join's; a shared column keeps the first input's values +# --------------------------------------------------------------------------- + + +def _bits(value: Any) -> bytes: + """The eight bytes of a float: its sign and its NaN payload count.""" + return struct.pack(" Any: + """The first input in Rejoin's canonical order: by pipeline hash; inputs with equal + pipeline hashes stay in the order given.""" + return sorted(streams, key=lambda stream: stream.pipeline_hash().to_hex())[0] + + +@pytest.mark.parametrize( + ("left", "right"), + [([0.0, 0.0], [-0.0, -0.0]), ([float("nan")] * 2, [-float("nan")] * 2)], + ids=["signed_zero", "nan_payload"], +) +def test_equal_values_in_different_bits_match_and_the_first_inputs_are_kept( + left: list[float], right: list[float] +) -> None: + """``-0.0`` equals ``0.0`` and NaN equals NaN, as in ``Join``: the rows are put + together and nothing warns. The shared tag keeps the first input's bits. These two + inputs have one pipeline hash, so the first is the first argument.""" + a, b = _tied(left), _tied(right) + assert a.pipeline_hash() == b.pipeline_hash() + for inputs in ((a, b), (b, a)): + result, warned = _rejoined(*inputs) + table = result.as_table() + assert table.num_rows == 2 and not warned + kept = [_bits(value) for value in table.column("k").to_pylist()] + assert kept == [ + _bits(value) for value in inputs[0].as_table().column("k").to_pylist() + ] + assert _bits(left[0]) != _bits(right[0]) + assert math.isnan(left[0]) or left[0] == right[0] + + +def test_the_first_input_is_the_first_by_pipeline_hash_whatever_the_argument_order() -> ( + None +): + """Inputs of different pipeline hashes are taken in the order of those hashes: the + shared column keeps the same input's bits in both argument orders. Here the shared + column is a float system tag, ``-0.0`` in one input and ``0.0`` in the other.""" + a = _float_provenance([0.0, 1.0], "x") + b = _float_provenance([-0.0, 1.0], "y") + assert a.pipeline_hash() != b.pipeline_hash() + first = _first(a, b) + wanted = _bits( + first.as_table(columns={"system_tags": True}) + .column("_tag_origin") + .to_pylist()[0] + ) + for inputs in ((a, b), (b, a)): + result, warned = _rejoined(*inputs) + table = result.as_table(columns={"system_tags": True}) + assert table.num_rows == 2 and not warned + by_g = dict( + zip(table.column("g").to_pylist(), table.column("_tag_origin").to_pylist()) + ) + assert _bits(by_g[1]) == wanted + + +def test_three_inputs_keep_the_bits_of_the_first_that_has_the_column() -> None: + """A tag only the second and third inputs have keeps the second's values.""" + origin = _origin() + zeros, minus = [0.0] * 8, [-0.0] * 8 + a = _branch(origin, ["rate"]) + b = _branch(origin, ["depth"], tags=["subject", "unit", "level"], level=zeros) + c = _branch(origin, ["area"], tags=["subject", "unit", "level"], level=minus) + holders = [ + stream + for stream in sorted((a, b, c), key=lambda s: s.pipeline_hash().to_hex()) + if stream is not a + ] + wanted = _bits(holders[0].as_table().column("level").to_pylist()[0]) + for order in itertools.permutations((a, b, c)): + result, warned = _rejoined(*order) + levels = result.as_table().column("level").to_pylist() + assert len(levels) == 8 and not warned + assert {_bits(value) for value in levels} == {wanted} + + +# --------------------------------------------------------------------------- +# The warning +# --------------------------------------------------------------------------- + + +def test_the_warning_is_issued_once_per_operator_and_set_of_columns() -> None: + """One operator warns once for one set of differing columns, again for another + set, and never when nothing differs; an error filter raises it each time.""" + origin = _origin() + plain = _branch( + origin, + ["rate"], + tags=["subject", "unit", "run", "site"], + run=[1] * 8, + site=["x"] * 8, + ) + same = _branch( + origin, + ["depth"], + tags=["subject", "unit", "run", "site"], + run=[1] * 8, + site=["x"] * 8, + ) + other_run = _branch( + origin, + ["depth"], + tags=["subject", "unit", "run", "site"], + run=[2] * 8, + site=["x"] * 8, + ) + both = _branch( + origin, + ["depth"], + tags=["subject", "unit", "run", "site"], + run=[2, *[1] * 7], + site=[*["x"] * 7, "y"], + ) + rejoin = Rejoin() + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + for inputs in ( + (plain, same), + (plain, other_run), + (other_run, plain), + (plain, both), + (plain, both), + (plain, other_run), + ): + _ = rejoin.static_process(*inputs) + messages = [ + str(w.message) + for w in caught + if issubclass(w.category, RejoinDifferingColumnWarning) + ] + assert len(messages) == 2 + assert "tag 'run'" in messages[0] and "site" not in messages[0] + assert "tag 'run'" in messages[1] and "tag 'site'" in messages[1] + assert "orcapod.errors.RejoinDifferingColumnWarning" in messages[0] + + strict = Rejoin() + with warnings.catch_warnings(): + warnings.simplefilter("error", RejoinDifferingColumnWarning) + _ = strict.static_process(plain, same) # nothing differs: nothing raised + for _ in range(2): + with pytest.raises(RejoinDifferingColumnWarning, match="tag 'run'"): + _ = strict.static_process(plain, other_run) + + +def test_a_diamond_through_operators_never_warns() -> None: + """Branches that changed no shared column: every row is put together, no warning.""" + source = _source(data_tags=True) + a = source.select_data_columns(["subject", "unit", "rate"]).polars_filter( + pl.col("rate") > 2 + ) + b = cast( + Any, double.pod(source.select_data_columns(["subject", "unit", "rate"])) + ).map_data({"doubled": "twice"}) + c = source.select_data_columns(["subject", "unit", "depth", "area"]).add_tags( + cohort="A" + ) + with warnings.catch_warnings(): + warnings.simplefilter("error", RejoinDifferingColumnWarning) + for order in itertools.permutations((a, b, c)): + assert Rejoin()(*order).as_table().num_rows == 5 + + +# --------------------------------------------------------------------------- +# Data contexts +# --------------------------------------------------------------------------- + + +def test_rows_of_different_data_contexts_match_nothing( other_context: contexts.DataContext, ) -> None: - """Mixed contexts are refused from the rows: two lazy branches both report the - default context, yet one's rows are of another.""" - a = _in_context(other_context, "x").select_data_columns(["x"]) - b = _in_context(contexts.get_default_context(), "y").select_data_columns(["y"]) - assert a.data_context_key == b.data_context_key + """Rows of one origin row in different data contexts are not put together: the + result is empty, nothing is refused, and the warning names the data context.""" + a = _in_context(other_context, "x") + b = _in_context(contexts.get_default_context(), "y") for inputs in ((a, b), (b, a)): - with pytest.raises(InputValidationError, match="different data contexts"): - _ = Rejoin()(*inputs).as_table() + result, warned = _rejoined(*inputs) + assert result.as_table().num_rows == 0 + assert len(warned) == 1 and "the data context" in warned[0] + # Whatever the streams report: two lazy branches both report the default context. + lazy_a = a.select_data_columns(["x"]) + lazy_b = b.select_data_columns(["y"]) + assert lazy_a.data_context_key == lazy_b.data_context_key + for inputs in ((lazy_a, lazy_b), (lazy_b, lazy_a)): + result, warned = _rejoined(*inputs) + assert result.as_table().num_rows == 0 and len(warned) == 1 + + +def test_rows_keep_their_own_data_context(other_context: contexts.DataContext) -> None: + """Inputs holding rows of two data contexts: the rows whose contexts agree are put + together, each keeping its own in the data context column.""" + default = contexts.get_default_context().context_key + + def mixed(keys: list[str], data: str) -> ArrowTableStream: + table = pa.table( + { + "g": pa.array([1, 2, 3], pa.int64()), + "h": pa.array(["a", "b", "c"], pa.large_string()), + data: pa.array([0.5, 0.25, 0.125], pa.float64()), + "origin": pa.array(["r1", "r2", "r3"], pa.large_string()), + constants.CONTEXT_KEY: pa.array(keys, pa.large_string()), + } + ) + return ArrowTableStream( + table, tag_columns=["g", "h"], system_tag_columns=["origin"] + ) + + a = mixed([OTHER_CONTEXT, default, OTHER_CONTEXT], "x") + b = mixed([OTHER_CONTEXT, default, default], "y") + for inputs in ((a, b), (b, a)): + result, warned = _rejoined(*inputs) + table = result.as_table(columns={"context": True}) + rows = dict( + zip( + table.column("g").to_pylist(), + table.column(constants.CONTEXT_KEY).to_pylist(), + ) + ) + assert rows == {1: OTHER_CONTEXT, 2: default} + assert len(warned) == 1 and "the data context" in warned[0] From 6409984dc691e5884440be386cfd0ceafea34367 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sat, 21 Nov 2026 23:56:03 -0800 Subject: [PATCH 2/4] fix(operators): Rejoin pairs repeated origin rows linearly and warns from the inputs' rows (ITL-1355) Two findings of the independent review of this branch. Repeated origin rows: an input that repeats an origin row was matched on the system tags first, which pairs every repeat of one input with every repeat of the other (N repeats: N x N pairs) before each row was cut down to one pair. Rows are now paired one to one by occurrence number: the k-th of one input with the k-th of the other among the rows equal in every shared column, in row order, by one join on the shared columns and that number. No pair is made that is not kept. With unique system tags the earlier path is unchanged: the same system-tag join, then its pairs filtered, so accepted inputs give the same rows in the same order. The warning: it was read from the rows rejoined so far, which no longer hold an origin row an earlier input lacks or disagrees on, so with three or more inputs a differing column could be missed. It is now read from the inputs' own rows: for each column several inputs have, their rows are stacked and counted per origin row. Every differing column is named, in any order of the inputs. Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 21 ++- CLAUDE.md | 21 ++- changelog.d/ITL-1355.md | 4 +- docs/concepts/operators.md | 7 +- src/orcapod/core/operators/rejoin.py | 206 ++++++++++++++++------- tests/test_core/operators/test_rejoin.py | 163 +++++++++++++++++- 6 files changed, 338 insertions(+), 84 deletions(-) diff --git a/.zed/rules b/.zed/rules index 6671e0f11..08c8bb467 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1502,13 +1502,20 @@ data. The rules: rows hold, only on what the inputs' columns show (system-tag names, a shared column's Arrow type, disjoint data columns): a row that matches nothing is left out, and rows of one origin row that differ in another shared column raise `RejoinDifferingColumnWarning` - once per operator and set of columns. System tags are assumed unique (no check reads the - rows; repeated ones pair in row order, arrival order on the async path, each row at most - once). A shared column keeps the - values of the first input that has it, in the canonical input order (by pipeline hash; - equal hashes stay in argument order, which only the bits of equal floats can follow). The - rows are matched on the system tags first, as before ITL-1355, and the pairs filtered, so - inputs whose shared columns agree give the same rows in the same order. The result's data + once per operator and set of columns. The warning is computed from the inputs' own rows + (`_differing_columns`: per shared column, the inputs that have it stacked and counted per + origin row), never from the rows rejoined so far, which have lost the origin rows an + earlier input lacks or disagrees on. System tags are assumed unique (no input is refused + for repeating one). A shared column keeps the values of the first input that has it, in + the canonical input order (by pipeline hash; equal hashes stay in argument order, which + only the bits of equal floats can follow). With unique system tags the rows are matched + on the system tags first, by the same join as before ITL-1355, and the pairs filtered, + so inputs whose shared columns agree give the same rows in the same order (Polars' join + order depends on the inputs' sizes: never replace that join). When an input repeats an + origin row, rows are paired one to one by occurrence number (`_pairs_of_repeated_origins`: + the k-th with the k-th among rows equal in every shared column, in row order, arrival + order on the async path), in linear time: never join repeats on the system tags alone, + which builds their cross product. The result's data context is read from its rows (some operators return rows in the default context, ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which rebuilds each input in its rows' data context. diff --git a/CLAUDE.md b/CLAUDE.md index 2d8577912..e500333e6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1546,13 +1546,20 @@ data. The rules: rows hold, only on what the inputs' columns show (system-tag names, a shared column's Arrow type, disjoint data columns): a row that matches nothing is left out, and rows of one origin row that differ in another shared column raise `RejoinDifferingColumnWarning` - once per operator and set of columns. System tags are assumed unique (no check reads the - rows; repeated ones pair in row order, arrival order on the async path, each row at most - once). A shared column keeps the - values of the first input that has it, in the canonical input order (by pipeline hash; - equal hashes stay in argument order, which only the bits of equal floats can follow). The - rows are matched on the system tags first, as before ITL-1355, and the pairs filtered, so - inputs whose shared columns agree give the same rows in the same order. The result's data + once per operator and set of columns. The warning is computed from the inputs' own rows + (`_differing_columns`: per shared column, the inputs that have it stacked and counted per + origin row), never from the rows rejoined so far, which have lost the origin rows an + earlier input lacks or disagrees on. System tags are assumed unique (no input is refused + for repeating one). A shared column keeps the values of the first input that has it, in + the canonical input order (by pipeline hash; equal hashes stay in argument order, which + only the bits of equal floats can follow). With unique system tags the rows are matched + on the system tags first, by the same join as before ITL-1355, and the pairs filtered, + so inputs whose shared columns agree give the same rows in the same order (Polars' join + order depends on the inputs' sizes: never replace that join). When an input repeats an + origin row, rows are paired one to one by occurrence number (`_pairs_of_repeated_origins`: + the k-th with the k-th among rows equal in every shared column, in row order, arrival + order on the async path), in linear time: never join repeats on the system tags alone, + which builds their cross product. The result's data context is read from its rows (some operators return rows in the default context, ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which rebuilds each input in its rows' data context. diff --git a/changelog.d/ITL-1355.md b/changelog.d/ITL-1355.md index 48a55c30a..1d9c297b8 100644 --- a/changelog.d/ITL-1355.md +++ b/changelog.d/ITL-1355.md @@ -17,9 +17,9 @@ match, and the shared column keeps the values of the first input that has it, in Rejoin's canonical input order (by pipeline hash; inputs with equal pipeline hashes stay in argument order); - - an input holding two rows of one origin row: no longer checked. System tags are + - an input holding two rows of one origin row: no longer refused. System tags are assumed unique, as every source makes them; repeated ones pair in row order, each row - at most once. + at most once, in time linear in the rows. `Rejoin` still refuses what the inputs' columns show: system-tag columns that differ or are absent, a shared column whose Arrow type differs, overlapping data columns. For every diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 9bef3d055..ac62382b8 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -222,10 +222,11 @@ The rules: shared column on rows of one origin row (two branches each add a tag `run` with different values, or change a tag's value), those rows are left out, and Rejoin names the columns in a `RejoinDifferingColumnWarning` (from `orcapod.errors`), once per operator and set of - columns. To keep the rows, drop or rename the column in one branch before the rejoin - (`drop_tag_columns`, `map_tags`). + columns. Every column in which two inputs differ on an origin row is named, whatever the + order of the inputs. To keep the rows, drop or rename the column in one branch before the + rejoin (`drop_tag_columns`, `map_tags`). - **Unique system tags.** System tags are assumed unique in each input, as every source - makes them, so each row matches at most once; nothing reads the rows to check it. Should + makes them, so each row matches at most once; no input is refused for repeating one. Should an input repeat an origin row, each row still matches at most once: among the rows equal in every shared column, the first of one input pairs with the first of the other, the second with the second, in row order (on the async path, the order the rows arrived in). diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index e66fde8f5..14cbc5672 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -56,11 +56,11 @@ pa = LazyModule("pyarrow") pl = LazyModule("polars") -# Row-number columns of the frames Polars matches, and the column that names a group of -# pairs; never a key (keys are columns of the inputs, and no input column starts so). +# Row-number columns of the frames Polars matches, and the column of a row's occurrence +# number; never a key (keys are columns of the inputs, and no input column starts so). _LEFT_ROW = "__rejoin_left_row" _RIGHT_ROW = "__rejoin_right_row" -_GROUP = "__rejoin_group" +_OCCURRENCE = "__rejoin_occurrence" def _system_tag_names(stream: StreamProtocol) -> list[str]: @@ -110,37 +110,125 @@ def _agreeing( ) -def _each_row_once(pairs: "pl.DataFrame") -> "pl.DataFrame": - """Keep each row in at most one pair. +def _repeats_an_origin(table: "pa.Table", keys: Sequence[str]) -> bool: + """Whether two rows of ``table`` hold the same system tags.""" + return bool(polars_key_frame(table, keys).is_duplicated().any()) + + +def _numbered( + table: "pa.Table", + keys: Sequence[str], + others: Sequence[str], + *, + among: Sequence[str], + row: str | None = None, +) -> "pl.DataFrame": + """Return the key frame of the rows that have their system tags, each numbered. + + A row with a null system tag matches nothing and is left out. Every other row gets + its occurrence number (``_OCCURRENCE``): how many rows before it, in row order, are + equal to it in the columns ``among``. With it, rows that repeat an origin row are + told apart, and two inputs' rows can be matched one to one in row order by a join + on the key columns and that number, without ever pairing every repeat of one input + with every repeat of the other. + + Args: + table: An input's rows. + keys: The system-tag columns. + others: The other columns to prepare beside them. + among: The columns whose equal rows are numbered 0, 1, 2, ... + row: The name of the row-number column, or ``None`` for none. + + Returns: + The prepared ``keys`` and ``others``, the row numbers when asked for, and the + occurrence numbers. + """ + frame = polars_key_frame(table, [*keys, *others], row) + return frame.filter( + pl.all_horizontal(pl.col(name).is_not_null() for name in keys) + ).with_columns(pl.int_range(pl.len()).over(list(among)).alias(_OCCURRENCE)) + + +def _pairs_of_repeated_origins( + left: "pa.Table", right: "pa.Table", keys: Sequence[str], others: Sequence[str] +) -> "pl.DataFrame": + """Pair rows one to one when an input repeats an origin row. System tags are assumed unique in each input (developer, November 22, 2026, - ITL-1355), so every row is in one pair already and ``pairs`` is returned as it is. - If an input does repeat an origin row, the rows of one origin row that agree pair - every left row with every right row; of those, the first left row keeps the first - right row, the second the second, and so on in row order (the order the rows - arrived in, on the async path), and the rows left over match nothing. + ITL-1355), so this is not the usual path. Should an input repeat an origin row, + each row still matches at most once: among the rows equal in every shared column, + the first of one input pairs with the first of the other, the second with the + second, and so on in row order (the order the rows arrived in, on the async path); + a row left over matches nothing. The work is linear in the rows: no pair is ever + made that is not kept. Args: - pairs: Row numbers of the rows that match and agree on every shared column. + left: The rows rejoined so far. + right: The next input's rows. + keys: The system-tag columns, in both tables. + others: The other columns both tables have. Returns: - The pairs to put together, in the order of ``pairs``. + The row numbers of the pairs, ``_LEFT_ROW`` and ``_RIGHT_ROW``, in the order + of ``left``'s rows. """ - left_rows, right_rows = pairs.get_column(_LEFT_ROW), pairs.get_column(_RIGHT_ROW) - if not (left_rows.is_duplicated().any() or right_rows.is_duplicated().any()): - return pairs - # The pairs of one such group share their right rows: its smallest names it. - group = pl.col(_RIGHT_ROW).min().over(_LEFT_ROW) + shared = [*keys, *others] return ( - pairs.with_columns(group.alias(_GROUP)) - .filter( - pl.col(_LEFT_ROW).rank("dense").over(_GROUP) - == pl.col(_RIGHT_ROW).rank("dense").over(_GROUP) + _numbered(left, keys, others, among=shared, row=_LEFT_ROW) + .join( + _numbered(right, keys, others, among=shared, row=_RIGHT_ROW), + on=[*shared, _OCCURRENCE], + how="inner", + nulls_equal=True, + maintain_order="left", ) - .drop(_GROUP) + .select(_LEFT_ROW, _RIGHT_ROW) ) +def _differing_columns(tables: Sequence["pa.Table"], keys: Sequence[str]) -> list[str]: + """Return the shared columns in which rows of one origin row differ between inputs. + + Read from the inputs' own rows, not from the rows rejoined so far (which no longer + hold an origin row an earlier input lacks or disagrees on): for every column + several inputs have besides the system tags, the rows of those inputs are put + under one another and counted per origin row. An origin row with two values in + the column is one where two inputs differ. Rows that repeat an origin row are + compared in row order, the first of each input with the first of the others + (``_numbered``). Equality is ``Join``'s, and a null equals a null. + + Args: + tables: The inputs' rows. + keys: The system-tag columns, in every table. + + Returns: + The names of the differing columns, in the order first met. + """ + holders: dict[str, list[int]] = {} + for index, table in enumerate(tables): + for name in table.column_names: + if name not in keys: + holders.setdefault(name, []).append(index) + # The columns several inputs have, by the inputs that have them. + shared: dict[tuple[int, ...], list[str]] = {} + for name, indices in holders.items(): + if len(indices) > 1: + shared.setdefault(tuple(indices), []).append(name) + origin = [*keys, _OCCURRENCE] + differing: list[str] = [] + for indices, names in shared.items(): + rows = pl.concat( + [_numbered(tables[index], keys, names, among=keys) for index in indices] + ) + origins = rows.select(origin).n_unique() + if rows.n_unique() == origins: + continue # every origin row holds one value in each of these columns + differing.extend( + name for name in names if rows.select([*origin, name]).n_unique() > origins + ) + return differing + + def _described(name: str, shared_tags: Collection[str]) -> str: """How a warning names a shared column that is not a system tag.""" if name in shared_tags: @@ -202,15 +290,17 @@ class Rejoin(Join): nothing (provenance is never null). In any other shared column a null equals a null, on purpose unlike ``Join``, where a null tag key matches nothing: two rows of one origin row that both hold no value in a column agree on it. When rows of one - origin row (their system tags match) differ in another shared column, a - ``RejoinDifferingColumnWarning`` names the columns, once per operator and set of - columns. + origin row (their system tags match) differ between two inputs in another shared + column, a ``RejoinDifferingColumnWarning`` names the columns, once per operator and + set of columns. It is read from the inputs' own rows, so it names every such + column whatever the order of the inputs, also when a third input lacks the row. System tags are assumed unique in each input, as every source makes them, so each - row matches at most once; no check reads the rows for it. Should an input repeat an - origin row, each row still matches at most once: among the rows equal in every - shared column, the first of one input pairs with the first of the other, the second - with the second, in row order (the order the rows arrived in, on the async path). + row matches at most once; no input is refused for repeating one. Should an input + repeat an origin row, each row still matches at most once: among the rows equal in + every shared column, the first of one input pairs with the first of the other, the + second with the second, in row order (the order the rows arrived in, on the async + path), in time linear in the rows. A shared column is kept once, with the values of the first input that has it. The inputs are taken in a canonical order, by pipeline hash, so the result does not @@ -348,18 +438,15 @@ def static_process(self, *streams: StreamProtocol) -> StreamProtocol: table = tables[0] user_tags = set(ordered_streams[0].keys()[0]) - differing: set[str] = set() for next_table, next_stream in zip(tables[1:], ordered_streams[1:]): next_tags = set(next_stream.keys()[0]) - table, differed = self._rejoin_pair( - table, next_table, keys, user_tags & next_tags - ) - differing.update( - _described(name, user_tags & next_tags) for name in differed - ) + table = self._rejoin_pair(table, next_table, keys, user_tags & next_tags) user_tags |= next_tags - if differing: - self._warn_differing_once(tuple(sorted(differing))) + # After the rows are paired: pairing checks that the shared columns' types agree. + if differing := _differing_columns(tables, keys): + self._warn_differing_once( + tuple(sorted(_described(name, user_tags) for name in differing)) + ) # Lay the columns out as Join does: tags, data, then the hidden columns. tag_order = list(tag_schema.keys()) @@ -441,7 +528,7 @@ def _rejoin_pair( right: "pa.Table", keys: Sequence[str], shared_tags: Collection[str], - ) -> tuple["pa.Table", list[str]]: + ) -> "pa.Table": """Pair the rows of two tables that are equal in every column both have. Every output value is taken from ``left`` or ``right`` by row number; Polars @@ -449,7 +536,10 @@ def _rejoin_pair( the system tags, as they always were (so inputs whose shared columns all agree give the same rows in the same order as before ITL-1355), and of those pairs only the ones that agree on every other shared column are kept (``_agreeing``). - A column both tables have is kept once, from ``left``. + With unique system tags each row is in one pair at most. When an input repeats + an origin row, that first match would pair every repeat with every repeat, so + the rows are paired one to one instead (``_pairs_of_repeated_origins``). A + column both tables have is kept once, from ``left``. Args: left: The rows rejoined so far. @@ -458,8 +548,7 @@ def _rejoin_pair( shared_tags: The user tags of both tables. Returns: - The paired rows, and the shared columns (other than system tags) in which - rows of one origin row differ. + The paired rows. Raises: InputValidationError: If a shared column's Arrow type differs, or has no @@ -480,25 +569,15 @@ def _rejoin_pair( arrow_utils.column_arrow_type(right.schema, name), ) require_matchable_key("Rejoin", name, shared_type) - matched = polars_key_frame(left, keys, _LEFT_ROW).join( - polars_key_frame(right, keys, _RIGHT_ROW), on=list(keys), how="inner" - ) - # Nothing matched, or nothing else is shared: there is nothing to compare. - pairs = ( - _agreeing(matched, left, right, keys, others) - if others and matched.height - else matched - ) - differed = ( - [ - name - for name in others - if _agreeing(matched, left, right, keys, [name]).height < matched.height - ] - if pairs.height < matched.height - else [] - ) - pairs = _each_row_once(pairs) + if _repeats_an_origin(left, keys) or _repeats_an_origin(right, keys): + pairs = _pairs_of_repeated_origins(left, right, keys, others) + else: + pairs = polars_key_frame(left, keys, _LEFT_ROW).join( + polars_key_frame(right, keys, _RIGHT_ROW), on=list(keys), how="inner" + ) + # Nothing matched, or nothing else is shared: there is nothing to compare. + if others and pairs.height: + pairs = _agreeing(pairs, left, right, keys, others) left_rows = pairs.get_column(_LEFT_ROW).to_arrow() right_rows = pairs.get_column(_RIGHT_ROW).to_arrow() names: list[str] = [] @@ -512,9 +591,8 @@ def _rejoin_pair( arrays.append(right.column(name).combine_chunks().take(right_rows)) table = pa.Table.from_arrays(arrays, names=names) table = arrow_utils.restore_schema_nullability(table, left.schema, right.schema) - return ( - self._shared_key_nullability(table, left.schema, right.schema, shared_tags), - differed, + return self._shared_key_nullability( + table, left.schema, right.schema, shared_tags ) async def async_execute( diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index 1d9684921..aad5f6cfa 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -24,6 +24,7 @@ from collections.abc import Sequence from pathlib import Path from typing import Any, cast +from unittest import mock import polars as pl import pyarrow as pa @@ -740,8 +741,9 @@ def test_several_shared_tags_several_inputs_in_every_order() -> None: for order in itertools.permutations((a, b, c)): result, warned = _rejoined(*order) assert _units(result) == [0, 3, 4, 5, 7] + # Every differing column is named, whatever the order of the inputs. assert len(warned) == 1 - assert any(f"tag {name!r}" in warned[0] for name in ("run", "site", "day")) + assert all(f"tag {name!r}" in warned[0] for name in ("run", "site", "day")) results.append(result) first = results[0] assert all(row["site"] == "x" and row["day"] == 5 for row in _user_rows(first)) @@ -847,6 +849,74 @@ def test_an_input_that_repeats_an_origin_row_pairs_each_row_once() -> None: assert result.as_table().num_rows == 9 +def _repeated(n: int, data: str, k: list[int] | None = None) -> ArrowTableStream: + """``n`` rows of ONE origin row: tag ``k``, one system tag, data ``data`` = 0..n-1.""" + table = pa.table( + { + "k": pa.array(k or [1] * n, pa.int64()), + data: pa.array(range(n), pa.int64()), + "origin": pa.array(["x"] * n, pa.large_string()), + } + ) + return ArrowTableStream(table, tag_columns=["k"], system_tag_columns=["origin"]) + + +def _join_sizes(compute: Any) -> tuple[Any, list[int]]: + """Run ``compute`` and return its result and the height of every Polars join in it.""" + sizes: list[int] = [] + join = pl.DataFrame.join + + def measured(frame: pl.DataFrame, *args: Any, **kwargs: Any) -> pl.DataFrame: + joined = join(frame, *args, **kwargs) + sizes.append(joined.height) + return joined + + with mock.patch.object(pl.DataFrame, "join", measured): + return compute(), sizes + + +def test_thousands_of_repeats_of_one_origin_row_are_paired_without_a_cross_product() -> ( + None +): + """Two inputs that each hold one origin row 3,000 times give 3,000 rows, the n-th + of one with the n-th of the other, and no join ever holds more rows than an input + (pairing every repeat with every repeat would make 9,000,000).""" + n = 3000 + with warnings.catch_warnings(): + warnings.simplefilter("error", RejoinDifferingColumnWarning) + table, sizes = _join_sizes( + lambda: Rejoin()(_repeated(n, "a"), _repeated(n, "b")).as_table() + ) + assert table.num_rows == n + assert table.column("a").to_pylist() == table.column("b").to_pylist() + assert sizes and max(sizes) <= n + # Fewer repeats in one input: the rows left over match nothing. + table, sizes = _join_sizes( + lambda: Rejoin()(_repeated(n, "a"), _repeated(n - 7, "b")).as_table() + ) + assert table.num_rows == n - 7 and max(sizes) <= n + assert table.column("a").to_pylist() == table.column("b").to_pylist() + + +def test_repeats_that_differ_in_a_shared_tag_pair_within_equal_values() -> None: + """Repeats of one origin row with two values of a shared tag, in opposite orders in + the two inputs: each row pairs with the next free row of the same value, in row + order, still without a cross product.""" + n = 2000 + left = _repeated(n, "a", [1, 2] * (n // 2)) + right = _repeated(n, "b", [2, 1] * (n // 2)) + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RejoinDifferingColumnWarning) + table, sizes = _join_sizes(lambda: Rejoin()(left, right).as_table()) + assert table.num_rows == n and max(sizes) <= n + rows = sorted(zip(*(table.column(c).to_pylist() for c in ("a", "b", "k")))) + # a = 0, 2, 4, ... hold k = 1, as b = 1, 3, 5, ... do; and the other way round. + assert rows == sorted( + [(i, i + 1, 1) for i in range(0, n, 2)] + + [(i, i - 1, 2) for i in range(1, n, 2)] + ) + + # --------------------------------------------------------------------------- # Equality is Join's; a shared column keeps the first input's values # --------------------------------------------------------------------------- @@ -1001,6 +1071,97 @@ def test_the_warning_is_issued_once_per_operator_and_set_of_columns() -> None: _ = strict.static_process(plain, other_run) +def _one_row(data: str, k: int, h: int, origin: str = "r") -> ArrowTableStream: + """One row: tags ``k`` and ``h``, one system tag, data column ``data``.""" + table = pa.table( + { + "k": pa.array([k], pa.int64()), + "h": pa.array([h], pa.int8()), + data: pa.array([0.5], pa.float64()), + "origin": pa.array([origin], pa.large_string()), + } + ) + return ArrowTableStream( + table, tag_columns=["k", "h"], system_tag_columns=["origin"] + ) + + +def _in_canonical_order(*data: str) -> list[str]: + """The data column names in the order Rejoin takes inputs holding them (their + pipeline hashes do not depend on the values).""" + return sorted(data, key=lambda name: _one_row(name, 0, 0).pipeline_hash().to_hex()) + + +def _rejoined_async(*inputs: Any) -> tuple[list[Any], list[str]]: + """The rows of the async path, and its ``RejoinDifferingColumnWarning``s.""" + from orcapod.channels import Channel + + async def run() -> list[Any]: + readers = [] + for stream in inputs: + channel: Channel[Any] = Channel() + for row in stream.iter_data(): + await channel.writer.send(row) + await channel.writer.close() + readers.append(channel.reader) + out: Channel[Any] = Channel() + await Rejoin().async_execute( + readers, + out.writer, + input_pipeline_hashes=[stream.pipeline_hash() for stream in inputs], + ) + return await out.reader.collect() + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + rows = asyncio.run(run()) + return rows, [ + str(w.message) + for w in caught + if issubclass(w.category, RejoinDifferingColumnWarning) + ] + + +def test_the_warning_names_every_differing_column_of_one_origin_row() -> None: + """Three inputs hold one origin row with ``(k, h)`` = (1, 1), (2, 1), (1, 2) in the + order Rejoin takes them: the first two differ in ``k``, so the row is gone before + the third is met, and the third differs in ``h``. Both are named, on the sync and + the async path, in every argument order (the warning is read from the inputs' own + rows, not from the rows rejoined so far).""" + first, second, third = _in_canonical_order("a", "b", "c") + inputs = (_one_row(first, 1, 1), _one_row(second, 2, 1), _one_row(third, 1, 2)) + for order in itertools.permutations(inputs): + result, warned = _rejoined(*order) + assert result.as_table().num_rows == 0 + assert len(warned) == 1 and "tag 'h', tag 'k'" in warned[0] + rows, warned = _rejoined_async(*order) + assert rows == [] + assert len(warned) == 1 and "tag 'h', tag 'k'" in warned[0] + + +def test_the_warning_sees_two_inputs_that_differ_where_another_lacks_the_row() -> None: + """The first input Rejoin takes holds another origin row only; the second and + third hold one origin row and differ in ``k``. Nothing is put together, and the + warning still names ``k`` (and not ``h``, which agrees), on both paths.""" + first, second, third = _in_canonical_order("a", "b", "c") + inputs = ( + _one_row(first, 1, 1, origin="elsewhere"), + _one_row(second, 1, 1), + _one_row(third, 2, 1), + ) + for order in itertools.permutations(inputs): + result, warned = _rejoined(*order) + assert result.as_table().num_rows == 0 + assert len(warned) == 1 and "tag 'k'" in warned[0] and "'h'" not in warned[0] + rows, warned = _rejoined_async(*order) + assert rows == [] + assert len(warned) == 1 and "tag 'k'" in warned[0] and "'h'" not in warned[0] + # Nothing differs: nothing warns, although nothing is put together either. + agreeing = (inputs[0], inputs[1], _one_row(third, 1, 1)) + for run in (_rejoined, _rejoined_async): + assert run(*agreeing)[1] == [] + + def test_a_diamond_through_operators_never_warns() -> None: """Branches that changed no shared column: every row is put together, no warning.""" source = _source(data_tags=True) From ffe67558025898835bb7e313b73999ccfe95663a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:22:10 -0800 Subject: [PATCH 3/4] docs(operators): Rejoin's warning compares repeated origin rows by occurrence (ITL-1355) With repeated origin rows the warning compares the repeats by occurrence, the first of one input with the first of another, and a surplus repeat (one more than another input holds) matches nothing whatever its values and is never compared: no warning names a column for it. Developer decision, no code change: repeats break the assumption that system tags are unique. Stated in Rejoin's docstring, the warning class, the concept page and the agent instructions, and pinned by a test (one row, no warning, sync and async, both argument orders). Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 4 +++- CLAUDE.md | 4 +++- docs/concepts/operators.md | 4 ++++ src/orcapod/core/operators/rejoin.py | 11 +++++++++-- src/orcapod/errors.py | 5 +++++ tests/test_core/operators/test_rejoin.py | 21 +++++++++++++++++++++ 6 files changed, 45 insertions(+), 4 deletions(-) diff --git a/.zed/rules b/.zed/rules index 08c8bb467..7be9a3735 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1506,7 +1506,9 @@ data. The rules: (`_differing_columns`: per shared column, the inputs that have it stacked and counted per origin row), never from the rows rejoined so far, which have lost the origin rows an earlier input lacks or disagrees on. System tags are assumed unique (no input is refused - for repeating one). A shared column keeps the values of the first input that has it, in + for repeating one); the warning compares repeats by occurrence, and a surplus repeat is + never compared, so it warns for none (developer, November 22, 2026: no code for it). A + shared column keeps the values of the first input that has it, in the canonical input order (by pipeline hash; equal hashes stay in argument order, which only the bits of equal floats can follow). With unique system tags the rows are matched on the system tags first, by the same join as before ITL-1355, and the pairs filtered, diff --git a/CLAUDE.md b/CLAUDE.md index e500333e6..518600abc 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1550,7 +1550,9 @@ data. The rules: (`_differing_columns`: per shared column, the inputs that have it stacked and counted per origin row), never from the rows rejoined so far, which have lost the origin rows an earlier input lacks or disagrees on. System tags are assumed unique (no input is refused - for repeating one). A shared column keeps the values of the first input that has it, in + for repeating one); the warning compares repeats by occurrence, and a surplus repeat is + never compared, so it warns for none (developer, November 22, 2026: no code for it). A + shared column keeps the values of the first input that has it, in the canonical input order (by pipeline hash; equal hashes stay in argument order, which only the bits of equal floats can follow). With unique system tags the rows are matched on the system tags first, by the same join as before ITL-1355, and the pairs filtered, diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index ac62382b8..84da815d6 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -230,6 +230,10 @@ The rules: an input repeat an origin row, each row still matches at most once: among the rows equal in every shared column, the first of one input pairs with the first of the other, the second with the second, in row order (on the async path, the order the rows arrived in). + The warning is narrower for such rows: it compares the repeats of an origin row by + occurrence (the first of one input with the first of another), and a surplus repeat, one + more than another input holds, matches nothing whatever its values and is never compared, + so no warning names a column for it. - **The first input's values.** A shared column is kept once, with the values of the first input that has it. Rejoin takes its inputs in a canonical order, by pipeline hash, so the result does not follow the order of the arguments; inputs with equal pipeline hashes (two diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index 14cbc5672..8d7a6f9a9 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -195,7 +195,10 @@ def _differing_columns(tables: Sequence["pa.Table"], keys: Sequence[str]) -> lis under one another and counted per origin row. An origin row with two values in the column is one where two inputs differ. Rows that repeat an origin row are compared in row order, the first of each input with the first of the others - (``_numbered``). Equality is ``Join``'s, and a null equals a null. + (``_numbered``); a surplus repeat, one more than another input holds, has nothing + to be compared with and names no column (developer decision, November 22, 2026: + repeats break the assumption that system tags are unique, and a surplus one is + left out whatever it holds). Equality is ``Join``'s, and a null equals a null. Args: tables: The inputs' rows. @@ -300,7 +303,11 @@ class Rejoin(Join): repeat an origin row, each row still matches at most once: among the rows equal in every shared column, the first of one input pairs with the first of the other, the second with the second, in row order (the order the rows arrived in, on the async - path), in time linear in the rows. + path), in time linear in the rows. The warning is narrower for such rows: it + compares the repeats of an origin row by occurrence (the first of one input with + the first of another, the second with the second), and a surplus repeat, one more + than another input holds, matches nothing whatever its values and is never + compared, so no warning names a column for it. A shared column is kept once, with the values of the first input that has it. The inputs are taken in a canonical order, by pipeline hash, so the result does not diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 6d063e6d3..cc62ba678 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -790,6 +790,11 @@ class RejoinDifferingColumnWarning(UserWarning): of the result. A branch changed that column, which is rarely meant, so this warning names such columns, once per operator and set of columns. + System tags are assumed unique in each input. Should an input repeat an origin row, + the repeats are compared by occurrence, the first of one input with the first of + another; a surplus repeat matches nothing whatever its values, and no warning is + issued for it. + To keep the rows, drop or rename the column in one branch before the rejoin (``drop_tag_columns``, ``map_tags``). To silence the warning, call ``warnings.filterwarnings("ignore", category=RejoinDifferingColumnWarning)``. diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index aad5f6cfa..484be6d5c 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -917,6 +917,27 @@ def test_repeats_that_differ_in_a_shared_tag_pair_within_equal_values() -> None: ) +def test_a_surplus_repeat_matches_nothing_and_warns_for_no_column() -> None: + """One input holds an origin row twice, with ``k`` = 1 and 2; the other holds it + once, with ``k`` = 1. The first rows are put together; the surplus repeat matches + nothing whatever it holds and is never compared, so no warning names ``k`` + (developer decision, November 22, 2026: with repeated origin rows the warning + compares repeats by occurrence). On the sync and the async path, in both orders.""" + twice = _repeated(2, "a", [1, 2]) + once = _repeated(1, "b", [1]) + for inputs in ((twice, once), (once, twice)): + result, warned = _rejoined(*inputs) + assert result.as_table().to_pylist() == [{"k": 1, "a": 0, "b": 0}] + assert warned == [] + rows, warned = _rejoined_async(*inputs) + assert [(tag["k"], data["a"], data["b"]) for tag, data in rows] == [(1, 0, 0)] + assert warned == [] + # The repeats in the other order: now the first rows differ, and ``k`` is named. + result, warned = _rejoined(_repeated(2, "a", [2, 1]), once) + assert result.as_table().num_rows == 1 + assert len(warned) == 1 and "tag 'k'" in warned[0] + + # --------------------------------------------------------------------------- # Equality is Join's; a shared column keeps the first input's values # --------------------------------------------------------------------------- From 662e0961283af554fd0cce8b8dacdf216108a293 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" <> Date: Sun, 22 Nov 2026 00:52:02 -0800 Subject: [PATCH 4/4] docs(operators): state two limits of Rejoin found in review, with tests (ITL-1355) Rows of several data contexts: each result row keeps its own in the data context column of the result's table, but the rows a stream yields one by one report the stream's one data context, as for any stream whose table holds rows of several (ITL-1359). The wording said more than that; it now says exactly that, and the test asserts both facts, for the result and for an input. Repeated origin rows with three or more inputs: the inputs are paired one after another in the canonical order, and a surplus repeat left out at one step is not considered again, so which repeats remain can depend on that order (by pipeline hash, never the argument order). Stated in the docstring and the concept page, and pinned by a test in all six argument orders. No change to what Rejoin computes. Co-Authored-By: Claude Fable 5.2 --- .zed/rules | 12 ++++-- CLAUDE.md | 12 ++++-- docs/concepts/operators.md | 16 ++++--- src/orcapod/core/operators/rejoin.py | 27 ++++++++---- tests/test_core/operators/test_rejoin.py | 53 +++++++++++++++++++++++- 5 files changed, 99 insertions(+), 21 deletions(-) diff --git a/.zed/rules b/.zed/rules index 7be9a3735..cca3287e3 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1507,7 +1507,10 @@ data. The rules: origin row), never from the rows rejoined so far, which have lost the origin rows an earlier input lacks or disagrees on. System tags are assumed unique (no input is refused for repeating one); the warning compares repeats by occurrence, and a surplus repeat is - never compared, so it warns for none (developer, November 22, 2026: no code for it). A + never compared, so it warns for none (developer, November 22, 2026: no code for it). With + repeats and three or more inputs the fold is pairwise in the canonical order and a surplus + repeat left out at one step is not considered again, so which repeats remain can follow + that order (documented; no order-free N-ary rule for repeats without a design). A shared column keeps the values of the first input that has it, in the canonical input order (by pipeline hash; equal hashes stay in argument order, which only the bits of equal floats can follow). With unique system tags the rows are matched @@ -1519,8 +1522,11 @@ data. The rules: order on the async path), in linear time: never join repeats on the system tags alone, which builds their cross product. The result's data context is read from its rows (some operators return rows in the default context, - ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which - rebuilds each input in its rows' data context. + ITL-1339); a result whose table holds rows of several data contexts keeps each in the + data context column, while the rows it yields one by one report the stream's one + context, as for any `ArrowTableStream` (`iter_data`'s limit, not Rejoin's: ITL-1359); N-ary and + commutative; identity `"Rejoin"`; async is the barrier, which rebuilds each input in its + rows' data context. - `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars decides which rows match, and every output column is taken from the input tables by row number (`take`), so every value is the input's, bit for bit (they used to carry every column diff --git a/CLAUDE.md b/CLAUDE.md index 518600abc..3f2b6a347 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1551,7 +1551,10 @@ data. The rules: origin row), never from the rows rejoined so far, which have lost the origin rows an earlier input lacks or disagrees on. System tags are assumed unique (no input is refused for repeating one); the warning compares repeats by occurrence, and a surplus repeat is - never compared, so it warns for none (developer, November 22, 2026: no code for it). A + never compared, so it warns for none (developer, November 22, 2026: no code for it). With + repeats and three or more inputs the fold is pairwise in the canonical order and a surplus + repeat left out at one step is not considered again, so which repeats remain can follow + that order (documented; no order-free N-ary rule for repeats without a design). A shared column keeps the values of the first input that has it, in the canonical input order (by pipeline hash; equal hashes stay in argument order, which only the bits of equal floats can follow). With unique system tags the rows are matched @@ -1563,8 +1566,11 @@ data. The rules: order on the async path), in linear time: never join repeats on the system tags alone, which builds their cross product. The result's data context is read from its rows (some operators return rows in the default context, - ITL-1339); N-ary and commutative; identity `"Rejoin"`; async is the barrier, which - rebuilds each input in its rows' data context. + ITL-1339); a result whose table holds rows of several data contexts keeps each in the + data context column, while the rows it yields one by one report the stream's one + context, as for any `ArrowTableStream` (`iter_data`'s limit, not Rejoin's: ITL-1359); N-ary and + commutative; identity `"Rejoin"`; async is the barrier, which rebuilds each input in its + rows' data context. - `Join` and `SemiJoin` give Polars only their key columns and row numbers (ITL-1284): Polars decides which rows match, and every output column is taken from the input tables by row number (`take`), so every value is the input's, bit for bit (they used to carry every column diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 84da815d6..009155368 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -233,16 +233,20 @@ The rules: The warning is narrower for such rows: it compares the repeats of an origin row by occurrence (the first of one input with the first of another), and a surplus repeat, one more than another input holds, matches nothing whatever its values and is never compared, - so no warning names a column for it. + so no warning names a column for it. With three or more inputs, the inputs are paired one + after another in their canonical order, and a surplus repeat left out at one step is not + considered again at a later one, so which repeats remain can depend on that order. - **The first input's values.** A shared column is kept once, with the values of the first input that has it. Rejoin takes its inputs in a canonical order, by pipeline hash, so the result does not follow the order of the arguments; inputs with equal pipeline hashes (two - branches of the same structure) stay in argument order. Only the bits of values that are - equal but not identical (`-0.0` and `0.0`, NaNs of different payloads) can follow it: no - row, hash or identity does. A tag of one input only is kept. + branches of the same structure) stay in argument order. With unique system tags only the + bits of values that are equal but not identical (`-0.0` and `0.0`, NaNs of different + payloads) can follow it: no row, hash or identity does. A tag of one input only is kept. - **Data contexts.** The data context is one of the shared columns: rows of different data - contexts match nothing, and each result row keeps its own. Only the default data context - ships, so this matters only for a stream built in another one. A known limitation + contexts match nothing. Each result row keeps its own in the data context column of the + result's table. A stream reports one data context, and so do the rows it yields one by + one (`iter_data`), as for any stream whose table holds rows of several (ITL-1359). Only the default + data context ships, so this matters only for a stream built in another one. A known limitation (ITL-1339): some operators (`PolarsFilter` and `MergeJoin`, likely `Join` and `SemiJoin` too) return their rows in the default data context whatever their input's, so in another data context the rows of a branch through one of them match nothing diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index 8d7a6f9a9..0976faa89 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -160,7 +160,9 @@ def _pairs_of_repeated_origins( the first of one input pairs with the first of the other, the second with the second, and so on in row order (the order the rows arrived in, on the async path); a row left over matches nothing. The work is linear in the rows: no pair is ever - made that is not kept. + made that is not kept. A row left over here is not considered again when a later + input is rejoined, so with three or more inputs the repeats that remain can depend + on the order in which the inputs are taken. Args: left: The rows rejoined so far. @@ -307,15 +309,21 @@ class Rejoin(Join): compares the repeats of an origin row by occurrence (the first of one input with the first of another, the second with the second), and a surplus repeat, one more than another input holds, matches nothing whatever its values and is never - compared, so no warning names a column for it. + compared, so no warning names a column for it. With three or more inputs, the + inputs are paired one after another in their canonical order, and a surplus repeat + left out at one step is not considered again at a later one: which repeats remain + can then depend on that order. A shared column is kept once, with the values of the first input that has it. The inputs are taken in a canonical order, by pipeline hash, so the result does not follow the order of the arguments; inputs with equal pipeline hashes (two branches - of the same structure) stay in argument order. Only the bits of values that are - equal but not identical (``-0.0`` and ``0.0``, NaNs of different payloads) can - follow it; no row, hash or identity does. A tag of one input is kept. The result - keeps the common system-tag columns unchanged, and its rows' data context. + of the same structure) stay in argument order. With unique system tags only the + bits of values that are equal but not identical (``-0.0`` and ``0.0``, NaNs of + different payloads) can follow it; no row, hash or identity does. A tag of one + input is kept. The result keeps the common system-tag columns unchanged. Each row + keeps its own data context in the data context column of the result's table; like + any stream, the result reports one data context, and so do the rows it yields one + by one (``iter_data``), also when its table holds rows of several. Inputs from two different sources with the same schema share their system-tag column names but no value: their rejoin is empty, not an error. To combine different rows @@ -482,8 +490,11 @@ def _rows_data_context( operator's lazy stream reports its pod's context, ITL-1339). Matched rows are of one data context each, so a result usually has one; with no result row it is the inputs' rows' own. Should rows of several remain (inputs that each hold rows - of several data contexts), the stream takes the first key in text order: every - row still carries its own in the data context column. + of several data contexts), the stream takes the first key in text order. Every + row still carries its own in the data context column of the table; the rows + the stream yields one by one report the stream's, as those of any stream that + holds rows of several data contexts do (``ArrowTableStream.iter_data``, + ITL-1359). Args: result: The rejoined rows. diff --git a/tests/test_core/operators/test_rejoin.py b/tests/test_core/operators/test_rejoin.py index 484be6d5c..c4bda4a42 100644 --- a/tests/test_core/operators/test_rejoin.py +++ b/tests/test_core/operators/test_rejoin.py @@ -938,6 +938,42 @@ def test_a_surplus_repeat_matches_nothing_and_warns_for_no_column() -> None: assert len(warned) == 1 and "tag 'k'" in warned[0] +def test_repeats_and_three_inputs_are_paired_in_the_canonical_order() -> None: + """With repeated origin rows and three inputs, the inputs are paired one after + another in Rejoin's canonical order, and a surplus repeat left out at one step is + not considered again. ``A`` holds one origin row twice (``k`` = 1 and 2), ``B`` + once without ``k``, ``C`` once with ``k`` = 2. When ``A`` and ``B`` are put + together before ``C`` is met, ``B`` takes ``A``'s first row and ``C`` then matches + nothing; otherwise ``A``'s second row is put together with ``C`` and ``B``. The + result follows that order (by pipeline hash), never the order of the arguments.""" + + def branch(data: str, k: list[int] | None, n: int) -> ArrowTableStream: + columns: dict[str, Any] = {} if k is None else {"k": pa.array(k, pa.int64())} + columns |= { + "g": pa.array([7] * n, pa.int64()), + data: pa.array(range(n), pa.int64()), + "origin": pa.array(["r"] * n, pa.large_string()), + } + return ArrowTableStream( + pa.table(columns), + tag_columns=[name for name in ("k", "g") if name in columns], + system_tag_columns=["origin"], + ) + + inputs = { + "A": branch("a", [1, 2], 2), + "B": branch("b", None, 1), + "C": branch("c", [2], 1), + } + canonical = sorted(inputs, key=lambda name: inputs[name].pipeline_hash().to_hex()) + assert len({stream.pipeline_hash() for stream in inputs.values()}) == 3 + expected = [] if canonical[2] == "C" else [{"k": 2, "g": 7, "a": 1, "b": 0, "c": 0}] + for order in itertools.permutations(inputs.values()): + with warnings.catch_warnings(): + warnings.simplefilter("ignore", RejoinDifferingColumnWarning) + assert Rejoin()(*order).as_table().to_pylist() == expected + + # --------------------------------------------------------------------------- # Equality is Join's; a shared column keeps the first input's values # --------------------------------------------------------------------------- @@ -1228,7 +1264,9 @@ def test_rows_of_different_data_contexts_match_nothing( def test_rows_keep_their_own_data_context(other_context: contexts.DataContext) -> None: """Inputs holding rows of two data contexts: the rows whose contexts agree are put - together, each keeping its own in the data context column.""" + together, each keeping its own in the data context column of the result's table. + The rows the result yields one by one report the stream's one data context, as + those of any stream whose table holds rows of several do (the inputs here too).""" default = contexts.get_default_context().context_key def mixed(keys: list[str], data: str) -> ArrowTableStream: @@ -1258,3 +1296,16 @@ def mixed(keys: list[str], data: str) -> ArrowTableStream: ) assert rows == {1: OTHER_CONTEXT, 2: default} assert len(warned) == 1 and "the data context" in warned[0] + # The stream reports one data context, the first key in text order, and the + # rows it yields one by one report that one. + assert result.data_context_key == min(OTHER_CONTEXT, default) + assert [data.data_context_key for _, data in result.iter_data()] == ( + [result.data_context_key] * 2 + ) + # So does any stream whose table holds rows of several data contexts. + assert a.as_table(columns={"context": True}).column( + constants.CONTEXT_KEY + ).to_pylist() == [OTHER_CONTEXT, default, OTHER_CONTEXT] + assert [data.data_context_key for _, data in a.iter_data()] == ( + [a.data_context_key] * 3 + )