From 76c3b95b52804ce7d9622e45b15f2e19ef85dcde Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 17:19:25 -0800 Subject: [PATCH 1/3] fix(operators): Join declares its commutative group once, in argument_symmetry (ITL-1854) Join answered every identity from a second, class-fixed declaration (structural_argument_symmetry, ITL-1590), so a Join subclass declaring a tuple was hashed as commutative: op(a, b) and op(b, a) shared one pipeline hash, content hash and stored path, and a job kept only one branch. Join.argument_symmetry now returns a SymmetricGroup (keeps repeated inputs, hashes no stream) and the separate override is deleted. The saved-job order check accepts a SymmetricGroup. No built-in hash moves. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1854.md | 8 + docs/reference/hashing.md | 2 +- src/orcapod/core/operators/join.py | 7 +- src/orcapod/pipeline/serialization.py | 12 +- .../operators/test_join_argument_symmetry.py | 193 ++++++++++++++++++ .../operators/test_join_tag_order.py | 2 +- tests/test_core/operators/test_operators.py | 11 +- tests/test_core/test_order_invariance.py | 3 +- 8 files changed, 221 insertions(+), 17 deletions(-) create mode 100644 changelog.d/ITL-1854.md create mode 100644 tests/test_core/operators/test_join_argument_symmetry.py diff --git a/changelog.d/ITL-1854.md b/changelog.d/ITL-1854.md new file mode 100644 index 000000000..df40e4e62 --- /dev/null +++ b/changelog.d/ITL-1854.md @@ -0,0 +1,8 @@ +### Fixed + +- A `Join` subclass that declares its inputs ordered (`argument_symmetry` returning a + tuple) is ordered again (ITL-1854). Since ITL-1590, `Join` answered every identity from a + second, fixed declaration, so `op(a, b)` and `op(b, a)` shared one pipeline hash, content + hash and stored path, and a job kept only one of the two branches. `Join` now declares + its commutative group once, in `argument_symmetry` (a `SymmetricGroup`, which keeps + repeated inputs and hashes no stream). No hash of a built-in operator moves. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 365a3703d..61663174c 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -711,7 +711,7 @@ source chain. Some structures below also contribute to the inputs of those chain | `SpiralDBTableSource` | `(source_id, Arrow schema identity, record ID key tuple)`, the rule of every root source (no class name, ITL-1425), then the sorted `tags_as_data` items when given | A restriction (`where`, `limit`, `asof`) chooses rows of the same table and adds nothing | | `CachedSource` | the wrapped source's identity | | | Operators (unary) | `(operator_class_name, upstream_stream)` | Stream reference resolved via `content_resolver` | -| Operators (binary/N-ary) | `(operator_class_name, argument_symmetry(streams))` | `frozenset` for commutative (Join); `tuple` for ordered (SemiJoin, MergeJoin: ITL-1281) | +| Operators (binary/N-ary) | `(operator_class_name, argument_symmetry(streams))` | `SymmetricGroup` for commutative (Join, Rejoin; ITL-1854: the one declaration every identity reads, so a subclass that declares a `tuple` is ordered); `tuple` for ordered (SemiJoin, MergeJoin: ITL-1281) | | `SelectTagColumns`, `SelectDataColumns`, `DropTagColumns`, `DropDataColumns`, `SelectColumns`, `DropColumns` | `(operator_class_name, sorted unique column names as a list, strict)` | The operators act on a set of names: a list, a tuple, a set, a single string, a repeated or a reordered name list give one hash (ITL-942) | | `MapTags`, `MapData`, `MapColumns` | `(operator_class_name, name_map, drop_unmapped, strict)` | An operator's identity is its full configuration, `strict` included, as for the column selection operators (ITL-1160) | | `AddTags` | `(operator_class_name, ((name, value), ...) in name order)` | The new tags are a set: the order they are given in never enters the identity, and the tags are placed in name order (ITL-1269) | diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index b7b99e3e5..b7c7fa4cd 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -510,13 +510,8 @@ def order_input_streams(self, *streams: StreamProtocol) -> list[StreamProtocol]: return sorted(streams, key=lambda s: s.pipeline_hash().to_hex()) def argument_symmetry(self, streams: Collection) -> ArgumentGroup: - return frozenset(streams) - - def structural_argument_symmetry( - self, streams: tuple[StreamProtocol, ...] - ) -> ArgumentGroup: """Declare every interchangeable occurrence without comparing the streams.""" - return SymmetricGroup(streams) + return SymmetricGroup(tuple(streams)) def output_schema( self, diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 71d9dc394..408fe6e1e 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -12,6 +12,7 @@ from typing import TYPE_CHECKING, Any, TypeAlias, cast from orcapod.types import Schema +from orcapod.types.argument_groups import SymmetricGroup from orcapod.logical_types.canonical_form import ( declaration_form_field, declaration_form_schema, @@ -78,8 +79,8 @@ def require_positively_commutative( Its argument order cannot be known, so an operator node with two or more different inputs is accepted only when it is positively known to be fully commutative: the operator is available, and ``argument_symmetry``, called as its - contract requires (on the rebuilt input streams), returns a flat ``frozenset`` of - exactly those inputs. A binary operator with other than two edges (one stream + contract requires (on the rebuilt input streams), returns a flat ``SymmetricGroup`` + or ``frozenset`` of exactly those inputs. A binary operator with other than two edges (one stream given twice) cannot have its inputs restored and is refused too. Anything else (the call raises, a tuple, a nested group, an operator that is not available, an input not restored) is refused: when in doubt, refuse. @@ -120,9 +121,12 @@ def require_positively_commutative( symmetry = operator.argument_symmetry(input_streams) except Exception as exc: raise refusal from exc - if not isinstance(symmetry, frozenset): + if isinstance(symmetry, SymmetricGroup): + members = symmetry.members + elif isinstance(symmetry, frozenset): + members = cast("frozenset[Any]", symmetry) + else: raise refusal - members = cast("frozenset[Any]", symmetry) if {id(member) for member in members} != {id(stream) for stream in input_streams}: raise refusal diff --git a/tests/test_core/operators/test_join_argument_symmetry.py b/tests/test_core/operators/test_join_argument_symmetry.py new file mode 100644 index 000000000..230718cb6 --- /dev/null +++ b/tests/test_core/operators/test_join_argument_symmetry.py @@ -0,0 +1,193 @@ +"""A ``Join`` declares its argument symmetry once, in ``argument_symmetry`` (ITL-1854). + +Every identity (pipeline hash, content hash, the capture key of a job, the stored path +of a node) reads that one declaration. A ``Join`` subclass that declares its inputs +ordered (a ``tuple``) therefore gives ``op(a, b)`` and ``op(b, a)`` two identities and +two nodes; before ITL-1854, ``Join`` answered a second, class-fixed declaration and the +capture kept only the first of the two branches. The built-in operators keep their +symmetry and their hashes, pinned below. +""" + +from __future__ import annotations + +import asyncio +from collections.abc import Collection +from typing import Any + +import pytest +from typing_extensions import override + +from orcapod import PipelineJob +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol +from orcapod.sources import DictSource +from orcapod.types import ColumnConfig, Schema +from orcapod.types.argument_groups import SymmetricGroup + + +def _source(name: str, first: str, second: str, shift: int) -> DictSource: + """Two tag columns and two data columns.""" + rows = [ + {"region": "north", "item": 1, first: 5 + shift, second: 7}, + {"region": "south", "item": 2, first: 11 + shift, second: 13}, + ] + return DictSource( + rows, tag_columns=["region", "item"], tag_only_columns=True, source_id=name + ) + + +class FirstInputJoin(Join): + """A ``Join`` subclass whose inputs have roles: it keeps the first input's rows.""" + + @override + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: + return tuple(streams) + + @override + def validate_inputs(self, *streams: StreamProtocol) -> None: + SemiJoin().validate_inputs(*streams) + + @override + def output_schema( + self, + *streams: StreamProtocol, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[Schema, Schema]: + return SemiJoin().output_schema(*streams, columns=columns, all_info=all_info) + + @override + def static_process(self, *streams: StreamProtocol) -> StreamProtocol: + return SemiJoin().static_process(*streams) + + +def test_an_ordered_join_subclass_has_one_identity_per_order() -> None: + a, b = _source("a", "x", "y", 0), _source("b", "u", "v", 100) + ab, ba = FirstInputJoin()(a, b), FirstInputJoin()(b, a) + assert ab.keys()[1] == ("x", "y") + assert ba.keys()[1] == ("u", "v") + assert ab.pipeline_hash() != ba.pipeline_hash() + assert ab.content_hash() != ba.content_hash() + + +@pytest.mark.parametrize("run_async", [False, True], ids=["sync", "async"]) +def test_an_ordered_join_subclass_keeps_both_branches_in_a_job( + run_async: bool, +) -> None: + a, b = _source("a", "x", "y", 0), _source("b", "u", "v", 100) + operator = FirstInputJoin() + job = PipelineJob(name="ordered_join", database=InMemoryArrowDatabase()) + with job: + _ = operator(a, b, label="ab") + _ = operator(b, a, label="ba") + if run_async: + _ = asyncio.run(job.run_async()) + else: + _ = job.run() + + assert sorted(job.nodes) == ["a", "ab", "b", "ba"] + ab, ba = job.nodes["ab"], job.nodes["ba"] + assert ab.pipeline_hash() != ba.pipeline_hash() + assert ab.content_hash() != ba.content_hash() + assert ab.node_identity_path != ba.node_identity_path + first = ab.as_table().sort_by("item") + second = ba.as_table().sort_by("item") + assert first.select(["region", "item", "x", "y"]).to_pylist() == [ + {"region": "north", "item": 1, "x": 5, "y": 7}, + {"region": "south", "item": 2, "x": 11, "y": 13}, + ] + assert second.select(["region", "item", "u", "v"]).to_pylist() == [ + {"region": "north", "item": 1, "u": 105, "v": 7}, + {"region": "south", "item": 2, "u": 111, "v": 13}, + ] + + +def test_join_declares_every_occurrence_without_hashing_the_inputs() -> None: + """A repeated input is kept, and the declaration reads no stream hash.""" + hashed: list[str] = [] + + class Watched(DictSource): + @override + def __hash__(self) -> int: + hashed.append(self.source_id) + return id(self) + + a = Watched( + [{"k": 1, "x": 1}], tag_columns=["k"], tag_only_columns=True, source_id="a" + ) + b = Watched( + [{"k": 1, "y": 1}], tag_columns=["k"], tag_only_columns=True, source_id="b" + ) + symmetry = Join().argument_symmetry((a, b, a)) + assert isinstance(symmetry, SymmetricGroup) + assert [id(member) for member in symmetry.members] == [id(a), id(b), id(a)] + assert hashed == [] + + +# The values main computed before ITL-1854: the fix moves no built-in hash. +_PINNED = { + "Join": ( + "semantic_v1:a39fca094af0ab19137a63bc97731ce2e6e6cf43fe7b724cefbbb37dcd2e7fba", + "content_hash_v1:d82655f5cbd2fc9a1e9ab7291e10d5e6d9ba666f368c38d8fe24e8f8fb3c24a3", + ), + "Rejoin": ( + "semantic_v1:8394a3f839b83cc529efd8899e5680dd4e7179afcdcc373bf7fe1af7b02e92cb", + "content_hash_v1:55cee396f41df3e76167668b39b703ac34b779dd035c1e5b7ae93bf7a4522a85", + ), + "SemiJoin": ( + "semantic_v1:04d1c4d95a268eca06217226e6096c83366b96a81a52d9f41dd6b00fd3102915", + "content_hash_v1:0f1366acb65aef837f21913da4e469fff18bb79ff6900e5b16c33aaefaacd090", + ), + "SemiJoin reversed": ( + "semantic_v1:32baf9ce7adae65ea6b2210cdabbd925527bcd61370a21c46dcb6ab8b6c983eb", + "content_hash_v1:bf30a29c4af48d1a0cb2dc47daa7e9c3e476ebf74c2dc9d978bbb76ce177defc", + ), + "MergeJoin": ( + "semantic_v1:8e7677a4b61ea2c86dbbcdb84fb901e4d6f788c788bcbe7cb55afdf235d0cc0c", + "content_hash_v1:d525bcc5971b277d602e90c0104c08e42d300270c830ccd85403570f29d0bd88", + ), + "MergeJoin reversed": ( + "semantic_v1:0890716f3bfa7d9f7a3c4cdf27faa68b9503474df7f5c2e79a601ac2f930ea13", + "content_hash_v1:08906fc856f001a0512e16bede50855932814f5c89bfbea86ad0967440b9efe3", + ), +} + + +def _hashes(stream: StreamProtocol) -> tuple[str, str]: + return stream.pipeline_hash().to_string(), stream.content_hash().to_string() + + +@pytest.mark.parametrize("operator", [Join, Rejoin], ids=["Join", "Rejoin"]) +def test_commutative_built_ins_keep_their_symmetry_and_hash(operator: type) -> None: + if operator is Join: + first, second = _source("a", "x", "y", 0), _source("b", "u", "v", 100) + else: + base = _source("a", "x", "y", 0) + first = base.select_data_columns(["x"]) + second = base.select_data_columns(["y"]) + symmetry = operator().argument_symmetry((first, second)) + assert isinstance(symmetry, SymmetricGroup) + pinned = _PINNED[operator.__name__] + assert _hashes(operator()(first, second)) == pinned + assert _hashes(operator()(second, first)) == pinned + + +@pytest.mark.parametrize( + ("operator", "second_columns"), + [(SemiJoin, ("u", "v")), (MergeJoin, ("x", "v"))], + ids=["SemiJoin", "MergeJoin"], +) +def test_ordered_built_ins_keep_their_symmetry_and_hash( + operator: type, second_columns: tuple[str, str] +) -> None: + name = "b" if operator is SemiJoin else "m" + first = _source("a", "x", "y", 0) + second = _source(name, *second_columns, 100) + symmetry = operator().argument_symmetry((first, second)) + assert isinstance(symmetry, tuple) + assert [id(member) for member in symmetry] == [id(first), id(second)] + assert _hashes(operator()(first, second)) == _PINNED[operator.__name__] + assert ( + _hashes(operator()(second, first)) == _PINNED[f"{operator.__name__} reversed"] + ) diff --git a/tests/test_core/operators/test_join_tag_order.py b/tests/test_core/operators/test_join_tag_order.py index 27334f412..292dbe789 100644 --- a/tests/test_core/operators/test_join_tag_order.py +++ b/tests/test_core/operators/test_join_tag_order.py @@ -1,6 +1,6 @@ """Column order produced by Join and MergeJoin. -``Join`` is commutative (``argument_symmetry`` returns a ``frozenset``), so its +``Join`` is commutative (``argument_symmetry`` returns a ``SymmetricGroup``), so its column order must not depend on the order of the operands: tag and data columns are listed by first appearance across the inputs taken in canonical ``pipeline_hash`` order. ``MergeJoin`` is ordered (ITL-1281): its columns follow diff --git a/tests/test_core/operators/test_operators.py b/tests/test_core/operators/test_operators.py index f774afe92..9a6931c23 100644 --- a/tests/test_core/operators/test_operators.py +++ b/tests/test_core/operators/test_operators.py @@ -19,6 +19,7 @@ ) from orcapod.core.streams import ArrowTableStream from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol +from orcapod.types.argument_groups import SymmetricGroup # PolarsFilter is built here on purpose; the warning of every construction is tested in # test_polars_filter_warning.py (ITL-1296). @@ -512,7 +513,7 @@ def test_join_output_schema(self, simple_stream, disjoint_stream): def test_join_is_commutative(self, simple_stream, disjoint_stream): op = Join() sym = op.argument_symmetry([simple_stream, disjoint_stream]) - assert isinstance(sym, frozenset) + assert isinstance(sym, SymmetricGroup) class TestJoinWithListExtensionColumn: @@ -1066,11 +1067,13 @@ def test_batch_argument_symmetry(self, simple_stream): # --- Join: commutative → frozenset --- - def test_join_argument_symmetry_is_frozenset(self, simple_stream, disjoint_stream): + def test_join_argument_symmetry_is_symmetric_group( + self, simple_stream, disjoint_stream + ): op = Join() sym = op.argument_symmetry([simple_stream, disjoint_stream]) - assert isinstance(sym, frozenset) - assert sym == frozenset([simple_stream, disjoint_stream]) + assert isinstance(sym, SymmetricGroup) + assert sym.members == (simple_stream, disjoint_stream) def test_join_argument_symmetry_order_invariant( self, simple_stream, disjoint_stream diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index f304cf75d..d93595045 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -68,6 +68,7 @@ streams, ) from orcapod.channels import Channel +from orcapod.types.argument_groups import SymmetricGroup from orcapod.core.nodes import OperatorJobNode, SourceJobNode from orcapod.core.nodes.function_node import ( PIPELINE_RECORDED_AT_COL, @@ -660,7 +661,7 @@ def _commutative_cases() -> list[Any]: for case in cases for role in case.roles if len(case.inputs) > 1 - and isinstance(case.build().argument_symmetry([]), frozenset) + and isinstance(case.build().argument_symmetry([]), (frozenset, SymmetricGroup)) ] From 18e9ce284195281d848420b513be09e3e359c7a4 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:02:22 -0800 Subject: [PATCH 2/3] test(pipeline): cover a custom operator declaring a frozenset; update symmetry wording (ITL-1854) Review of the ITL-1854 PR: - S1: a legacy file with a custom commutative BinaryOperator (which declares a flat frozenset) loads in either argument order with the live rows; the test fails when the frozenset branch of require_positively_commutative is removed. - N1, N2: the argument_symmetry docstrings and a test comment show SymmetricGroup for Join and say that a frozenset collapses repeated inputs. Co-Authored-By: Claude Opus 5.5 --- .../core/operators/static_output_pod.py | 12 ++-- src/orcapod/protocols/core_protocols/pod.py | 27 ++++---- .../test_loaded_argument_order.py | 61 ++++++++++++++++++- 3 files changed, 84 insertions(+), 16 deletions(-) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f41272d4f..53387c926 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -267,22 +267,26 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou """Describe symmetry/ordering constraints on input arguments. Returns a structure encoding which arguments can be reordered: - - ``frozenset``: Arguments commute (order doesn't matter). + - ``SymmetricGroup``: Arguments commute (order doesn't matter); every + occurrence is kept, so an input given twice counts twice. + - ``frozenset``: Arguments commute too, but a set collapses repeated inputs + and hashes its members (the streams); prefer ``SymmetricGroup``. - ``tuple``: Arguments have fixed positions. - Nesting expresses partial symmetry. Examples: Full symmetry (Join):: - return frozenset([a, b, c]) + return SymmetricGroup((a, b, c)) No symmetry (Concatenate):: return (a, b, c) - Partial symmetry:: + Partial symmetry (``a`` and ``b`` are interchangeable, ``c`` has a + fixed position):: - return (frozenset([a, b]), c) + return (SymmetricGroup((a, b)), c) """ ... diff --git a/src/orcapod/protocols/core_protocols/pod.py b/src/orcapod/protocols/core_protocols/pod.py index 4b8c41cac..b27b05d83 100644 --- a/src/orcapod/protocols/core_protocols/pod.py +++ b/src/orcapod/protocols/core_protocols/pod.py @@ -66,24 +66,29 @@ def validate_inputs(self, *streams: StreamProtocol) -> None: ... def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: - """ - Describe symmetry/ordering constraints on input arguments. + """Describe symmetry/ordering constraints on input arguments. Returns a structure encoding which arguments can be reordered: - - frozenset: Arguments commute (order doesn't matter) - - OrderedGroup (tuple): Arguments have fixed positions - - Nesting expresses partial symmetry + - ``SymmetricGroup``: Arguments commute (order doesn't matter); every + occurrence is kept, so an input given twice counts twice. + - ``frozenset``: Arguments commute too, but a set collapses repeated inputs + and hashes its members (the streams); prefer ``SymmetricGroup``. + - ``tuple``: Arguments have fixed positions. + - Nesting expresses partial symmetry. Examples: - Full symmetry (Join): - return frozenset([a, b, c]) + Full symmetry (Join):: + + return SymmetricGroup((a, b, c)) + + No symmetry (Concatenate):: - No symmetry (Concatenate): return (a, b, c) - Partial symmetry: - return (frozenset([a, b]), c) - # a,b are interchangeable, c has fixed position + Partial symmetry (``a`` and ``b`` are interchangeable, ``c`` has a + fixed position):: + + return (SymmetricGroup((a, b)), c) """ ... diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index 6d8dfcbee..9b5a09367 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -46,7 +46,8 @@ def test_every_multi_input_operator_is_classified() -> None: ): continue # Placeholders stand for two different streams: only the kind of the - # returned group (tuple: ordered, frozenset: commutative) is read. + # returned group (tuple: ordered; SymmetricGroup, or a frozenset, which + # collapses repeated inputs: commutative) is read. two_inputs: Any = ("a", "b") symmetry = cls().argument_symmetry(two_inputs) (ordered if isinstance(symmetry, tuple) else commutative).add(name) @@ -266,7 +267,38 @@ def argument_symmetry(self, streams: Collection[Any]) -> Any: return frozenset((tuple(streams),)) +class CommutativeBinaryJoin(BinaryOperator): + """A custom commutative binary operator: ``is_commutative()`` is true, so the + inherited ``argument_symmetry`` declares a flat ``frozenset`` of the streams (the + form the saved-job order check still accepts besides a ``SymmetricGroup``).""" + + def validate_binary_inputs(self, left_stream: Any, right_stream: Any) -> None: + Join().validate_inputs(left_stream, right_stream) + + def binary_static_process(self, left_stream: Any, right_stream: Any) -> Any: + return Join().static_process(left_stream, right_stream) + + def binary_output_schema( + self, + left_stream: Any, + right_stream: Any, + *, + columns: Any = None, + all_info: bool = False, + ) -> Any: + return Join().output_schema( + left_stream, right_stream, columns=columns, all_info=all_info + ) + + def is_commutative(self) -> bool: + return True + + def identity_structure(self) -> Any: + return self.__class__.__name__ + + register_operator("SchemaAwareJoin", SchemaAwareJoin) +register_operator("CommutativeBinaryJoin", CommutativeBinaryJoin) register_operator("SchemaAwareSemiJoin", SchemaAwareSemiJoin) register_operator("NestedMergeJoin", NestedMergeJoin) @@ -311,6 +343,33 @@ def test_a_legacy_custom_commutative_operator_that_reads_its_streams_loads( assert _rows(loaded.step.as_table()) == _rows(job.step.as_table()) +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_c", "c_a"]) +def test_a_legacy_custom_operator_declaring_a_frozenset_loads( + reverse: bool, blueprint: bool, tmp_path: Path +) -> None: + """A custom operator still declaring commutativity as a flat ``frozenset`` (here a + commutative ``BinaryOperator``) is positively commutative: its legacy file loads in + either argument order and gives the live rows, as on main (ITL-1854 review).""" + assert isinstance( + CommutativeBinaryJoin().argument_symmetry(("a", "c")), # pyright: ignore[reportArgumentType] # Placeholders; only the kind is read. + frozenset, + ) + + def make(s: dict[str, Any]) -> Any: + pair = (s["a"].select_data_columns(["y"]), s["c"]) + first, second = reversed(pair) if reverse else pair + return CommutativeBinaryJoin()(first, second, label="step") + + path, db_path, job = _legacy_custom(tmp_path, make, blueprint) + if blueprint: + assert "step" in Pipeline.load(path).nodes + else: + loaded = PipelineJob.load(path, database=DeltaTableDatabase(db_path)) + loaded.run(load_only=True) + assert _rows(loaded.step.as_table()) == _rows(job.step.as_table()) + + @pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) @pytest.mark.parametrize( "make", From 7a43383f1238cd488365fac84d9ed057d95ba741 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Tue, 1 Dec 2026 18:37:04 -0800 Subject: [PATCH 3/3] fix(pipeline): the legacy order check counts SymmetricGroup occurrences (ITL-1854) CodeRabbit on PR 694: require_positively_commutative compared the set of input ids, so a SymmetricGroup naming the same inputs with another multiplicity passed it and was refused later by the structural identity with an internal error. A SymmetricGroup counts every occurrence (ITL-1590), so the check now compares the multiset; a frozenset, which collapses repeats, still names only which inputs commute. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/serialization.py | 15 +++- .../test_loaded_argument_order.py | 79 ++++++++++++++++++- 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 408fe6e1e..944552185 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -6,6 +6,7 @@ import json as _json import logging import re +from collections import Counter from collections.abc import Callable, Collection, Iterable from enum import Enum from functools import partial @@ -80,7 +81,8 @@ def require_positively_commutative( different inputs is accepted only when it is positively known to be fully commutative: the operator is available, and ``argument_symmetry``, called as its contract requires (on the rebuilt input streams), returns a flat ``SymmetricGroup`` - or ``frozenset`` of exactly those inputs. A binary operator with other than two edges (one stream + of exactly those inputs, each as many times as it is an input (ITL-1590), or a + flat ``frozenset`` of exactly those inputs (a set collapses repeats). A binary operator with other than two edges (one stream given twice) cannot have its inputs restored and is refused too. Anything else (the call raises, a tuple, a nested group, an operator that is not available, an input not restored) is refused: when in doubt, refuse. @@ -121,14 +123,19 @@ def require_positively_commutative( symmetry = operator.argument_symmetry(input_streams) except Exception as exc: raise refusal from exc + inputs = Counter(id(stream) for stream in input_streams) if isinstance(symmetry, SymmetricGroup): - members = symmetry.members + # A SymmetricGroup counts every occurrence (ITL-1590): the same inputs with + # another multiplicity are not these inputs. + if Counter(id(member) for member in symmetry.members) != inputs: + raise refusal elif isinstance(symmetry, frozenset): + # A set collapses repeats: it can only name which inputs commute. members = cast("frozenset[Any]", symmetry) + if {id(member) for member in members} != set(inputs): + raise refusal else: raise refusal - if {id(member) for member in members} != {id(stream) for stream in input_streams}: - raise refusal def require_current_format(version: str, current: str) -> None: diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index 9b5a09367..3d6c1337f 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -18,7 +18,7 @@ import sys from collections.abc import Callable, Collection from pathlib import Path -from typing import Any +from typing import Any, ClassVar import pytest @@ -28,6 +28,7 @@ from orcapod.databases import DeltaTableDatabase from orcapod.pipeline.serialization import OPERATOR_INPUTS_KEY, register_operator from orcapod.types import CacheMode +from orcapod.types.argument_groups import SymmetricGroup ORDERED = {"MergeJoin", "SemiJoin"} COMMUTATIVE = {"Join", "Rejoin"} @@ -297,7 +298,36 @@ def identity_structure(self) -> Any: return self.__class__.__name__ +class OccurrenceJoin(Join): + """A commutative custom operator that accepts a repeated input: it keeps the input + that comes first in pipeline-hash order, so its rows do not depend on the order or + the repeats of its inputs. It declares a ``SymmetricGroup`` of every occurrence; + with ``miscount`` set it declares one occurrence too many of its last input (for + ``op(a, c)``: ``{a, c, c}``), the same inputs with the wrong multiplicity.""" + + miscount: ClassVar[bool] = False + + def argument_symmetry(self, streams: Collection[Any]) -> Any: + members = tuple(streams) + if self.miscount: + members += members[-1:] + return SymmetricGroup(members) + + def validate_inputs(self, *streams: Any) -> None: + pass + + def output_schema( + self, *streams: Any, columns: Any = None, all_info: bool = False + ) -> Any: + first = self.order_input_streams(*streams)[0] + return super().output_schema(first, columns=columns, all_info=all_info) + + def static_process(self, *streams: Any) -> Any: + return super().static_process(self.order_input_streams(*streams)[0]) + + register_operator("SchemaAwareJoin", SchemaAwareJoin) +register_operator("OccurrenceJoin", OccurrenceJoin) register_operator("CommutativeBinaryJoin", CommutativeBinaryJoin) register_operator("SchemaAwareSemiJoin", SchemaAwareSemiJoin) register_operator("NestedMergeJoin", NestedMergeJoin) @@ -370,6 +400,53 @@ def make(s: dict[str, Any]) -> Any: assert _rows(loaded.step.as_table()) == _rows(job.step.as_table()) +def _occurrence_join(reverse: bool) -> Callable[[dict[str, Any]], Any]: + """``OccurrenceJoin`` over a repeated input, ``(a, a, c)`` or ``(c, a, a)``.""" + + def make(s: dict[str, Any]) -> Any: + a = s["a"].select_data_columns(["y"]) + inputs = (s["c"], a, a) if reverse else (a, a, s["c"]) + return OccurrenceJoin()(*inputs, label="step") + + return make + + +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_a_c", "c_a_a"]) +def test_a_legacy_custom_symmetric_group_with_a_repeated_input_loads( + reverse: bool, blueprint: bool, tmp_path: Path +) -> None: + """A ``SymmetricGroup`` that counts every occurrence of the rebuilt inputs is + positively commutative: the legacy file loads in either argument order and gives + the live rows (ITL-1854, CodeRabbit on PR 694).""" + path, db_path, job = _legacy_custom(tmp_path, _occurrence_join(reverse), blueprint) + if blueprint: + assert "step" in Pipeline.load(path).nodes + else: + loaded = PipelineJob.load(path, database=DeltaTableDatabase(db_path)) + loaded.run(load_only=True) + assert _rows(loaded.step.as_table()) == _rows(job.step.as_table()) + + +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_a_c", "c_a_a"]) +def test_a_legacy_custom_symmetric_group_with_the_wrong_multiplicity_is_refused( + reverse: bool, blueprint: bool, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A ``SymmetricGroup`` naming the same inputs with the wrong number of occurrences + does not establish that the operator is commutative over exactly its inputs: the + legacy check compares occurrence counts, not the set of inputs (ITL-1590, + ITL-1854, CodeRabbit on PR 694). The file is saved with a correct declaration; + the miscount applies at load.""" + path, db_path, _ = _legacy_custom(tmp_path, _occurrence_join(reverse), blueprint) + monkeypatch.setattr(OccurrenceJoin, "miscount", True) + with pytest.raises(ValueError, match=LEGACY_REFUSAL): + if blueprint: + Pipeline.load(path) + else: + PipelineJob.load(path, database=DeltaTableDatabase(db_path)) + + @pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) @pytest.mark.parametrize( "make",