Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions changelog.d/ITL-1854.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -712,7 +712,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) |
Expand Down
7 changes: 1 addition & 6 deletions src/orcapod/core/operators/join.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
12 changes: 8 additions & 4 deletions src/orcapod/core/operators/static_output_pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""
...

Expand Down
23 changes: 17 additions & 6 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,14 @@
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
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,
Expand Down Expand Up @@ -78,8 +80,9 @@ 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``
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.
Expand Down Expand Up @@ -120,10 +123,18 @@ def require_positively_commutative(
symmetry = operator.argument_symmetry(input_streams)
except Exception as exc:
raise refusal from exc
if not isinstance(symmetry, frozenset):
raise refusal
members = cast("frozenset[Any]", symmetry)
if {id(member) for member in members} != {id(stream) for stream in input_streams}:
inputs = Counter(id(stream) for stream in input_streams)
if isinstance(symmetry, SymmetricGroup):
# 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


Expand Down
27 changes: 16 additions & 11 deletions src/orcapod/protocols/core_protocols/pod.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
"""
...

Expand Down
193 changes: 193 additions & 0 deletions tests/test_core/operators/test_join_argument_symmetry.py
Original file line number Diff line number Diff line change
@@ -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"]
)
2 changes: 1 addition & 1 deletion tests/test_core/operators/test_join_tag_order.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down
11 changes: 7 additions & 4 deletions tests/test_core/operators/test_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading