From 24cc45461b8827999b3f977383a2b2e965d37b72 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 02:39:03 -0800 Subject: [PATCH 01/11] fix(pipeline): graph edges carry their input position, so MergeJoin(a, a) and SemiJoin(a, a) run in a job (ITL-1419) A pipeline's graph edges are (upstream, node, position): the argument index for an ordered pod, None for a commutative one, from one rule (pipeline/edges.py, input_positions). Both orchestrators give a node one input per edge through one function (node_inputs); the async orchestrator wires one reader per edge. Saved files are unchanged: each (upstream, node) pair is written once and positions are rebuilt from an operator's saved inputs list. No hash or stored path moves. Stage 1 of ITL-1472. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1419.md | 18 + docs/dev/plans/itl-1419-edge-positions.md | 87 ++++ scripts/hash_audit_example.py | 4 +- src/orcapod/pipeline/async_orchestrator.py | 63 ++- src/orcapod/pipeline/base.py | 46 +- src/orcapod/pipeline/edges.py | 134 ++++++ src/orcapod/pipeline/graph.py | 38 +- src/orcapod/pipeline/job.py | 22 +- src/orcapod/pipeline/sync_orchestrator.py | 39 +- ...est_postgresql_table_source_integration.py | 2 +- .../sources/test_sqlite_table_source.py | 2 +- tests/test_core/test_tracker.py | 2 +- tests/test_pipeline/test_edge_positions.py | 403 ++++++++++++++++++ .../test_loaded_argument_order.py | 16 +- tests/test_pipeline/test_orchestrator.py | 2 +- 15 files changed, 782 insertions(+), 96 deletions(-) create mode 100644 changelog.d/ITL-1419.md create mode 100644 docs/dev/plans/itl-1419-edge-positions.md create mode 100644 src/orcapod/pipeline/edges.py create mode 100644 tests/test_pipeline/test_edge_positions.py diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md new file mode 100644 index 000000000..9bd5efd78 --- /dev/null +++ b/changelog.d/ITL-1419.md @@ -0,0 +1,18 @@ +### Fixed + +- A job runs an ordered operator given one stream for both inputs, `MergeJoin()(a, a)` + and `SemiJoin()(a, a)` (ITL-1419, stage 1 of ITL-1472). A pipeline's graph edges now + carry their input position, `(upstream, node, position)`: the argument index for an + ordered pod, none for a commutative one. Both orchestrators give a node one input per + edge, so the operator gets its two inputs, sync and async, in a job made from a + `Pipeline` or a `PipelineJob`, after `PipelineJob.load` and through `node.run()`; before, + the run raised "BinaryOperator requires exactly two input streams". No hash, stored path, + stored column or saved file changes: a saved file still lists each `(upstream, node)` + pair once, and the positions are rebuilt from an operator's saved `inputs` list. + `Join`, `Rejoin` and a function pod given one stream twice are still refused (overlapping + data columns). + +### Known limitations + +- `diagram()` draws one line for the two inputs of `MergeJoin()(a, a)`: drawing one line + per positioned edge is left to stage 2 of ITL-1472. diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md new file mode 100644 index 000000000..264af765c --- /dev/null +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -0,0 +1,87 @@ +# ITL-1419: graph edges carry their input position (stage 1 of ITL-1472) + +The design is `docs/dev/specs/itl-1472-edge-registration.md` (draft PR 580) and its plan, +`docs/dev/plans/itl-1472-plan.md`, "Stage 1". This is that stage only. + +Developer decision (2026-11-26): `MergeJoin(A, A)` is well defined, because its two input +positions are two edges, and it must run in a job. Refusing it (ITL-1419's other option) is +not taken. + +## The bug on `main` + +A pipeline's graph is a set of `(upstream key, node key)` pairs (`_hash_graph`, `_graph_edges`, +and the `OrcaDAG` of node objects the orchestrators walk). One upstream given to two inputs of +an operator is one pair, so `MergeJoin()(a, a)` and `SemiJoin()(a, a)` reach the orchestrator +with one predecessor: the sync orchestrator hands the operator one stream ("BinaryOperator +requires exactly two input streams"), the async one one reader. Pinned by +`tests/test_pipeline/test_loaded_argument_order.py::test_one_stream_given_twice_fails_to_run_in_a_job`. + +## What one stream given twice does elsewhere (unchanged by this stage) + +- `Join()(a, a)` and `Rejoin()(a, a)`: refused by the operator itself (overlapping data + columns, `InputValidationError`), standalone and when recorded into a pipeline. Kept. +- A function pod given one stream for two parameters, `pod(a, a)`: the pod joins its inputs + first, so it is refused as `Join(a, a)` is, standalone and when recorded. Kept. + +## Change + +1. **One rule for positions** (new `src/orcapod/pipeline/edges.py`): `input_positions(pod, + inputs)` gives each input its position, the argument index when the pod's + `argument_symmetry` is a tuple (function and side-effect pods: 0; `MergeJoin`, `SemiJoin`: + 0 and 1) and `None` when it is a `frozenset` (`Join`, `Rejoin`). Used by + `_record_invocation`, `compile`, the `PipelineJob` rebuild of a blueprint and the loader. +2. **Hash-level edges are triples.** `_graph_edges` becomes a sorted list of + `(upstream key, node key, position)`. `_hash_graph` (networkx, used for topological order and + ancestors) stays a graph of keys. Every consumer of `_graph_edges` in `job.py` and `graph.py` + reads the triple. +3. **No saved-format change.** `save()` writes the distinct `(upstream, node)` pairs, sorted, as + today (byte-equal files). The loader builds the triples from each operator's saved `inputs` + list (ITL-1417: argument order), position 0 for a function or side-effect node; a legacy + file without `inputs` keeps today's refusal/commutative rule. +4. **One function gives a node its inputs** (`node_input_edges(node, graph)` in `edges.py`): + the node's input edges in position order, one per position, each naming the upstream node + of the graph. It reads the node's own `upstreams` (built from the invocation's inputs in + argument order, the same order as the triples) and checks each is a predecessor in the + graph, by identity. It replaces `_single_input` / `_ordered_inputs` (sync) and the + predecessor sorting (async). +5. **Async: one reader per edge.** Channels are wired per positioned edge, so an upstream feeding + two positions of one node gets two readers of its broadcast channel. A held node drains + every one of its edge readers. A source node still executes once per run; its observer + events are unchanged. +6. **Held rows** (`node.run()`, the state rule) feed every position alike: the sync orchestrator + reads `outputs[upstream]` per edge, the async one sends the held rows to every edge reader. +7. **Diagram: left to stage 2.** The diagram keys its edges by node pair and role + (`(start, end, constrains)`) and routes them in the layout code, so two lines for + `MergeJoin(A, A)` need parallel-edge routing there, not a change in the edge listing + (coordinator, 2026-11-26: leave it to stage 2 if it reaches layout code). + `SemiJoin(A, A)` already draws two lines (plain and constraining, ITL-1455). + +Not in this stage: any public name (`job.edges`), any restriction, any change to a refusal, and +nothing in the id code of `core/nodes/function_node.py` / `operator_node.py` (ITL-1466). + +## Hashes + +No content hash, pipeline hash, stored path, stored column or golden value moves: node keys +are unchanged (invocation content hashes), and positions enter no hash. +`generate_golden_hashes.py --check` must report no drift. + +## Tests (first, shown failing on `main`) + +New file `tests/test_pipeline/test_edge_positions.py`, inputs with two tag and two data columns +(`id`, `key`; `x`, `y`), in two layouts (tag order and column order swapped): + +- `MergeJoin(A, A)` and `SemiJoin(A, A)` run, sync and async, in a `Pipeline` bound to a job and + in a `PipelineJob`; after `save` and `PipelineJob.load` (`load_only`); and through + `node.run()` (with a held upstream). Rows equal the standalone operator's. +- `MergeJoin(A, B)` and `MergeJoin(B, A)`, and a chain where one upstream is at position 0 and + another at 1 and the reverse, give the standalone rows. +- A source node's observer events are the same for `MergeJoin(A, A)` as for `MergeJoin(A, B)` + per source (one start and end per run). +- `Join(A, A)`, `Rejoin(A, A)` and a function pod given `(A, A)` stay refused. +- The saved file of a job with `MergeJoin(A, A)` has one edge pair and `inputs` `[A, A]`; + saving a loaded job writes the same bytes. +- `test_one_stream_given_twice_fails_to_run_in_a_job` becomes the test that it runs. + +Also run: the golden suite, `test_order_invariance.py`, `test_graph_walk_cost.py`, the +sync/async equivalence tests, `test_sync_orchestrator.py`, `test_rows_on_read.py`, +`tests/test_pipeline/`. diff --git a/scripts/hash_audit_example.py b/scripts/hash_audit_example.py index 358120920..62652baa3 100644 --- a/scripts/hash_audit_example.py +++ b/scripts/hash_audit_example.py @@ -253,9 +253,9 @@ def grade_simple(math: int) -> float: sub("Site 13 — snapshot_hash (deterministic from leaf content hashes)") # Reproduce PipelineJob.run() algorithm from the compiled node map. - # Edge (u_hash, v_hash): u is upstream → v is downstream. + # Edge (u_hash, v_hash, position): u is upstream → v is downstream. # Leaf = node whose hash does NOT appear as the upstream (u) in any edge. - upstream_set = {u_hash for u_hash, _ in job._graph_edges} + upstream_set = {u_hash for u_hash, _, _ in job._graph_edges} # Each leaf hash enters with its label, as PipelineJob.run() feeds it (ITL-1154). leaf_hashes = sorted( n.content_hash().to_string() diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 9edd1614e..9f06b13c3 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -212,6 +212,7 @@ async def _run_async( from orcapod.core.operators.static_output_pod import ( rows_on_read, ) + from orcapod.pipeline.edges import node_inputs from orcapod.pipeline.observer import NoOpObserver run_id = run_id or str(uuid.uuid4()) @@ -226,27 +227,34 @@ async def _run_async( topo_order = list(graph.topological_sort()) buf = self._buffer_size - # Build edge maps - out_edges: dict[Any, list[Any]] = defaultdict(list) - in_edges: dict[Any, list[Any]] = defaultdict(list) - for upstream_node, downstream_node in graph.edges(): - out_edges[upstream_node].append(downstream_node) - in_edges[downstream_node].append(upstream_node) + # One edge per input of a node, in position order: an upstream given to + # two inputs (``MergeJoin()(a, a)``) is two edges, each with its own + # reader (ITL-1419). An edge is (upstream, node, index of the input). + in_edges: dict[Any, list[tuple[Any, Any, int]]] = {} + out_edges: dict[Any, list[tuple[Any, Any, int]]] = defaultdict(list) + for node in topo_order: + # A node with no predecessor in the graph (a source, or a node the + # run holds without its inputs) reads no edge. + upstreams = node_inputs(node, graph) if graph.predecessors(node) else [] + edges = [(upstream, node, i) for i, upstream in enumerate(upstreams)] + in_edges[node] = edges + for edge in edges: + out_edges[edge[0]].append(edge) # Create channels for each edge node_output_channels: dict[Any, Channel | BroadcastChannel] = {} - edge_readers: dict[tuple[Any, Any], Any] = {} + edge_readers: dict[tuple[Any, Any, int], Any] = {} - for node, downstreams in out_edges.items(): - if len(downstreams) == 1: + for node, edges in out_edges.items(): + if len(edges) == 1: ch = Channel(buffer_size=buf) node_output_channels[node] = ch - edge_readers[(node, downstreams[0])] = ch.reader + edge_readers[edges[0]] = ch.reader else: bch = BroadcastChannel(buffer_size=buf) node_output_channels[node] = bch - for ds in downstreams: - edge_readers[(node, ds)] = bch.add_reader() + for edge in edges: + edge_readers[edge] = bch.add_reader() # Terminal nodes need sink channels terminal_channels: list[Channel] = [] @@ -275,8 +283,8 @@ async def _run_async( # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. - for upstream in in_edges.get(node, []): - tg.create_task(_drain(edge_readers[(upstream, node)])) + for edge in in_edges[node]: + tg.create_task(_drain(edge_readers[edge])) _start_node( tg, failed_nodes, @@ -292,12 +300,7 @@ async def _run_async( node.async_execute(writer, observer=effective_observer), ) elif is_function_node(node) or is_side_effect_function_node(node): - predecessors = in_edges.get(node, []) - if len(predecessors) != 1: - raise ValueError( - f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" - ) - input_reader = edge_readers[(predecessors[0], node)] + (input_reader,) = [edge_readers[e] for e in in_edges[node]] _start_node( tg, failed_nodes, @@ -312,18 +315,7 @@ async def _run_async( ), ) elif is_operator_node(node): - predecessors = in_edges.get(node, []) - # Sort by node.upstreams order for non-commutative operators - upstream_order = { - id(s): i for i, s in enumerate(node.upstreams) - } - sorted_preds = sorted( - predecessors, - key=lambda p: upstream_order.get(id(p), 0), - ) - input_readers = [ - edge_readers[(upstream, node)] for upstream in sorted_preds - ] + input_readers = [edge_readers[e] for e in in_edges[node]] _start_node( tg, failed_nodes, @@ -336,12 +328,7 @@ async def _run_async( ), ) elif is_side_effect_node(node): - predecessors = in_edges.get(node, []) - if not predecessors: - raise ValueError( - "SideEffectNode expects exactly 1 upstream, got 0" - ) - input_reader = edge_readers[(predecessors[0], node)] + (input_reader,) = [edge_readers[e] for e in in_edges[node]] # In a load-only run the node passes its rows on and delivers # nothing. _start_node( diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 966809d94..d125572d1 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -11,6 +11,13 @@ from orcapod.core.nodes.function_node import FunctionNodeBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.edges import ( + Position, + distinct_pairs, + edge_sort_key, + input_positions, + positioned_edges, +) from orcapod.pipeline.pod_invocation import ( FunctionInvocation, OperatorInvocation, @@ -141,7 +148,8 @@ def __init__( # Populated from _persistent_node_map / _hash_graph at end of compile(). self._node_lut: dict[str, Any] = {} # hash → non-source compiled node self._upstreams: dict[str, Any] = {} # hash → source compiled node - self._graph_edges: list[tuple[str, str]] = [] # edge list from _hash_graph + # (upstream key, node key, position), sorted: one edge per input (ITL-1419). + self._graph_edges: list[tuple[str, str, Position]] = [] # ------------------------------------------------------------------ # Properties @@ -352,8 +360,10 @@ def _record_invocation(self, invocation: PodInvocation) -> None: require_one_restriction([*self._held_streams(), *inputs]) self._remember_invocation(key, invocation) self._hash_graph.add_node(key) + self._hash_graph.add_edges_from( + distinct_pairs(_invocation_edges(key, invocation)) + ) for upstream, upstream_hash in upstreams: - self._hash_graph.add_edge(upstream_hash, key) if upstream_hash not in self._source_streams: self._source_streams[upstream_hash] = upstream @@ -625,11 +635,21 @@ def compile(self) -> None: self._nodes.update((node.label, node) for node in node_map.values()) # 5. Build node_graph (OrcaDAG with node objects as vertices). - graph_edges = sorted(self._hash_graph.edges()) + # One edge per input, positioned (ITL-1419); the node graph holds each + # (upstream, node) pair once. + graph_edges = sorted( + ( + edge + for key, inv in self._invocation_lut.items() + if key in self._hash_graph + for edge in _invocation_edges(key, inv) + ), + key=edge_sort_key, + ) node_dag: OrcaDAG[NodeT] = OrcaDAG() for node in node_map.values(): node_dag.add_node(node) - for up_hash, down_hash in graph_edges: + for up_hash, down_hash in distinct_pairs(graph_edges): up_node = node_map.get(up_hash) down_node = node_map.get(down_hash) if up_node is not None and down_node is not None: @@ -805,11 +825,25 @@ def from_invocations( key = inv.content_hash().to_string() instance._remember_invocation(key, inv) instance._hash_graph.add_node(key) - for upstream in inv.input_streams: - instance._hash_graph.add_edge(upstream.content_hash().to_string(), key) + instance._hash_graph.add_edges_from( + distinct_pairs(_invocation_edges(key, inv)) + ) # Also add source hashes as isolated nodes (no incoming edges) for h in graph.source_streams: if h not in instance._hash_graph: instance._hash_graph.add_node(h) instance.compile() return instance + + +def _invocation_edges( + key: str, invocation: PodInvocation +) -> list[tuple[str, str, Position]]: + """The positioned edges ``(upstream key, key, position)`` into an invocation's node, + one per input, in argument order (ITL-1419).""" + inputs = tuple(invocation.input_streams) + return positioned_edges( + key, + [upstream.content_hash().to_string() for upstream in inputs], + input_positions(invocation.pod, inputs), + ) diff --git a/src/orcapod/pipeline/edges.py b/src/orcapod/pipeline/edges.py new file mode 100644 index 000000000..c423185aa --- /dev/null +++ b/src/orcapod/pipeline/edges.py @@ -0,0 +1,134 @@ +"""The edges of a pipeline's graph carry their input position (ITL-1419; stage 1 of ITL-1472). + +An edge is ``(upstream, node, position)``. One upstream given to two inputs of an ordered +operator (``MergeJoin()(a, a)``) is two edges, at positions 0 and 1; it was one +``(upstream, node)`` pair, so the operator was handed one input when the job ran. + +Two rules live here and nowhere else: + +- ``input_positions``: the position of each input of a pod, from its + ``argument_symmetry``. The compile, the recording of an invocation, the rebuild of a + job's blueprint and the loader take positions from it. +- ``node_inputs``: the upstream of each input of a compiled node, in position order, as + the orchestrators give it its inputs. + +Positions enter no hash, no stored path and no saved file: a saved file lists each +distinct ``(upstream, node)`` pair once, as before, and an operator's ``inputs`` list +(ITL-1417) gives the argument order its positions are rebuilt from. +""" + +from __future__ import annotations + +from collections.abc import Collection, Iterable, Sequence +from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast + +if TYPE_CHECKING: + from orcapod.pipeline.dag import GraphProtocol + from orcapod.protocols.core_protocols import StreamProtocol + +KeyT = TypeVar("KeyT") + +Position = int | None +"""An input's position: its argument index for an ordered pod, ``None`` for a +commutative one, whose inputs have no position.""" + + +class _SymmetryDeclaring(Protocol): + """A pod, as far as positions read it: its argument symmetry.""" + + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> object: ... + + +def input_positions( + pod: _SymmetryDeclaring | None, inputs: Sequence[object] +) -> tuple[Position, ...]: + """The position of each of ``inputs`` of ``pod``. + + A pod with one input gives it position 0. Otherwise the kind of + ``pod.argument_symmetry(inputs)`` decides: a ``tuple`` (ordered: ``MergeJoin``, + ``SemiJoin``) gives each input its argument index, a ``frozenset`` (commutative: + ``Join``, ``Rejoin``) gives every input ``None``. Only the kind of the returned + group is read, so ``inputs`` may hold one stream twice. A pod that is not known + (``None``: a node a loaded file keeps read-only, or of a kind this version does not + restore) has its inputs in the argument order the file gives, so each its index. + + Args: + pod: The pod the inputs are given to, or ``None`` when it is not known. + inputs: The input streams, in argument order: the pod's ``argument_symmetry`` + may read them, so never their keys (keys only when ``pod`` is ``None``). + + Returns: + One position per input, in argument order. + """ + if len(inputs) <= 1 or pod is None: + return tuple(range(len(inputs))) + streams = cast("Sequence[StreamProtocol]", inputs) + if isinstance(pod.argument_symmetry(streams), frozenset): + return (None,) * len(inputs) + return tuple(range(len(inputs))) + + +def positioned_edges( + node: KeyT, upstreams: Sequence[KeyT], positions: Sequence[Position] +) -> list[tuple[KeyT, KeyT, Position]]: + """The edges ``(upstream, node, position)`` into ``node``, in argument order. + + Args: + node: The node's key. + upstreams: Its inputs' keys, in argument order. + positions: Their positions, from ``input_positions``. + + Returns: + One edge per input. + """ + return [ + (upstream, node, position) + for upstream, position in zip(upstreams, positions, strict=True) + ] + + +def edge_sort_key(edge: tuple[str, str, Position]) -> tuple[str, str, int]: + """The order of a list of edges: by upstream, then node, then position (``None`` + first).""" + upstream, node, position = edge + return (upstream, node, -1 if position is None else position) + + +def distinct_pairs( + edges: Iterable[tuple[KeyT, KeyT, Position]], +) -> list[tuple[KeyT, KeyT]]: + """The distinct ``(upstream, node)`` pairs of ``edges``, in first-seen order: what a + graph of nodes (and a saved file) holds.""" + return list(dict.fromkeys((upstream, node) for upstream, node, _ in edges)) + + +def node_inputs(node: Any, graph: GraphProtocol[Any]) -> list[Any]: + """The upstream node of each input of ``node``, in position order. + + One entry per input: an upstream given to two inputs is listed twice. The positions + are the node's own ``upstreams`` (built from its pod's inputs in argument order); each + must be a predecessor of ``node`` in ``graph``, by identity. + + Args: + node: A compiled node that is not a source. + graph: The graph being run. + + Returns: + The node's inputs, as nodes of ``graph``. + + Raises: + ValueError: If an input of the node is not a predecessor of it in ``graph``. + """ + predecessors = list(graph.predecessors(node)) + inputs: list[Any] = [] + for upstream in node.upstreams: + found = next((p for p in predecessors if p is upstream), None) + if found is None: + raise ValueError( + f"Node {node.label!r}: its input {getattr(upstream, 'label', upstream)!r} " + "is not a node of the graph being run." + ) + inputs.append(found) + if not inputs: + raise ValueError(f"Node {node.label!r} has no input in the graph being run.") + return inputs diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index baec82ecf..151858979 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -17,6 +17,13 @@ from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.edges import ( + Position, + distinct_pairs, + edge_sort_key, + input_positions, + positioned_edges, +) from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule @@ -297,7 +304,9 @@ def save(self, path: str | Path) -> None: "orcapod_version": orcapod.__version__, "pipeline": {"name": list(self._name)}, "nodes": nodes, - "edges": [list(edge) for edge in self._graph_edges], + # Each (upstream, node) pair once, as before ITL-1419: an operator's + # ``inputs`` list gives the argument order positions are rebuilt from. + "edges": [list(pair) for pair in distinct_pairs(self._graph_edges)], } path = Path(path) @@ -372,6 +381,8 @@ def load(cls, path: str | Path) -> "Pipeline": reconstructed: dict[str, GraphNode] = {} # Each operator's input keys in argument order, for the job loader (ITL-1417). loaded_input_keys: dict[str, list[str]] = {} + # Each node's positioned edges (ITL-1419), from its inputs in argument order. + positioned: dict[str, list[tuple[str, str, Position]]] = {} for node_hash in topo_order: descriptor = nodes_data.get(node_hash) @@ -576,6 +587,18 @@ def load(cls, path: str | Path) -> "Pipeline": operator, upstream_nodes, up_hashes, descriptor.get("label") ) loaded_input_keys[node_hash] = list(up_hashes) + # Asked of the rebuilt input streams, never of their keys; with an + # input not restored, the inputs are in the file's argument order. + positioned[node_hash] = positioned_edges( + node_hash, + list(up_hashes), + input_positions( + operator if len(upstream_nodes) == len(up_hashes) else None, + upstream_nodes + if len(upstream_nodes) == len(up_hashes) + else up_hashes, + ), + ) node = OperatorNode.from_descriptor( descriptor, operator=operator, @@ -607,6 +630,17 @@ def load(cls, path: str | Path) -> "Pipeline": # Keep old files' edge order only for the legacy input-order fallback above. edges = sorted((up, down) for up, down in edges) + # A node with one input (a function or side-effect node), and one this version + # does not restore, has its inputs in the order the file gives. + for node_hash, up_hashes in upstream_map.items(): + if node_hash not in positioned: + positioned[node_hash] = positioned_edges( + node_hash, up_hashes, input_positions(None, up_hashes) + ) + graph_edges = sorted( + (edge for node_edges in positioned.values() for edge in node_edges), + key=edge_sort_key, + ) reconstructed = cls._ordered_node_map(reconstructed, edge_graph) # Build Pipeline instance @@ -642,7 +676,7 @@ def load(cls, path: str | Path) -> "Pipeline": node_dag.add_edge(up_node, down_node) pipeline._node_graph = node_dag - pipeline._graph_edges = edges + pipeline._graph_edges = graph_edges pipeline._hash_graph = nx.DiGraph() for up_hash, down_hash in edges: pipeline._hash_graph.add_edge(up_hash, down_hash) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 2f80d1fa0..8c1c2cf7f 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -26,6 +26,7 @@ ) from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.edges import distinct_pairs, edge_sort_key from orcapod.pipeline.node_run import ( RunPlan, check_sources, @@ -828,12 +829,17 @@ def as_pipeline(self) -> "Pipeline": dict(self._hash_graph.nodes[old_h]) if old_h in self._hash_graph else {} ) bp_hash_graph.add_node(new_h, **old_attrs) + # Each edge keeps its position (ITL-1419): the blueprint node has the job + # node's pod and its inputs in the same argument order. new_graph_edges = sorted( - (old_to_new[u], old_to_new[v]) - for u, v in self._graph_edges - if u in old_to_new and v in old_to_new + ( + (old_to_new[u], old_to_new[v], position) + for u, v, position in self._graph_edges + if u in old_to_new and v in old_to_new + ), + key=edge_sort_key, ) - bp_hash_graph.add_edges_from(new_graph_edges) + bp_hash_graph.add_edges_from(distinct_pairs(new_graph_edges)) pipeline = Pipeline(name=self._name, auto_compile=False) pipeline._hash_graph = bp_hash_graph @@ -857,7 +863,7 @@ def as_pipeline(self) -> "Pipeline": bp_dag: OrcaDAG = OrcaDAG() for node in pipeline._persistent_node_map.values(): bp_dag.add_node(node) - for up_h, down_h in new_graph_edges: + for up_h, down_h in distinct_pairs(new_graph_edges): bp_dag.add_edge(new_node_map[up_h], new_node_map[down_h]) pipeline._node_graph = bp_dag @@ -1298,7 +1304,7 @@ def _prepare_run( # --- Build hash-keyed OrcaDAG for topological ordering + exclusion --- hash_dag: OrcaDAG[str] = OrcaDAG() - for u, v in self._graph_edges: + for u, v, _ in self._graph_edges: hash_dag.add_edge(u, v) for node_hash in self._persistent_node_map: if node_hash not in hash_dag: @@ -1350,7 +1356,7 @@ def _prepare_run( for node_hash, node in self._persistent_node_map.items(): if node_hash not in excluded_hashes: exec_dag.add_node(node) - for u_hash, v_hash in self._graph_edges: + for u_hash, v_hash in distinct_pairs(self._graph_edges): if ( u_hash not in excluded_hashes and v_hash not in excluded_hashes @@ -2100,7 +2106,7 @@ def load( job_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): job_dag.add_node(node) - for u_hash, v_hash in job._graph_edges: + for u_hash, v_hash in distinct_pairs(job._graph_edges): u_node = job._persistent_node_map.get(u_hash) v_node = job._persistent_node_map.get(v_hash) if u_node is not None and v_node is not None: diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 3286caab7..9b521afd5 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -116,7 +116,7 @@ def run( elif is_source_node(node): outputs[node] = node.execute(observer=effective_observer) elif is_function_node(node) or is_side_effect_function_node(node): - input_stream = self._single_input(node, graph, outputs) + (input_stream,) = self._inputs(node, graph, outputs) outputs[node] = node.execute( input_stream, observer=effective_observer, @@ -125,12 +125,12 @@ def run( load_only=load_only, ) elif is_operator_node(node): - input_streams = self._ordered_inputs(node, graph, outputs) + input_streams = self._inputs(node, graph, outputs) outputs[node] = node.execute( *input_streams, observer=effective_observer, load_only=load_only ) elif is_side_effect_node(node): - input_stream = self._single_input(node, graph, outputs) + (input_stream,) = self._inputs(node, graph, outputs) # In a load-only run the node passes its rows on and delivers nothing. outputs[node] = node.execute( input_stream, @@ -171,37 +171,20 @@ def run( effective_observer.on_run_end(run_id) @staticmethod - def _single_input( - node: Any, - graph: "GraphProtocol[Any]", - outputs: dict[Any, StreamProtocol], - ) -> StreamProtocol: - """The output stream of a node's one predecessor (function and side-effect nodes).""" - predecessors = list(graph.predecessors(node)) - if len(predecessors) != 1: - raise ValueError( - f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" - ) - from orcapod.core.operators.static_output_pod import at_edge - - return at_edge(outputs[predecessors[0]]) - - @staticmethod - def _ordered_inputs( + def _inputs( node: Any, graph: "GraphProtocol[Any]", outputs: dict[Any, StreamProtocol], ) -> list[StreamProtocol]: - """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" - predecessors = list(graph.predecessors(node)) - upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} - sorted_preds = sorted( - predecessors, - key=lambda p: upstream_order.get(id(p), 0), - ) + """The output stream of each of a node's input edges, in position order. + + One stream per edge: an upstream given to two inputs (``MergeJoin()(a, a)``) is + read at both (ITL-1419). A held upstream's stream feeds every position alike. + """ from orcapod.core.operators.static_output_pod import at_edge + from orcapod.pipeline.edges import node_inputs - return [at_edge(outputs[p]) for p in sorted_preds] + return [at_edge(outputs[upstream]) for upstream in node_inputs(node, graph)] @staticmethod def _release_built_inputs( diff --git a/tests/test_core/sources/test_postgresql_table_source_integration.py b/tests/test_core/sources/test_postgresql_table_source_integration.py index e2fc69b92..12ccc5b69 100644 --- a/tests/test_core/sources/test_postgresql_table_source_integration.py +++ b/tests/test_core/sources/test_postgresql_table_source_integration.py @@ -240,7 +240,7 @@ def double_response(trial: int, response: float) -> float: exec_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): exec_dag.add_node(node) - for u_hash, v_hash in job._graph_edges: + for u_hash, v_hash, _ in job._graph_edges: if ( u_hash in job._persistent_node_map and v_hash in job._persistent_node_map diff --git a/tests/test_core/sources/test_sqlite_table_source.py b/tests/test_core/sources/test_sqlite_table_source.py index d22ea391d..49fd254fd 100644 --- a/tests/test_core/sources/test_sqlite_table_source.py +++ b/tests/test_core/sources/test_sqlite_table_source.py @@ -598,7 +598,7 @@ def double_response(trial: int, response: float) -> float: exec_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): exec_dag.add_node(node) - for u_hash, v_hash in job._graph_edges: + for u_hash, v_hash, _ in job._graph_edges: if ( u_hash in job._persistent_node_map and v_hash in job._persistent_node_map diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 046239abb..896863a97 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -445,7 +445,7 @@ def test_record_function_pod_stores_edge(self): # _graph_edges is populated by compile() tracker.compile() assert len(tracker._graph_edges) == 1 - upstream_hash, node_hash = tracker._graph_edges[0] + upstream_hash, node_hash, _ = tracker._graph_edges[0] assert upstream_hash == stream.content_hash().to_string() assert node_hash in tracker._node_lut diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py new file mode 100644 index 000000000..4a1da2cac --- /dev/null +++ b/tests/test_pipeline/test_edge_positions.py @@ -0,0 +1,403 @@ +"""A job's graph edges carry their input position (ITL-1419, stage 1 of ITL-1472). + +An edge is ``(upstream, node, position)``: one upstream given to two inputs of an ordered +operator is two edges, so ``MergeJoin()(a, a)`` and ``SemiJoin()(a, a)`` run in a job as +they run standalone. ``Join``, ``Rejoin`` and a function pod given one stream twice are +refused by the operator (or the pod's join) itself, standalone and in a job. + +Inputs have two tag columns (``id``, ``key``) and two data columns (``x``, ``y``), in two +layouts (tag order and column order swapped). +""" + +from __future__ import annotations + +import asyncio +import json +from pathlib import Path +from typing import Any + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, function_pod, sources +from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.errors import InputValidationError +from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator + + +LAYOUTS = ["tags_id_key", "tags_key_id"] +MODES = ["sync", "async"] +OPERATORS = {"MergeJoin": MergeJoin, "SemiJoin": SemiJoin} + + +def _source(name: str, layout: str, rows: list[tuple[int, str, int, int]]) -> Any: + """A source over ``rows`` of ``(id, key, x, y)``, laid out by ``layout``.""" + columns = { + "id": pa.array([r[0] for r in rows], pa.int64()), + "key": pa.array([r[1] for r in rows], pa.large_string()), + "x": pa.array([r[2] for r in rows], pa.int64()), + "y": pa.array([r[3] for r in rows], pa.int64()), + } + if layout == "tags_id_key": + order, tags = ["id", "key", "x", "y"], ["id", "key"] + else: + order, tags = ["y", "key", "x", "id"], ["key", "id"] + table = pa.table({name: columns[name] for name in order}) + return sources.ArrowTableSource( + table, tag_columns=tags, tag_only_columns=True, source_id=name + ) + + +def _csv_a(tmp_path: Path, layout: str) -> Any: + """``_a`` as a CSV file, which a loaded job reads again from its saved config.""" + return _csv( + tmp_path, "a", layout, [(1, "p", 1, 10), (2, "q", 2, 20), (3, "r", 3, 30)] + ) + + +def _csv( + tmp_path: Path, name: str, layout: str, rows: list[tuple[int, str, int, int]] +) -> Any: + if layout == "tags_id_key": + header, tags = "id,key,x,y", ["id", "key"] + lines = [f"{i},{k},{x},{y}" for i, k, x, y in rows] + else: + header, tags = "y,key,x,id", ["key", "id"] + lines = [f"{y},{k},{x},{i}" for i, k, x, y in rows] + path = tmp_path / f"{name}.csv" + path.write_text("\n".join([header, *lines]) + "\n") + return sources.CSVSource( + str(path), tag_columns=tags, tag_only_columns=True, source_id=name + ) + + +def _a(layout: str) -> Any: + return _source("a", layout, [(1, "p", 1, 10), (2, "q", 2, 20), (3, "r", 3, 30)]) + + +def _b(layout: str) -> Any: + return _source("b", layout, [(1, "p", 100, 1000), (2, "q", 101, 1001)]) + + +def _rows(table: Any) -> list[str]: + return sorted(repr(sorted(row.items())) for row in table.to_pylist()) + + +def _run(job: Any, mode: str, **kwargs: Any) -> None: + if mode == "sync": + job.run(**kwargs) + else: + asyncio.run(job.run_async(**kwargs)) + + +def _standalone(operator: str, first: Any, second: Any) -> list[str]: + return _rows(OPERATORS[operator]()(first, second).as_table(all_info=True)) + + +# ── one stream given to both inputs ─────────────────────────────────────────── + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_stream_twice_runs_in_a_pipeline_job( + operator: str, layout: str, mode: str +) -> None: + a = _a(layout) + job = PipelineJob(name="twice", database=InMemoryArrowDatabase()) + with job: + OPERATORS[operator]()(a, a, label="step") + _run(job, mode) + assert _rows(job.step.as_table(all_info=True)) == _standalone(operator, a, a) + assert job.step.as_table().num_rows == 3 + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_stream_twice_runs_in_a_job_made_from_a_pipeline( + operator: str, layout: str, mode: str +) -> None: + a = _a(layout) + pipeline = Pipeline(name="twice") + with pipeline: + OPERATORS[operator]()(a, a, label="step") + job = PipelineJob.from_pipeline( + pipeline, sources={"a": a}, database=InMemoryArrowDatabase() + ) + _run(job, mode) + assert _rows(job.step.as_table(all_info=True)) == _standalone(operator, a, a) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_stream_twice_runs_after_save_and_load( + operator: str, layout: str, mode: str, tmp_path: Path +) -> None: + a = _csv_a(tmp_path, layout) + db_path = tmp_path / "db" + job = PipelineJob(name="twice", database=DeltaTableDatabase(db_path)) + with job: + OPERATORS[operator]()(a, a, label="step") + _run(job, mode) + live = _rows(job.step.as_table(all_info=True)) + job.save(tmp_path / "job.json") + saved = json.loads((tmp_path / "job.json").read_text())["pipeline"] + # No format change: the edge list holds the pair once; the operator's inputs + # list holds the stream twice, in argument order. + step_key = next(k for k, d in saved["nodes"].items() if d.get("label") == "step") + a_key = next(k for k, d in saved["nodes"].items() if d.get("label") == "a") + assert saved["edges"] == [[a_key, step_key]] + assert saved["nodes"][step_key]["inputs"] == [a_key, a_key] + + loaded = PipelineJob.load( + tmp_path / "job.json", database=DeltaTableDatabase(db_path) + ) + assert [up.label for up in loaded.step.upstreams] == ["a", "a"] + _run(loaded, mode, load_only=True) + assert _rows(loaded.step.as_table(all_info=True)) == live + # Saving the loaded job writes the same pipeline. + loaded.save(tmp_path / "again.json") + assert json.loads((tmp_path / "again.json").read_text())["pipeline"] == saved + + +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_stream_twice_runs_through_node_run(operator: str, layout: str) -> None: + """``node.run()`` with the upstream run first and held, and with nothing run.""" + a = _a(layout) + job = PipelineJob(name="twice", database=InMemoryArrowDatabase()) + with job: + selected = a.select_data_columns(["x", "y"], label="selected") + OPERATORS[operator]()(selected, selected, label="step") + expected = _standalone( + operator, a.select_data_columns(["x", "y"]), a.select_data_columns(["x", "y"]) + ) + job.step.run() + assert _rows(job.step.as_table(all_info=True)) == expected + job.step.clear_cache() + job.step.run() # ``selected`` holds a current run: its rows feed both positions + assert _rows(job.step.as_table(all_info=True)) == expected + + +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_stream_twice_holds_and_feeds_both_positions_async(operator: str) -> None: + """A held upstream feeds both positions on the async orchestrator.""" + a = _a("tags_id_key") + job = PipelineJob(name="twice", database=InMemoryArrowDatabase()) + with job: + selected = a.select_data_columns(["x", "y"], label="selected") + OPERATORS[operator]()(selected, selected, label="step") + expected = _standalone( + operator, a.select_data_columns(["x", "y"]), a.select_data_columns(["x", "y"]) + ) + job.selected.run() + job.run(orchestrator=AsyncPipelineOrchestrator()) + assert _rows(job.step.as_table(all_info=True)) == expected + + +# ── two streams, both orders ───────────────────────────────────────────────── + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_b", "b_a"]) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_two_streams_in_either_order_give_the_standalone_rows( + operator: str, reverse: bool, mode: str +) -> None: + a, b = _a("tags_id_key"), _b("tags_key_id") + first, second = (b, a) if reverse else (a, b) + job = PipelineJob(name="two", database=InMemoryArrowDatabase()) + with job: + OPERATORS[operator]()(first, second, label="step") + _run(job, mode) + assert _rows(job.step.as_table(all_info=True)) == _standalone( + operator, first, second + ) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_first", "b_first"]) +def test_one_upstream_at_both_positions_of_two_nodes(reverse: bool, mode: str) -> None: + """``a`` at position 0 of one node and 1 of another, ``b`` the reverse.""" + a, b = _a("tags_id_key"), _b("tags_id_key") + job = PipelineJob(name="cross", database=InMemoryArrowDatabase()) + with job: + if reverse: + MergeJoin()(b, a, label="ba") + MergeJoin()(a, b, label="ab") + else: + MergeJoin()(a, b, label="ab") + MergeJoin()(b, a, label="ba") + MergeJoin()(a, a, label="aa") + _run(job, mode) + assert _rows(job.ab.as_table(all_info=True)) == _standalone("MergeJoin", a, b) + assert _rows(job.ba.as_table(all_info=True)) == _standalone("MergeJoin", b, a) + assert _rows(job.aa.as_table(all_info=True)) == _standalone("MergeJoin", a, a) + + +# ── observer events of a source node ───────────────────────────────────────── + + +class _Events: + def __init__(self) -> None: + self.events: list[tuple[str, str]] = [] + + def contextualize(self, *identity_path: str) -> _Events: + return self + + def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None: + pass + + def on_run_end(self, run_id: str) -> None: + pass + + def on_node_start( + self, node_label: str, node_hash: str, tag_schema: Any = None + ) -> None: + self.events.append(("start", node_label)) + + def on_node_end(self, node_label: str, node_hash: str) -> None: + self.events.append(("end", node_label)) + + def on_data_start(self, node_label: str, tag: Any, data: Any) -> None: + pass + + def on_data_end(self, node_label: str, *args: Any, **kwargs: Any) -> None: + pass + + def on_data_crash(self, node_label: str, *args: Any, **kwargs: Any) -> None: + pass + + def create_data_logger(self, tag: Any, data: Any) -> Any: + from orcapod.pipeline.observer import NoOpObserver + + return NoOpObserver().create_data_logger(tag, data) + + +@pytest.mark.parametrize("mode", MODES) +def test_a_source_fed_twice_has_the_events_of_a_source_fed_once(mode: str) -> None: + def events_of(twice: bool) -> list[tuple[str, str]]: + a, b = _a("tags_id_key"), _b("tags_id_key") + job = PipelineJob(name="events", database=InMemoryArrowDatabase()) + with job: + MergeJoin()(a, a if twice else b, label="step") + observer = _Events() + _run(job, mode, observer=observer) + return [event for event in observer.events if event[1] == "a"] + + assert events_of(twice=True) == events_of(twice=False) + assert events_of(twice=True) == [("start", "a"), ("end", "a")] + + +# ── what stays refused ─────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("operator", [Join, Rejoin]) +def test_a_commutative_operator_given_one_stream_twice_is_refused( + operator: type, +) -> None: + """Unchanged: the operator refuses its overlapping data columns, standalone and + when recorded into a job.""" + a = _a("tags_id_key") + with pytest.raises(InputValidationError, match="overlapping"): + operator()(a, a) + job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) + with pytest.raises(InputValidationError, match="overlapping"): + with job: + operator()(a, a, label="step") + + +def test_a_function_pod_given_one_stream_twice_is_refused() -> None: + """Unchanged: a function pod joins its inputs first, so one stream given for two + parameters is refused as ``Join(a, a)`` is.""" + + @function_pod(output_keys="s") + def add(x: int, y: int) -> int: + return x + y + + a = _a("tags_id_key") + with pytest.raises(InputValidationError, match="overlapping"): + add.pod(a, a) + job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) + with pytest.raises(InputValidationError, match="overlapping"): + with job: + add.pod(a, a, label="step") + + +# ── the positioned edges ───────────────────────────────────────────────────── + + +def _edges_by_label(job: Any) -> list[tuple[str, str, int | None]]: + """The job's positioned edges, by node label (the graph is keyed by hashes).""" + label = { + key: node.label + for key, node in job._persistent_node_map.items() # pyright: ignore[reportPrivateUsage] + } + return sorted( + (label[up], label[down], position) + for up, down, position in job._graph_edges # pyright: ignore[reportPrivateUsage] + if down in label and label[down] in {"aa", "ab", "ba", "joined", "fn"} + ) + + +def test_each_input_is_one_edge_at_its_position(tmp_path: Path) -> None: + """An ordered operator's inputs are at their argument index, a commutative one's + have no position, a function pod's input is at 0; the same after save and load.""" + a = _csv_a(tmp_path, "tags_id_key") + b = _csv(tmp_path, "b", "tags_key_id", [(1, "p", 100, 1000), (2, "q", 101, 1001)]) + + @function_pod(output_keys="s") + def total(x: int, y: int) -> int: + return x + y + + db_path = tmp_path / "db" + job = PipelineJob(name="edges", database=DeltaTableDatabase(db_path)) + with job: + MergeJoin()(a, a, label="aa") + MergeJoin()(b, a, label="ba") + Join()( + a.select_data_columns(["x"], label="ax"), + b.select_data_columns(["y"], label="by"), + label="joined", + ) + total.pod(a, label="fn") + expected = [ + ("a", "aa", 0), + ("a", "aa", 1), + ("a", "ba", 1), + ("a", "fn", 0), + ("ax", "joined", None), + ("b", "ba", 0), + ("by", "joined", None), + ] + assert _edges_by_label(job) == expected + job.run() + job.save(tmp_path / "job.json") + loaded = PipelineJob.load( + tmp_path / "job.json", database=DeltaTableDatabase(db_path) + ) + assert _edges_by_label(loaded) == expected + + +@pytest.mark.parametrize("repeat", [False, True], ids=["a_b", "a_a"]) +def test_the_saved_edge_list_is_the_one_main_wrote( + repeat: bool, tmp_path: Path +) -> None: + """No format change: a saved file lists each ``(upstream, node)`` pair once, sorted, + exactly as ``main`` wrote it (``sorted(_hash_graph.edges())``); the positions are + rebuilt from the operators' ``inputs`` lists.""" + a = _csv_a(tmp_path, "tags_id_key") + b = _csv(tmp_path, "b", "tags_id_key", [(1, "p", 100, 1000)]) + job = PipelineJob(name="saved", database=InMemoryArrowDatabase()) + with job: + b.select_data_columns(["y"], label="other") + MergeJoin()(a, a if repeat else b, label="step") + SemiJoin()(b, a, label="semi") + pipeline = job.compiled_pipeline + pipeline.save(tmp_path / "pipeline.json") + saved = json.loads((tmp_path / "pipeline.json").read_text()) + main_edges = sorted(pipeline._hash_graph.edges()) # pyright: ignore[reportPrivateUsage] + assert saved["edges"] == [list(edge) for edge in main_edges] diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index af154b56c..8b8aedc01 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -434,20 +434,20 @@ def test_a_loaded_read_only_node_keeps_its_inputs( @pytest.mark.parametrize("mode", ["sync", "async"]) @pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) -def test_one_stream_given_twice_fails_to_run_in_a_job( +def test_one_stream_given_twice_runs_in_a_job( operator: type, mode: str, tmp_path: Path ) -> None: - """Finding 5 (pre-existing on main, pinned; ITL-1419): a job's - graph has one edge for two argument slots of one stream, so ``MergeJoin()(a, a)`` - and ``SemiJoin()(a, a)`` fail when the job runs, though they run as plain - streams. A fix makes this test fail; it is then changed to the fixed behaviour.""" + """Finding 5 (ITL-1419, fixed): a job's graph edges carry their input position, + so one stream given to both inputs of ``MergeJoin`` or ``SemiJoin`` is two edges + and the job runs it as the plain streams do.""" a = _inputs(tmp_path)["a"] - assert operator()(a, a).as_table().num_rows == 3 + expected = _rows(operator()(a, a).as_table(all_info=True)) + assert len(expected) == 3 job = PipelineJob(name="repeat", database=DeltaTableDatabase(tmp_path / "db")) with job: operator()(a, a, label="repeat") - with pytest.raises((ValueError, IndexError)): - _run(job, mode) + _run(job, mode) + assert _rows(job.repeat.as_table(all_info=True)) == expected @pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) diff --git a/tests/test_pipeline/test_orchestrator.py b/tests/test_pipeline/test_orchestrator.py index 1b0f16d12..dd27063fd 100644 --- a/tests/test_pipeline/test_orchestrator.py +++ b/tests/test_pipeline/test_orchestrator.py @@ -336,7 +336,7 @@ async def test_run_async_from_event_loop(self): exec_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): exec_dag.add_node(node) - for u_hash, v_hash in job._graph_edges: + for u_hash, v_hash, _ in job._graph_edges: if ( u_hash in job._persistent_node_map and v_hash in job._persistent_node_map From 9881264f99162188d3ef1fde52e515d3e34d2ce2 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 03:15:43 -0800 Subject: [PATCH 02/11] docs(hashing): list the positioned-edge helper in the hash site inventory (ITL-1419) _invocation_edges reads each input's content hash as the upstream key of its positioned edge, an in-memory graph key like _record_invocation's. Co-Authored-By: Claude Opus 5.5 --- docs/reference/hashing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 6130f2dd5..697ca0881 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -394,7 +394,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:_invocation_edges` (the upstream keys of positioned edges, ITL-1419), `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | From a09a869e3682a01e7352790b19a94235afe9d608 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 04:38:41 -0800 Subject: [PATCH 03/11] fix(operators): refuse a stream given twice to a commutative pod; a one-input Join has no position (ITL-1419) A commutative operator (Join, Rejoin) or a function pod hashes its inputs as a set, so Join()(d) and Join()(d, d) shared one identity and cache path but gave different rows. One rule, refuse_repeated_operands, refuses the same stream twice before anything is recorded: by object identity when the pod is called on its own (no content hash is computed there), by content hash when a pipeline records the step. It asks argument_symmetry only once a repeat is found. input_positions gives every input of a commutative operator no position, also with one input; a function or side-effect pod's one input stays at 0. Found by an independent review of 9881264f. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1419.md | 33 +++-- docs/dev/plans/itl-1419-edge-positions.md | 36 +++-- docs/reference/hashing.md | 2 +- docs/tutorial/handling-errors.md | 10 +- src/orcapod/core/function_pod.py | 7 + .../core/operators/repeated_operands.py | 75 ++++++++++ .../core/operators/static_output_pod.py | 3 + src/orcapod/pipeline/base.py | 9 ++ src/orcapod/pipeline/edges.py | 20 +-- tests/test_pipeline/test_edge_positions.py | 133 ++++++++++++++---- tests/test_pipeline/test_graph_walk_cost.py | 4 +- 11 files changed, 277 insertions(+), 55 deletions(-) create mode 100644 src/orcapod/core/operators/repeated_operands.py diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 9bd5efd78..9ac2c3a24 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -1,18 +1,35 @@ +### Breaking changes and migration + +- A commutative operator (`Join`, `Rejoin`) or a function pod given the same stream more + than once is refused with `InputValidationError`, naming the pod and the stream, before + anything is recorded (ITL-1419; decided on the developer's behalf, November 26, 2026). + Such a pod hashes its inputs as a set, so `Join()(d)` and `Join()(d, d)` had one + identity, stored path and cache entry but different rows (a stream whose only data + columns are data-tags, joined with itself, repeated every row whose key repeats; which + rows a job kept depended on the order the steps were recorded in). Called on its own, + the pod refuses the same stream object twice; recorded in a pipeline, also two streams + of one content hash (two sources of one identity), which would be one step there. + Before, `Join()(d, d)` ran when no data column overlapped, and was refused (overlapping + data columns) otherwise. To join a stream with itself, use `MergeJoin()(d, d)`, whose + inputs are ordered. + ### Fixed - A job runs an ordered operator given one stream for both inputs, `MergeJoin()(a, a)` and `SemiJoin()(a, a)` (ITL-1419, stage 1 of ITL-1472). A pipeline's graph edges now carry their input position, `(upstream, node, position)`: the argument index for an - ordered pod, none for a commutative one. Both orchestrators give a node one input per - edge, so the operator gets its two inputs, sync and async, in a job made from a - `Pipeline` or a `PipelineJob`, after `PipelineJob.load` and through `node.run()`; before, - the run raised "BinaryOperator requires exactly two input streams". No hash, stored path, - stored column or saved file changes: a saved file still lists each `(upstream, node)` - pair once, and the positions are rebuilt from an operator's saved `inputs` list. - `Join`, `Rejoin` and a function pod given one stream twice are still refused (overlapping - data columns). + ordered operator, none for a commutative one (also with one input), 0 for a function or + side-effect pod. Both orchestrators give a node one input per edge, so the operator gets + its two inputs, sync and async, in a job made from a `Pipeline` or a `PipelineJob`, after + `PipelineJob.load` and through `node.run()`; before, the run raised "BinaryOperator + requires exactly two input streams". No hash, stored path, stored column or saved file + changes: a saved file still lists each `(upstream, node)` pair once, and the positions + are rebuilt from an operator's saved `inputs` list. ### Known limitations - `diagram()` draws one line for the two inputs of `MergeJoin()(a, a)`: drawing one line per positioned edge is left to stage 2 of ITL-1472. +- An operator a loaded file keeps read-only (its config cannot be rebuilt) has its inputs + positioned by argument index, also when it is commutative; such a node never runs. + Saved positions are stage 2 of ITL-1472. diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index 264af765c..3d982594f 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -16,19 +16,36 @@ with one predecessor: the sync orchestrator hands the operator one stream ("Bina requires exactly two input streams"), the async one one reader. Pinned by `tests/test_pipeline/test_loaded_argument_order.py::test_one_stream_given_twice_fails_to_run_in_a_job`. -## What one stream given twice does elsewhere (unchanged by this stage) +## One stream given twice to a commutative pod: refused -- `Join()(a, a)` and `Rejoin()(a, a)`: refused by the operator itself (overlapping data - columns, `InputValidationError`), standalone and when recorded into a pipeline. Kept. -- A function pod given one stream for two parameters, `pod(a, a)`: the pod joins its inputs - first, so it is refused as `Join(a, a)` is, standalone and when recorded. Kept. +Independent review of the first head found that a commutative operator hashes its operands +as a set, so `Join()(d)` and `Join()(d, d)` (where `d` has no data column besides its +data-tags, so no overlap refuses it) shared one content hash and cache path but gave +different rows (5 against 3 for `id = [1, 1, 2]`), and which one a job kept followed the +order the steps were recorded in. Decided on the developer's behalf (2026-11-26): a +commutative operator (`Join`, `Rejoin`, any pod whose `argument_symmetry` is a +`frozenset`) or a function pod given the same stream more than once is refused with +`InputValidationError` before anything is recorded, naming the pod and the stream and +pointing to `MergeJoin` for a self-join. One rule, +`core/operators/repeated_operands.refuse_repeated_operands`: an operator's `process` and a +function pod's `handle_input_streams` call it with the operands' identity (the same object +twice), and `_record_invocation` with their content hashes (also two streams of one +identity, which would be one step of the pipeline). Called on its own, a pod computes no +content hash of its inputs (hashing a raw stream reads its rows, and not every value type +can be hashed), and the rule asks `argument_symmetry` (which builds a `frozenset` of the +streams, hashing them) only once a repeat is found. Before, standalone `Join()(d, d)` ran when no data column overlapped and was +refused (overlapping data columns) otherwise. + +A commutative operator's inputs have no position also when it has one input (`Join()(a)`): +only a function or side-effect pod gets position 0 for its one input. ## Change 1. **One rule for positions** (new `src/orcapod/pipeline/edges.py`): `input_positions(pod, - inputs)` gives each input its position, the argument index when the pod's - `argument_symmetry` is a tuple (function and side-effect pods: 0; `MergeJoin`, `SemiJoin`: - 0 and 1) and `None` when it is a `frozenset` (`Join`, `Rejoin`). Used by + inputs)` gives each input of an operator its argument index when the operator's + `argument_symmetry` is a tuple (`MergeJoin`, `SemiJoin`: 0 and 1) and `None` when it is a + `frozenset` (`Join`, `Rejoin`, with any number of inputs); a function or side-effect pod's + one input is at 0. Used by `_record_invocation`, `compile`, the `PipelineJob` rebuild of a blueprint and the loader. 2. **Hash-level edges are triples.** `_graph_edges` becomes a sorted list of `(upstream key, node key, position)`. `_hash_graph` (networkx, used for topological order and @@ -77,7 +94,8 @@ New file `tests/test_pipeline/test_edge_positions.py`, inputs with two tag and t another at 1 and the reverse, give the standalone rows. - A source node's observer events are the same for `MergeJoin(A, A)` as for `MergeJoin(A, B)` per source (one start and end per run). -- `Join(A, A)`, `Rejoin(A, A)` and a function pod given `(A, A)` stay refused. +- `Join`, `Rejoin` and a function pod given one stream twice are refused, standalone and + at recording, in both recording orders, sync and async; `Join(a)` has position `None`. - The saved file of a job with `MergeJoin(A, A)` has one edge pair and `inputs` `[A, A]`; saving a loaded job writes the same bytes. - `test_one_stream_given_twice_fails_to_run_in_a_job` becomes the test that it runs. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 697ca0881..b62b68bb5 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -394,7 +394,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:_invocation_edges` (the upstream keys of positioned edges, ITL-1419), `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation` (also comparing a commutative pod's input keys, ITL-1419), `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:_invocation_edges` (the upstream keys of positioned edges, ITL-1419), `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | diff --git a/docs/tutorial/handling-errors.md b/docs/tutorial/handling-errors.md index 1fdc3ee6a..5305c5b10 100644 --- a/docs/tutorial/handling-errors.md +++ b/docs/tutorial/handling-errors.md @@ -281,13 +281,15 @@ one. try: units.join(units) except InputValidationError as err: - print("c:", str(err).split(", but")[0]) - # c: Input streams are not compatible: Datas should not have overlapping keys + print("c:", str(err).split(". ")[0]) + # c: Join is given the same stream 'CSVSource' more than once ``` (a) The column is called `subject_id`. (b) `n_spikes` is in `units`: - pass both, `firing_rate.pod(units, sessions)`. (c) Both sides have the same data columns. - If two tables share a column name, rename one side or use `MergeJoin` (Part 3). + pass both, `firing_rate.pod(units, sessions)`. (c) A join takes each stream once: it + treats its inputs as a set, so a stream given twice is refused. To put a stream beside + itself, use `MergeJoin` (Part 3), whose inputs are ordered. Two different tables that + share a data column name are refused too: rename one side, or use `MergeJoin`. **2.** Run the failing version of `firing_rate` (the one with the 1200 limit) in a job with only a `StatusObserver`, and print how many rows ended in each state. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 8a24c3b49..b6952c889 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -647,6 +647,13 @@ def handle_input_streams(self, *streams: StreamProtocol) -> StreamProtocol: if len(streams) == 0: raise ValueError("At least one input stream is required") elif len(streams) > 1: + from orcapod.core.operators.repeated_operands import ( + refuse_repeated_operands, + ) + + # The pod joins its inputs: one stream twice is refused, naming the pod + # (ITL-1419), before the join is built or recorded. + refuse_repeated_operands(self, streams) # TODO: simplify the multi-stream handling logic multi_stream_handler = self.multi_stream_handler() joined_stream = multi_stream_handler.process(*streams) diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py new file mode 100644 index 000000000..9006c2171 --- /dev/null +++ b/src/orcapod/core/operators/repeated_operands.py @@ -0,0 +1,75 @@ +"""A commutative pod is never given the same stream twice (ITL-1419). + +A pod whose ``argument_symmetry`` is a ``frozenset`` (``Join``, ``Rejoin``, a function pod, +which joins its inputs) hashes its operands as a set: ``Join()(d)`` and ``Join()(d, d)`` +would have one identity, one stored path and one cache entry, yet give different rows +(a stream joined with itself repeats every row whose key repeats). So the same stream +twice is refused before anything is recorded, standalone (the same object) and when a +pipeline records the step (also two streams of one content hash) (decided on the +developer's behalf, November 26, 2026). An ordered operator (``MergeJoin``, ``SemiJoin``) takes one +stream twice: its positions are part of its identity. +""" + +from __future__ import annotations + +from collections.abc import Hashable, Sequence +from typing import TYPE_CHECKING, Protocol + +from orcapod.errors import InputValidationError + +if TYPE_CHECKING: + from collections.abc import Collection + + from orcapod.protocols.core_protocols import StreamProtocol + + +class _SymmetryDeclaring(Protocol): + """A pod, as far as this rule reads it: its argument symmetry.""" + + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> object: ... + + +def refuse_repeated_operands( + pod: _SymmetryDeclaring, + streams: Sequence[StreamProtocol], + keys: Sequence[Hashable] | None = None, +) -> None: + """Refuse the same stream given twice to a commutative pod. + + Two operands are the same stream when they have one key. Without ``keys`` the key + is the object itself: a pod called on its own compares its operands by identity, + since it computes no content hash for them (hashing a raw stream reads its rows, and + not every value type can be hashed). A pipeline recording the step passes the + operands' content hashes, which it computes anyway: there two streams of one + identity would make one step of two, so they are the same stream too. + + Args: + pod: The pod the streams are given to. + streams: Its operands, in argument order. + keys: One key per operand, in argument order; the objects' identity when + ``None``. + + Raises: + InputValidationError: If ``pod`` is commutative (its ``argument_symmetry`` is a + ``frozenset``) and two of ``streams`` have one key. The message names the + pod and the stream, and ``MergeJoin`` for a self-join. + """ + seen: set[Hashable] = set() + repeated: StreamProtocol | None = None + for stream, key in zip( + streams, keys if keys is not None else [id(s) for s in streams], strict=True + ): + if key in seen: + repeated = stream + break + seen.add(key) + # The symmetry is asked only for a repeat: a commutative operator's + # ``argument_symmetry`` builds a frozenset of its streams, which hashes them. + if repeated is None or not isinstance(pod.argument_symmetry(streams), frozenset): + return + raise InputValidationError( + f"{type(pod).__name__} is given the same stream {repeated.label!r} more than " + "once. It treats its inputs as a set, so a repeated input would change its rows " + "but not its identity. Give each stream once; to join a stream with itself, use " + "MergeJoin, whose inputs are ordered: MergeJoin()(stream, stream)." + ) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..2978f07cc 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -318,6 +318,9 @@ def process( self._note_provisional_identity_use() # perform input stream validation + from orcapod.core.operators.repeated_operands import refuse_repeated_operands + + refuse_repeated_operands(self, streams) self.check_data_tag_support(*streams) self.validate_inputs(*streams) self.tracker_manager.record_operator_pod_invocation( diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index d125572d1..ae5566b9d 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -343,7 +343,11 @@ def _record_invocation(self, invocation: PodInvocation) -> None: than the pipeline's streams read it under now, or two of its inputs read one source under two restrictions (ITL-1218), whatever streams lead there. Nothing is recorded then. + InputValidationError: If the pod is commutative and two of its inputs have + one content hash (``refuse_repeated_operands``, ITL-1419). Nothing is + recorded then. """ + from orcapod.core.operators.repeated_operands import refuse_repeated_operands from orcapod.pipeline.restrictions import require_one_restriction key = invocation.content_hash().to_string() @@ -358,6 +362,11 @@ def _record_invocation(self, invocation: PodInvocation) -> None: # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). require_one_restriction([*self._held_streams(), *inputs]) + # A commutative pod hashes its inputs as a set: two inputs of one identity + # would make one step of two different ones (ITL-1419). + refuse_repeated_operands( + invocation.pod, inputs, [upstream_hash for _, upstream_hash in upstreams] + ) self._remember_invocation(key, invocation) self._hash_graph.add_node(key) self._hash_graph.add_edges_from( diff --git a/src/orcapod/pipeline/edges.py b/src/orcapod/pipeline/edges.py index c423185aa..491c9cf21 100644 --- a/src/orcapod/pipeline/edges.py +++ b/src/orcapod/pipeline/edges.py @@ -44,13 +44,15 @@ def input_positions( ) -> tuple[Position, ...]: """The position of each of ``inputs`` of ``pod``. - A pod with one input gives it position 0. Otherwise the kind of - ``pod.argument_symmetry(inputs)`` decides: a ``tuple`` (ordered: ``MergeJoin``, - ``SemiJoin``) gives each input its argument index, a ``frozenset`` (commutative: - ``Join``, ``Rejoin``) gives every input ``None``. Only the kind of the returned - group is read, so ``inputs`` may hold one stream twice. A pod that is not known - (``None``: a node a loaded file keeps read-only, or of a kind this version does not - restore) has its inputs in the argument order the file gives, so each its index. + For an operator, the kind of ``pod.argument_symmetry(inputs)`` decides, with any + number of inputs: a ``tuple`` (ordered: ``MergeJoin``, ``SemiJoin``, a unary + operator) gives each input its argument index, a ``frozenset`` (commutative: + ``Join``, ``Rejoin``, also given one input) gives every input ``None``. Only the + kind of the returned group is read. A function pod is recorded with its one + (joined) input and a side-effect pod takes one input: position 0. A pod that is not + known (``None``: a node a loaded file keeps read-only, or of a kind this version + does not restore) has its inputs in the argument order the file gives, so each its + index. Args: pod: The pod the inputs are given to, or ``None`` when it is not known. @@ -60,7 +62,9 @@ def input_positions( Returns: One position per input, in argument order. """ - if len(inputs) <= 1 or pod is None: + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + if not isinstance(pod, StaticOutputOperatorPod) or not inputs: return tuple(range(len(inputs))) streams = cast("Sequence[StreamProtocol]", inputs) if isinstance(pod.argument_symmetry(streams), frozenset): diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index 4a1da2cac..3464cfa89 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -295,36 +295,115 @@ def events_of(twice: bool) -> list[tuple[str, str]]: # ── what stays refused ─────────────────────────────────────────────────────── -@pytest.mark.parametrize("operator", [Join, Rejoin]) -def test_a_commutative_operator_given_one_stream_twice_is_refused( - operator: type, +def _data_tags_only(name: str = "d") -> Any: + """A source whose one tag is a data-tag and which has no other data column: no + data column overlaps when it is given twice. ``id`` repeats a value, so + ``Join(d, d)`` would give 5 rows where ``Join(d)`` gives 3.""" + table = pa.table({"id": pa.array([1, 1, 2], pa.int64())}) + return sources.ArrowTableSource( + table, tag_columns=["id"], tag_only_columns=False, source_id=name + ) + + +def _data_tags_and_data(name: str = "w") -> Any: + """Two data-tags (``id``, ``key``) and two data columns (``x``, ``y``).""" + table = pa.table( + { + "key": pa.array(["p", "p", "q"], pa.large_string()), + "x": pa.array([1, 2, 3], pa.int64()), + "id": pa.array([1, 1, 2], pa.int64()), + "y": pa.array([10, 20, 30], pa.int64()), + } + ) + return sources.ArrowTableSource( + table, tag_columns=["id", "key"], tag_only_columns=False, source_id=name + ) + + +@function_pod(output_keys="s") +def _identity(id: int | None) -> int | None: + return id + + +COMMUTATIVE = { + "Join": lambda *streams, **kw: Join()(*streams, **kw), + "Rejoin": lambda *streams, **kw: Rejoin()(*streams, **kw), + "function_pod": lambda *streams, **kw: _identity.pod(*streams, **kw), +} +INPUTS = {"data_tags_only": _data_tags_only, "data_tags_and_data": _data_tags_and_data} + + +@pytest.mark.parametrize("inputs", sorted(INPUTS)) +@pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) +def test_a_repeated_operand_of_a_commutative_pod_is_refused_standalone( + pod: str, inputs: str ) -> None: - """Unchanged: the operator refuses its overlapping data columns, standalone and - when recorded into a job.""" - a = _a("tags_id_key") - with pytest.raises(InputValidationError, match="overlapping"): - operator()(a, a) + """A commutative operator, or a function pod (which joins its inputs), hashes its + operands as a set, so ``Join(d)`` and ``Join(d, d)`` would share one identity + and cache path but give different rows. The same stream object twice is refused, + naming the pod and the stream.""" + stream = INPUTS[inputs]() + name = "FunctionPod" if pod == "function_pod" else pod + with pytest.raises(InputValidationError, match=rf"{name}.*same stream.*MergeJoin"): + COMMUTATIVE[pod](stream, stream) + + +@pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) +def test_two_sources_of_one_identity_are_one_stream_when_recorded(pod: str) -> None: + """Two source objects of one identity: a pod called on its own compares objects + (it computes no content hash), so ``Join(d1, d2)`` is not refused for being one + stream there; recorded in a pipeline, their one content hash makes them one stream, + refused before anything is recorded (the function pod's join is the step refused).""" + d1, d2 = _data_tags_only(), _data_tags_only() + assert d1 is not d2 and d1.content_hash() == d2.content_hash() + COMMUTATIVE[pod](d1, d2) # not refused as one stream on its own job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) - with pytest.raises(InputValidationError, match="overlapping"): + name = "Rejoin" if pod == "Rejoin" else "Join" + with pytest.raises(InputValidationError, match=rf"{name} is given the same stream"): with job: - operator()(a, a, label="step") + COMMUTATIVE[pod](d1, d2, label="twice") + assert "twice" not in job.nodes -def test_a_function_pod_given_one_stream_twice_is_refused() -> None: - """Unchanged: a function pod joins its inputs first, so one stream given for two - parameters is refused as ``Join(a, a)`` is.""" +@pytest.mark.parametrize("pod", ["Join", "Rejoin"]) +def test_a_repeat_among_three_operands_is_refused(pod: str) -> None: + d, w = _data_tags_only("d"), _data_tags_and_data("w") + with pytest.raises(InputValidationError, match="same stream"): + COMMUTATIVE[pod](d, w.select_data_columns(["x"]), d) - @function_pod(output_keys="s") - def add(x: int, y: int) -> int: - return x + y - a = _a("tags_id_key") - with pytest.raises(InputValidationError, match="overlapping"): - add.pod(a, a) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("repeated_first", [False, True]) +@pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) +def test_a_repeated_operand_is_refused_when_recorded_in_either_order( + pod: str, repeated_first: bool, mode: str +) -> None: + """Refused before anything is recorded, whether the one-operand step is recorded + before or after: the job keeps only that step, and runs it (sync and async) with + the rows of the standalone step.""" + d = _data_tags_only() + # Tags and data only: a function's result record id (in its source info) is + # not the standalone pod's inside a job, whatever this test does. + expected = _rows(COMMUTATIVE[pod](d).as_table()) job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) - with pytest.raises(InputValidationError, match="overlapping"): - with job: - add.pod(a, a, label="step") + with job: + if not repeated_first: + COMMUTATIVE[pod](d, label="once") + with pytest.raises(InputValidationError, match="same stream"): + COMMUTATIVE[pod](d, d, label="twice") + if repeated_first: + COMMUTATIVE[pod](d, label="once") + assert "twice" not in job.nodes + _run(job, mode) + assert _rows(job.once.as_table()) == expected + assert len(expected) == 3 + + +def test_an_ordered_operator_still_takes_one_stream_twice() -> None: + """The refusal is for commutative pods only: ``MergeJoin(d, d)`` is two edges.""" + d = _data_tags_only() + assert MergeJoin()(d, d).as_table().num_rows == 5 + assert SemiJoin()(d, d).as_table().num_rows == 3 # ── the positioned edges ───────────────────────────────────────────────────── @@ -339,13 +418,15 @@ def _edges_by_label(job: Any) -> list[tuple[str, str, int | None]]: return sorted( (label[up], label[down], position) for up, down, position in job._graph_edges # pyright: ignore[reportPrivateUsage] - if down in label and label[down] in {"aa", "ab", "ba", "joined", "fn"} + if down in label + and label[down] in {"aa", "ab", "ba", "joined", "fn", "join1", "rejoin1"} ) def test_each_input_is_one_edge_at_its_position(tmp_path: Path) -> None: """An ordered operator's inputs are at their argument index, a commutative one's - have no position, a function pod's input is at 0; the same after save and load.""" + have no position (also with one input), a function pod's input is at 0; the same + after save and load.""" a = _csv_a(tmp_path, "tags_id_key") b = _csv(tmp_path, "b", "tags_key_id", [(1, "p", 100, 1000), (2, "q", 101, 1001)]) @@ -364,13 +445,17 @@ def total(x: int, y: int) -> int: label="joined", ) total.pod(a, label="fn") + Join()(a, label="join1") + Rejoin()(b, label="rejoin1") expected = [ ("a", "aa", 0), ("a", "aa", 1), ("a", "ba", 1), ("a", "fn", 0), + ("a", "join1", None), ("ax", "joined", None), ("b", "ba", 0), + ("b", "rejoin1", None), ("by", "joined", None), ] assert _edges_by_label(job) == expected diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index 359830e71..d78f366bc 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -398,7 +398,9 @@ def test_a_join_error_is_bounded_and_names_the_inputs_and_the_column( """A join of two inputs sharing a data column fails with a short message naming both.""" stream = _guarded_build(shape, monkeypatch) left = stream.map_data({"x": "y"}, label="left_branch") - right = stream.map_data({"x": "y"}, label="right_branch") + # Another computation with the column ``y``: two equal branches would be one + # stream given twice, which a join refuses before comparing columns (ITL-1419). + right = stream.map_data({"x": "z"}).map_data({"z": "y"}, label="right_branch") with _count_schema_queries(monkeypatch, _budget(shape)): with pytest.raises(InputValidationError) as excinfo: left.join(right) From 79e86762b1bf19146b16c4e7e978d3e631bef7ad Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 05:26:34 -0800 Subject: [PATCH 04/11] fix(operators): refuse a repeated operand where a commutative identity is formed (ITL-1419) Round-2 review of a09a869e: an object-identity check missed two separate streams of one identity (standalone hashes still collided; a step recorded over them compiled in one order and failed in the other), added its own error for an operand that cannot be hashed, and did not name the function of a function pod. The set a commutative identity is built from is formed in one place, repeated_operands.operand_set, which raises RepeatedOperandError when two operands have one identity. Join.argument_symmetry (so Rejoin), the commutative branch of BinaryOperator.argument_symmetry and the function pod's argument_symmetry call it and name the operator or the function; a function pod forms it when called with several inputs. Hashing, recording and compiling all meet the same refusal; the separate checks are gone. An operand that cannot be hashed raises the hashing error. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1419.md | 31 ++-- docs/dev/plans/itl-1419-edge-positions.md | 28 ++-- docs/reference/hashing.md | 2 +- docs/tutorial/handling-errors.md | 10 +- src/orcapod/core/function_pod.py | 27 +++- src/orcapod/core/operators/base.py | 14 +- src/orcapod/core/operators/join.py | 16 +- src/orcapod/core/operators/rejoin.py | 6 +- .../core/operators/repeated_operands.py | 109 +++++++------- .../core/operators/static_output_pod.py | 3 - src/orcapod/pipeline/base.py | 10 +- tests/test_pipeline/test_edge_positions.py | 142 ++++++++++++------ tests/test_pipeline/test_graph_walk_cost.py | 4 +- 13 files changed, 244 insertions(+), 158 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 9ac2c3a24..744d136e2 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -1,17 +1,24 @@ ### Breaking changes and migration -- A commutative operator (`Join`, `Rejoin`) or a function pod given the same stream more - than once is refused with `InputValidationError`, naming the pod and the stream, before - anything is recorded (ITL-1419; decided on the developer's behalf, November 26, 2026). - Such a pod hashes its inputs as a set, so `Join()(d)` and `Join()(d, d)` had one - identity, stored path and cache entry but different rows (a stream whose only data - columns are data-tags, joined with itself, repeated every row whose key repeats; which - rows a job kept depended on the order the steps were recorded in). Called on its own, - the pod refuses the same stream object twice; recorded in a pipeline, also two streams - of one content hash (two sources of one identity), which would be one step there. - Before, `Join()(d, d)` ran when no data column overlapped, and was refused (overlapping - data columns) otherwise. To join a stream with itself, use `MergeJoin()(d, d)`, whose - inputs are ordered. +- A commutative operator (`Join`, `Rejoin`, a commutative binary operator) or a function + pod given one stream more than once (two operands of one identity: one object, or two + separate streams such as two sources with one source id and schema) is refused with + `RepeatedOperandError` (an `InputValidationError`), naming the operator or the function + and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, + November 26, 2026). Such a pod forms its identity from its operands as a set, so + `Join()(d)` and `Join()(d, d2)` had one identity, stored path and cache entry but + different rows (a stream whose only data columns are data-tags, joined with itself, + repeated every row whose key repeats; in a job, which rows were kept, or whether a later + step compiled at all, depended on the order the steps were recorded in). The refusal is + where that set is formed, the operator's `argument_symmetry`, so it is met wherever the + identity is: hashing the result, recording the step in a pipeline, compiling it. A + function pod forms it when it is called with several inputs. Rows computed without + forming the identity (standalone `Join()(d, d).as_table()`) are computed as before. An + operand whose identity cannot be computed (a raw stream holding a value that cannot be + hashed) raises what hashing it raises; the rule adds no error of its own. Inputs that + share a data column are still refused first, when the step is built (overlapping data + columns). To join a stream with itself, use `MergeJoin()(d, d)`, whose inputs are + ordered. ### Fixed diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index 3d982594f..b50772761 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -22,19 +22,21 @@ Independent review of the first head found that a commutative operator hashes it as a set, so `Join()(d)` and `Join()(d, d)` (where `d` has no data column besides its data-tags, so no overlap refuses it) shared one content hash and cache path but gave different rows (5 against 3 for `id = [1, 1, 2]`), and which one a job kept followed the -order the steps were recorded in. Decided on the developer's behalf (2026-11-26): a -commutative operator (`Join`, `Rejoin`, any pod whose `argument_symmetry` is a -`frozenset`) or a function pod given the same stream more than once is refused with -`InputValidationError` before anything is recorded, naming the pod and the stream and -pointing to `MergeJoin` for a self-join. One rule, -`core/operators/repeated_operands.refuse_repeated_operands`: an operator's `process` and a -function pod's `handle_input_streams` call it with the operands' identity (the same object -twice), and `_record_invocation` with their content hashes (also two streams of one -identity, which would be one step of the pipeline). Called on its own, a pod computes no -content hash of its inputs (hashing a raw stream reads its rows, and not every value type -can be hashed), and the rule asks `argument_symmetry` (which builds a `frozenset` of the -streams, hashing them) only once a repeat is found. Before, standalone `Join()(d, d)` ran when no data column overlapped and was -refused (overlapping data columns) otherwise. +order the steps were recorded in. The round-2 review found that a check by object identity +missed two separate sources of one identity (standalone hashes still collided, and a step +recorded over them compiled in one order and failed in the other), and that the check +added its own error for an operand that cannot be hashed. + +Decided on the developer's behalf (2026-11-26): refuse exactly where the identity is formed +from the operands as a set. `core/operators/repeated_operands.operand_set` builds that set +and raises `RepeatedOperandError` (an `InputValidationError`) when two operands have one +identity (they are equal as the set compares them). `Join.argument_symmetry` (so also +`Rejoin`), the commutative branch of `BinaryOperator.argument_symmetry` and the function +pod's `argument_symmetry` call it and name the operator or the function. Whatever forms the +identity meets the refusal: hashing, recording, compiling; a function pod forms it when +called with several inputs. No separate check remains. An operand whose identity cannot be +computed raises what hashing it raises. Rows computed without forming the identity +(standalone `as_table()`) are computed as before. A commutative operator's inputs have no position also when it has one input (`Join()(a)`): only a function or side-effect pod gets position 0 for its one input. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index b62b68bb5..697ca0881 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -394,7 +394,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu |---|---| | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | -| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation` (also comparing a commutative pod's input keys, ITL-1419), `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:_invocation_edges` (the upstream keys of positioned edges, ITL-1419), `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:_invocation_edges` (the upstream keys of positioned edges, ITL-1419), `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | | in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | diff --git a/docs/tutorial/handling-errors.md b/docs/tutorial/handling-errors.md index 5305c5b10..1fdc3ee6a 100644 --- a/docs/tutorial/handling-errors.md +++ b/docs/tutorial/handling-errors.md @@ -281,15 +281,13 @@ one. try: units.join(units) except InputValidationError as err: - print("c:", str(err).split(". ")[0]) - # c: Join is given the same stream 'CSVSource' more than once + print("c:", str(err).split(", but")[0]) + # c: Input streams are not compatible: Datas should not have overlapping keys ``` (a) The column is called `subject_id`. (b) `n_spikes` is in `units`: - pass both, `firing_rate.pod(units, sessions)`. (c) A join takes each stream once: it - treats its inputs as a set, so a stream given twice is refused. To put a stream beside - itself, use `MergeJoin` (Part 3), whose inputs are ordered. Two different tables that - share a data column name are refused too: rename one side, or use `MergeJoin`. + pass both, `firing_rate.pod(units, sessions)`. (c) Both sides have the same data columns. + If two tables share a column name, rename one side or use `MergeJoin` (Part 3). **2.** Run the failing version of `firing_rate` (the one with the 1200 limit) in a job with only a `StatusObserver`, and print how many rows ended in each state. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index b6952c889..b6ae31f90 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -647,13 +647,9 @@ def handle_input_streams(self, *streams: StreamProtocol) -> StreamProtocol: if len(streams) == 0: raise ValueError("At least one input stream is required") elif len(streams) > 1: - from orcapod.core.operators.repeated_operands import ( - refuse_repeated_operands, - ) - - # The pod joins its inputs: one stream twice is refused, naming the pod - # (ITL-1419), before the join is built or recorded. - refuse_repeated_operands(self, streams) + # The pod's identity covers its inputs as the set its join forms: one + # stream twice is refused here, naming the function (ITL-1419). + _ = self.argument_symmetry(streams) # TODO: simplify the multi-stream handling logic multi_stream_handler = self.multi_stream_handler() joined_stream = multi_stream_handler.process(*streams) @@ -870,7 +866,22 @@ def __call__( return self.process(input_stream, label=label) def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: - return self.multi_stream_handler().argument_symmetry(streams) + """The symmetry of the join the pod puts its inputs through. + + Raises: + RepeatedOperandError: If two inputs have one identity (ITL-1419), naming + the function. + """ + from orcapod.core.operators.repeated_operands import RepeatedOperandError + + try: + return self.multi_stream_handler().argument_symmetry(streams) + except RepeatedOperandError as err: + raise RepeatedOperandError( + err.reason, + pod=f"the function pod of {self.canonical_function_name!r}, which joins " + "its inputs", + ) from None def output_schema( self, diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index c0fd0c320..6c82642ec 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -309,8 +309,18 @@ def validate_inputs(self, *streams: StreamProtocol) -> None: def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: if self.is_commutative(): - # return as symmetric group - return frozenset(streams) + # return as symmetric group, refusing one stream twice (ITL-1419) + from orcapod.core.operators.repeated_operands import ( + RepeatedOperandError, + operand_set, + ) + + try: + return operand_set(streams) + except RepeatedOperandError as err: + raise RepeatedOperandError( + err.reason, pod=type(self).__name__ + ) from None else: # return as ordered group return tuple(streams) diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 430957232..5902871f1 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -215,7 +215,21 @@ 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) + """The inputs as a set: ``Join`` is commutative. + + Raises: + RepeatedOperandError: If two inputs have one identity (ITL-1419): a set + cannot tell ``Join(d)`` from ``Join(d, d)``. + """ + from orcapod.core.operators.repeated_operands import ( + RepeatedOperandError, + operand_set, + ) + + try: + return operand_set(streams) + except RepeatedOperandError as err: + raise RepeatedOperandError(err.reason, pod=type(self).__name__) from None def output_schema( self, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..fbf32d487 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -277,8 +277,10 @@ class Rejoin(Join): each branch went through operators that keep system tags (filters, column selection and renaming, ``AddTags``, function pods) and no ``Join``, ``GroupBy`` or ``Batch``. Data columns must be disjoint, as in ``Join``, and a data-tag in several inputs is - one column. These are the only refusals: each is read from the inputs' columns, - none from their rows. + one column. These refusals are read from the inputs' columns, none from their rows. + As for ``Join``, the inputs form a set, so one stream given twice (two inputs of one + identity) is refused when the identity is formed, by hashing the result or recording + the step (``RepeatedOperandError``, ITL-1419): give each branch once. 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 diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index 9006c2171..e7683a891 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -1,75 +1,70 @@ -"""A commutative pod is never given the same stream twice (ITL-1419). +"""A commutative pod is never given one stream twice (ITL-1419). -A pod whose ``argument_symmetry`` is a ``frozenset`` (``Join``, ``Rejoin``, a function pod, -which joins its inputs) hashes its operands as a set: ``Join()(d)`` and ``Join()(d, d)`` -would have one identity, one stored path and one cache entry, yet give different rows -(a stream joined with itself repeats every row whose key repeats). So the same stream -twice is refused before anything is recorded, standalone (the same object) and when a -pipeline records the step (also two streams of one content hash) (decided on the -developer's behalf, November 26, 2026). An ordered operator (``MergeJoin``, ``SemiJoin``) takes one -stream twice: its positions are part of its identity. +A pod whose identity is formed from its operands as a set (``Join``, ``Rejoin``, a +commutative binary operator, a function pod, which joins its inputs) would give +``Join()(d)`` and ``Join()(d, d2)`` one identity, one stored path and one cache entry, +when ``d2`` is ``d`` or a separate stream of ``d``'s identity, yet different rows (a stream +joined with itself repeats every row whose key repeats). So the set is formed in one +place, ``operand_set``, which refuses two operands of one identity, the hash the set is +built from (decided on the developer's behalf, November 26, 2026). Whatever forms the +identity meets the refusal: hashing a stream standalone, recording a step in a pipeline, +compiling it. An ordered operator (``MergeJoin``, ``SemiJoin``) takes one stream twice: +its positions are part of its identity. + +The rule adds no error of its own for an operand whose identity cannot be computed (a raw +stream holding a value that cannot be hashed): it raises what hashing that stream raises. """ from __future__ import annotations -from collections.abc import Hashable, Sequence -from typing import TYPE_CHECKING, Protocol +from collections.abc import Collection from orcapod.errors import InputValidationError - -if TYPE_CHECKING: - from collections.abc import Collection - - from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols import StreamProtocol -class _SymmetryDeclaring(Protocol): - """A pod, as far as this rule reads it: its argument symmetry.""" +class RepeatedOperandError(InputValidationError): + """Two operands of a commutative pod have one identity. - def argument_symmetry(self, streams: Collection[StreamProtocol]) -> object: ... + Args: + reason: What is repeated and what to do instead. + pod: The operator or function the operands are given to, as the message names + it, or ``None`` before a caller adds it. + """ + def __init__(self, reason: str, pod: str | None = None) -> None: + self.reason: str = reason + super().__init__(f"{pod}: {reason}" if pod else reason) -def refuse_repeated_operands( - pod: _SymmetryDeclaring, - streams: Sequence[StreamProtocol], - keys: Sequence[Hashable] | None = None, -) -> None: - """Refuse the same stream given twice to a commutative pod. - Two operands are the same stream when they have one key. Without ``keys`` the key - is the object itself: a pod called on its own compares its operands by identity, - since it computes no content hash for them (hashing a raw stream reads its rows, and - not every value type can be hashed). A pipeline recording the step passes the - operands' content hashes, which it computes anyway: there two streams of one - identity would make one step of two, so they are the same stream too. +def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol]: + """The operands of a commutative pod as the set its identity is formed from. Args: - pod: The pod the streams are given to. - streams: Its operands, in argument order. - keys: One key per operand, in argument order; the objects' identity when - ``None``. + streams: The operands. + + Returns: + The operands as a ``frozenset``. Raises: - InputValidationError: If ``pod`` is commutative (its ``argument_symmetry`` is a - ``frozenset``) and two of ``streams`` have one key. The message names the - pod and the stream, and ``MergeJoin`` for a self-join. + RepeatedOperandError: If two operands have one identity (they are equal, as a + set compares them), one object or two. The caller names its pod + (``RepeatedOperandError(err.reason, pod=...)``). """ - seen: set[Hashable] = set() - repeated: StreamProtocol | None = None - for stream, key in zip( - streams, keys if keys is not None else [id(s) for s in streams], strict=True - ): - if key in seen: - repeated = stream - break - seen.add(key) - # The symmetry is asked only for a repeat: a commutative operator's - # ``argument_symmetry`` builds a frozenset of its streams, which hashes them. - if repeated is None or not isinstance(pod.argument_symmetry(streams), frozenset): - return - raise InputValidationError( - f"{type(pod).__name__} is given the same stream {repeated.label!r} more than " - "once. It treats its inputs as a set, so a repeated input would change its rows " - "but not its identity. Give each stream once; to join a stream with itself, use " - "MergeJoin, whose inputs are ordered: MergeJoin()(stream, stream)." - ) + seen: dict[StreamProtocol, StreamProtocol] = {} + for stream in streams: + first = seen.get(stream) + if first is not None: + names = ( + repr(stream.label) + if first is stream or first.label == stream.label + else f"{first.label!r} and {stream.label!r}" + ) + raise RepeatedOperandError( + f"the same stream ({names}, one identity) is given more than once. Its " + "inputs form a set, so a repeated input would change the rows but not " + "the identity. Give each stream once; to join a stream with itself, use " + "MergeJoin, whose inputs are ordered: MergeJoin()(stream, stream)." + ) + seen[stream] = stream + return frozenset(seen) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 2978f07cc..f829d44a5 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -318,9 +318,6 @@ def process( self._note_provisional_identity_use() # perform input stream validation - from orcapod.core.operators.repeated_operands import refuse_repeated_operands - - refuse_repeated_operands(self, streams) self.check_data_tag_support(*streams) self.validate_inputs(*streams) self.tracker_manager.record_operator_pod_invocation( diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index ae5566b9d..213f275e4 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -344,10 +344,9 @@ def _record_invocation(self, invocation: PodInvocation) -> None: read one source under two restrictions (ITL-1218), whatever streams lead there. Nothing is recorded then. InputValidationError: If the pod is commutative and two of its inputs have - one content hash (``refuse_repeated_operands``, ITL-1419). Nothing is - recorded then. + one identity: forming the invocation's identity refuses it + (``repeated_operands.operand_set``, ITL-1419). Nothing is recorded then. """ - from orcapod.core.operators.repeated_operands import refuse_repeated_operands from orcapod.pipeline.restrictions import require_one_restriction key = invocation.content_hash().to_string() @@ -362,11 +361,6 @@ def _record_invocation(self, invocation: PodInvocation) -> None: # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). require_one_restriction([*self._held_streams(), *inputs]) - # A commutative pod hashes its inputs as a set: two inputs of one identity - # would make one step of two different ones (ITL-1419). - refuse_repeated_operands( - invocation.pod, inputs, [upstream_hash for _, upstream_hash in upstreams] - ) self._remember_invocation(key, invocation) self._hash_graph.add_node(key) self._hash_graph.add_edges_from( diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index 3464cfa89..88d2c16fb 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -333,72 +333,130 @@ def _identity(id: int | None) -> int | None: INPUTS = {"data_tags_only": _data_tags_only, "data_tags_and_data": _data_tags_and_data} -@pytest.mark.parametrize("inputs", sorted(INPUTS)) -@pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) -def test_a_repeated_operand_of_a_commutative_pod_is_refused_standalone( - pod: str, inputs: str -) -> None: - """A commutative operator, or a function pod (which joins its inputs), hashes its - operands as a set, so ``Join(d)`` and ``Join(d, d)`` would share one identity - and cache path but give different rows. The same stream object twice is refused, - naming the pod and the stream.""" - stream = INPUTS[inputs]() - name = "FunctionPod" if pod == "function_pod" else pod - with pytest.raises(InputValidationError, match=rf"{name}.*same stream.*MergeJoin"): - COMMUTATIVE[pod](stream, stream) +REPEATS = { + "same_object": lambda make: (lambda s: (s, s))(make()), + "equal_sources": lambda make: (make(), make()), +} +REFUSAL = r"same stream.*more than once.*MergeJoin" +def _who(pod: str) -> str: + """What the refusal names: the operator, or the function of a function pod.""" + return "_identity" if pod == "function_pod" else pod + + +@pytest.mark.parametrize("repeat", sorted(REPEATS)) +@pytest.mark.parametrize("inputs", sorted(INPUTS)) @pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) -def test_two_sources_of_one_identity_are_one_stream_when_recorded(pod: str) -> None: - """Two source objects of one identity: a pod called on its own compares objects - (it computes no content hash), so ``Join(d1, d2)`` is not refused for being one - stream there; recorded in a pipeline, their one content hash makes them one stream, - refused before anything is recorded (the function pod's join is the step refused).""" - d1, d2 = _data_tags_only(), _data_tags_only() - assert d1 is not d2 and d1.content_hash() == d2.content_hash() - COMMUTATIVE[pod](d1, d2) # not refused as one stream on its own - job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) - name = "Rejoin" if pod == "Rejoin" else "Join" - with pytest.raises(InputValidationError, match=rf"{name} is given the same stream"): - with job: - COMMUTATIVE[pod](d1, d2, label="twice") - assert "twice" not in job.nodes +def test_a_repeated_operand_is_refused_where_the_identity_is_formed( + pod: str, inputs: str, repeat: str +) -> None: + """A commutative operator, or a function pod (which joins its inputs), forms its + identity from its operands as a set, so ``Join(d)`` and ``Join(d, d2)`` (``d2`` a + separate source of ``d``'s identity) would have one identity but different rows. + Forming that identity refuses two operands of one identity, one object or not, + naming the operator or function and the stream.""" + first, second = REPEATS[repeat](INPUTS[inputs]) + assert first.content_hash() == second.content_hash() + # With data columns besides the data-tags, the operator's own check refuses the + # overlapping columns first, when the step is built (as before ITL-1419). + refusal = ( + rf"{_who(pod)}.*{REFUSAL}" + if inputs == "data_tags_only" or pod == "function_pod" + else "overlapping" + ) + with pytest.raises(InputValidationError, match=refusal): + COMMUTATIVE[pod](first, second).content_hash() @pytest.mark.parametrize("pod", ["Join", "Rejoin"]) def test_a_repeat_among_three_operands_is_refused(pod: str) -> None: - d, w = _data_tags_only("d"), _data_tags_and_data("w") - with pytest.raises(InputValidationError, match="same stream"): - COMMUTATIVE[pod](d, w.select_data_columns(["x"]), d) + d = _data_tags_only("d") + # A second branch of ``d`` (Rejoin takes branches of one stream), and a separate + # source of ``d``'s identity as the third operand. + branch = d.add_tags(cohort="A") + with pytest.raises(InputValidationError, match=rf"{pod}.*{REFUSAL}"): + COMMUTATIVE[pod](d, branch, _data_tags_only("d")).content_hash() @pytest.mark.parametrize("mode", MODES) @pytest.mark.parametrize("repeated_first", [False, True]) +@pytest.mark.parametrize("repeat", sorted(REPEATS)) @pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) def test_a_repeated_operand_is_refused_when_recorded_in_either_order( - pod: str, repeated_first: bool, mode: str + pod: str, repeat: str, repeated_first: bool, mode: str ) -> None: - """Refused before anything is recorded, whether the one-operand step is recorded - before or after: the job keeps only that step, and runs it (sync and async) with - the rows of the standalone step.""" - d = _data_tags_only() - # Tags and data only: a function's result record id (in its source info) is - # not the standalone pod's inside a job, whatever this test does. - expected = _rows(COMMUTATIVE[pod](d).as_table()) + """Recording forms the identity: refused before anything is recorded, whether the + one-operand step is recorded before or after; the job keeps only that step, and + runs it (sync and async) with the rows of the standalone step.""" + first, second = REPEATS[repeat](_data_tags_only) + expected = _rows(COMMUTATIVE[pod](first).as_table()) job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) with job: if not repeated_first: - COMMUTATIVE[pod](d, label="once") - with pytest.raises(InputValidationError, match="same stream"): - COMMUTATIVE[pod](d, d, label="twice") + COMMUTATIVE[pod](first, label="once") + with pytest.raises(InputValidationError, match=rf"{_who(pod)}.*{REFUSAL}"): + COMMUTATIVE[pod](first, second, label="twice") if repeated_first: - COMMUTATIVE[pod](d, label="once") + COMMUTATIVE[pod](first, label="once") assert "twice" not in job.nodes _run(job, mode) assert _rows(job.once.as_table()) == expected assert len(expected) == 3 +@pytest.mark.parametrize("repeated_first", [False, True]) +def test_a_step_over_a_repeated_join_is_refused_in_either_order( + repeated_first: bool, +) -> None: + """Round-2 finding P1: a downstream step over ``Join(d, d2)`` ran in one recording + order and failed compilation in the other. The join is refused when its identity + is formed, in both orders.""" + d, d2 = _data_tags_only(), _data_tags_only() + job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) + with job: + if not repeated_first: + d.select_data_columns(["id"], label="once") + with pytest.raises(InputValidationError, match=REFUSAL): + Join()(d, d2).select_data_columns(["id"], label="after") + if repeated_first: + d.select_data_columns(["id"], label="once") + assert "after" not in job.nodes + job.run() + assert job.once.as_table().num_rows == 3 + + +def _raw_with_map(values: list[int]) -> Any: + """A raw stream (no source) with a map data column: its identity hashes its rows, + and a map value cannot be hashed.""" + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + table = pa.table( + { + "id": pa.array(values, pa.int64()), + "m": pa.array( + [[("k", v)] for v in values], pa.map_(pa.large_string(), pa.int64()) + ), + } + ) + return ArrowTableStream(table, tag_columns=["id"]) + + +def test_an_operand_whose_identity_cannot_be_formed_raises_the_hashing_error() -> None: + """Round-2 finding P2: the rule adds no error of its own. A raw stream whose + identity cannot be computed raises, when a commutative pod's identity is formed, + exactly what hashing that stream raises; its rows are computed as before.""" + raw = _raw_with_map([1, 2]) + other = _data_tags_and_data() + joined = Join()(raw, other.select_data_columns(["x"])) + assert joined.as_table().num_rows == 3 + with pytest.raises(ValueError) as own: + raw.content_hash() + with pytest.raises(type(own.value)) as formed: + joined.content_hash() + assert str(formed.value) == str(own.value) + + def test_an_ordered_operator_still_takes_one_stream_twice() -> None: """The refusal is for commutative pods only: ``MergeJoin(d, d)`` is two edges.""" d = _data_tags_only() diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py index d78f366bc..359830e71 100644 --- a/tests/test_pipeline/test_graph_walk_cost.py +++ b/tests/test_pipeline/test_graph_walk_cost.py @@ -398,9 +398,7 @@ def test_a_join_error_is_bounded_and_names_the_inputs_and_the_column( """A join of two inputs sharing a data column fails with a short message naming both.""" stream = _guarded_build(shape, monkeypatch) left = stream.map_data({"x": "y"}, label="left_branch") - # Another computation with the column ``y``: two equal branches would be one - # stream given twice, which a join refuses before comparing columns (ITL-1419). - right = stream.map_data({"x": "z"}).map_data({"z": "y"}, label="right_branch") + right = stream.map_data({"x": "y"}, label="right_branch") with _count_schema_queries(monkeypatch, _budget(shape)): with pytest.raises(InputValidationError) as excinfo: left.join(right) From a59c55b7e96e2afc3928f51d6b7cedd08a52b343 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 06:12:41 -0800 Subject: [PATCH 05/11] fix(operators): a function pod's rows form no identity; the refusal keeps the name of the pod given the repeat (ITL-1419) Verification of 79e86762: a standalone function pod over two inputs formed its operand set on the row path, so an unused raw map column that cannot be hashed stopped its rows; and a pod downstream of the one that got a repeated operand replaced its name in the error. The function pod no longer forms its operand set when called; the refusal is met only where an identity is formed. RepeatedOperandError is named once, by the pod whose own operands repeat (named); a pod downstream, and a function pod whose join got the operands, add context (add_context) and never replace that name. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1419.md | 11 +-- docs/dev/plans/itl-1419-edge-positions.md | 8 +- src/orcapod/core/function_pod.py | 31 +++++--- src/orcapod/core/operators/base.py | 5 +- src/orcapod/core/operators/join.py | 3 +- .../core/operators/repeated_operands.py | 41 ++++++++-- tests/test_pipeline/test_edge_positions.py | 75 ++++++++++++++++--- 7 files changed, 135 insertions(+), 39 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 744d136e2..f981d4005 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -3,17 +3,18 @@ - A commutative operator (`Join`, `Rejoin`, a commutative binary operator) or a function pod given one stream more than once (two operands of one identity: one object, or two separate streams such as two sources with one source id and schema) is refused with - `RepeatedOperandError` (an `InputValidationError`), naming the operator or the function - and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, + `RepeatedOperandError` (an `InputValidationError`), naming the operator that got the + repeated operand (a pod downstream of it, and a function pod whose join got it, add + context and never replace the name) and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, November 26, 2026). Such a pod forms its identity from its operands as a set, so `Join()(d)` and `Join()(d, d2)` had one identity, stored path and cache entry but different rows (a stream whose only data columns are data-tags, joined with itself, repeated every row whose key repeats; in a job, which rows were kept, or whether a later step compiled at all, depended on the order the steps were recorded in). The refusal is where that set is formed, the operator's `argument_symmetry`, so it is met wherever the - identity is: hashing the result, recording the step in a pipeline, compiling it. A - function pod forms it when it is called with several inputs. Rows computed without - forming the identity (standalone `Join()(d, d).as_table()`) are computed as before. An + identity is: hashing the result, recording the step in a pipeline, compiling it. Rows + computed without forming the identity (standalone `Join()(d, d).as_table()`, or a + function pod's rows over several inputs) are computed as before. An operand whose identity cannot be computed (a raw stream holding a value that cannot be hashed) raises what hashing it raises; the rule adds no error of its own. Inputs that share a data column are still refused first, when the step is built (overlapping data diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index b50772761..7b4ee87dd 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -32,9 +32,11 @@ from the operands as a set. `core/operators/repeated_operands.operand_set` build and raises `RepeatedOperandError` (an `InputValidationError`) when two operands have one identity (they are equal as the set compares them). `Join.argument_symmetry` (so also `Rejoin`), the commutative branch of `BinaryOperator.argument_symmetry` and the function -pod's `argument_symmetry` call it and name the operator or the function. Whatever forms the -identity meets the refusal: hashing, recording, compiling; a function pod forms it when -called with several inputs. No separate check remains. An operand whose identity cannot be +pod's `argument_symmetry` call it. The error names the operator whose own operands repeat +(`RepeatedOperandError.named`, set once); a pod downstream, and a function pod whose join +got the operands, add context (`add_context`) and never replace that name (verification +of the third head). Whatever forms the identity meets the refusal: hashing, recording, +compiling; a function pod never forms it on the row path. No separate check remains. An operand whose identity cannot be computed raises what hashing it raises. Rows computed without forming the identity (standalone `as_table()`) are computed as before. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index b6ae31f90..6e1d4485a 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -647,12 +647,22 @@ def handle_input_streams(self, *streams: StreamProtocol) -> StreamProtocol: if len(streams) == 0: raise ValueError("At least one input stream is required") elif len(streams) > 1: - # The pod's identity covers its inputs as the set its join forms: one - # stream twice is refused here, naming the function (ITL-1419). - _ = self.argument_symmetry(streams) # TODO: simplify the multi-stream handling logic + from orcapod.core.operators.repeated_operands import ( + RepeatedOperandError, + ) + multi_stream_handler = self.multi_stream_handler() - joined_stream = multi_stream_handler.process(*streams) + try: + joined_stream = multi_stream_handler.process(*streams) + except RepeatedOperandError as err: + # Recording the join forms its identity: the join is named, this + # function added as context (ITL-1419). Nothing is formed here that + # would not be formed anyway. + err.add_context( + f"the inputs of the function pod of {self.canonical_function_name!r}" + ) + raise return joined_stream return streams[0] @@ -869,19 +879,18 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou """The symmetry of the join the pod puts its inputs through. Raises: - RepeatedOperandError: If two inputs have one identity (ITL-1419), naming - the function. + RepeatedOperandError: If two inputs have one identity (ITL-1419): the join + that formed the set is named, and this function added as context. """ from orcapod.core.operators.repeated_operands import RepeatedOperandError try: return self.multi_stream_handler().argument_symmetry(streams) except RepeatedOperandError as err: - raise RepeatedOperandError( - err.reason, - pod=f"the function pod of {self.canonical_function_name!r}, which joins " - "its inputs", - ) from None + err.add_context( + f"the inputs of the function pod of {self.canonical_function_name!r}" + ) + raise def output_schema( self, diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index 6c82642ec..3426201d7 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -318,9 +318,8 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou try: return operand_set(streams) except RepeatedOperandError as err: - raise RepeatedOperandError( - err.reason, pod=type(self).__name__ - ) from None + # Named here only when this operator's own operands repeat. + raise err.named(type(self).__name__) from None else: # return as ordered group return tuple(streams) diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 5902871f1..66dd66ddf 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -229,7 +229,8 @@ def argument_symmetry(self, streams: Collection) -> ArgumentGroup: try: return operand_set(streams) except RepeatedOperandError as err: - raise RepeatedOperandError(err.reason, pod=type(self).__name__) from None + # Named here only when this join's own operands repeat (ITL-1419). + raise err.named(type(self).__name__) from None def output_schema( self, diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index e7683a891..9368f208e 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -26,15 +26,45 @@ class RepeatedOperandError(InputValidationError): """Two operands of a commutative pod have one identity. + The message names the pod that got the repeated operand, set once by the pod whose + own operands repeat (``named``) and never replaced. A pod further down, or a function + pod whose join got the operands, can only add context (``add_context``): what the + repeated operand is part of. + Args: reason: What is repeated and what to do instead. - pod: The operator or function the operands are given to, as the message names - it, or ``None`` before a caller adds it. + pod: The operator or function that got the repeated operand, or ``None`` until + that pod names itself. """ def __init__(self, reason: str, pod: str | None = None) -> None: self.reason: str = reason - super().__init__(f"{pod}: {reason}" if pod else reason) + self.pod: str | None = pod + self.context: list[str] = [] + super().__init__(self._message()) + + def _message(self) -> str: + message = f"{self.pod}: {self.reason}" if self.pod else self.reason + if self.context: + message += f" (in {'; '.join(self.context)})" + return message + + def named(self, pod: str) -> RepeatedOperandError: + """This error, naming ``pod`` as the one that got the repeated operand, unless + a pod is already named (the error then comes from upstream and is returned as + it is).""" + if self.pod is not None: + return self + named = RepeatedOperandError(self.reason, pod=pod) + named.context = list(self.context) + named.args = (named._message(),) + return named + + def add_context(self, context: str) -> None: + """Say what the repeated operand is part of (``"the inputs of ..."``); the named + pod is kept.""" + self.context.append(context) + self.args = (self._message(),) def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol]: @@ -48,8 +78,9 @@ def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol Raises: RepeatedOperandError: If two operands have one identity (they are equal, as a - set compares them), one object or two. The caller names its pod - (``RepeatedOperandError(err.reason, pod=...)``). + set compares them), one object or two, unnamed: the caller names its pod + (``err.named(...)``). An error met while hashing an operand (raised by a + pod upstream) is already named and passes through. """ seen: dict[StreamProtocol, StreamProtocol] = {} for stream in streams: diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index 88d2c16fb..b986636f4 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -340,9 +340,12 @@ def _identity(id: int | None) -> int | None: REFUSAL = r"same stream.*more than once.*MergeJoin" -def _who(pod: str) -> str: - """What the refusal names: the operator, or the function of a function pod.""" - return "_identity" if pod == "function_pod" else pod +def _refusal(pod: str) -> str: + """The refusal: it names the operator that formed the set (a function pod's join), + and a function pod adds its function as context.""" + if pod == "function_pod": + return rf"Join: the {REFUSAL}.*in the inputs of the function pod of '_identity'" + return rf"{pod}: the {REFUSAL}" @pytest.mark.parametrize("repeat", sorted(REPEATS)) @@ -358,13 +361,9 @@ def test_a_repeated_operand_is_refused_where_the_identity_is_formed( naming the operator or function and the stream.""" first, second = REPEATS[repeat](INPUTS[inputs]) assert first.content_hash() == second.content_hash() - # With data columns besides the data-tags, the operator's own check refuses the - # overlapping columns first, when the step is built (as before ITL-1419). - refusal = ( - rf"{_who(pod)}.*{REFUSAL}" - if inputs == "data_tags_only" or pod == "function_pod" - else "overlapping" - ) + # With data columns besides the data-tags, the operator's own check (a function + # pod's join's) refuses the overlapping columns first, when the step is built. + refusal = _refusal(pod) if inputs == "data_tags_only" else "overlapping" with pytest.raises(InputValidationError, match=refusal): COMMUTATIVE[pod](first, second).content_hash() @@ -395,7 +394,7 @@ def test_a_repeated_operand_is_refused_when_recorded_in_either_order( with job: if not repeated_first: COMMUTATIVE[pod](first, label="once") - with pytest.raises(InputValidationError, match=rf"{_who(pod)}.*{REFUSAL}"): + with pytest.raises(InputValidationError, match=_refusal(pod)): COMMUTATIVE[pod](first, second, label="twice") if repeated_first: COMMUTATIVE[pod](first, label="once") @@ -544,3 +543,57 @@ def test_the_saved_edge_list_is_the_one_main_wrote( saved = json.loads((tmp_path / "pipeline.json").read_text()) main_edges = sorted(pipeline._hash_graph.edges()) # pyright: ignore[reportPrivateUsage] assert saved["edges"] == [list(edge) for edge in main_edges] + + +def test_a_function_pod_over_two_inputs_computes_rows_without_an_identity() -> None: + """Verification of 79e86762 (P2): a function pod forms its operand set only where + its identity is formed. Its rows over two distinct inputs, one a raw stream with an + unused map column, are computed as before; asking its identity raises the existing + hashing error, as hashing that raw stream does.""" + raw = _raw_with_map([1, 2]) + other = _data_tags_only() + out = _identity.pod(raw, other) + assert out.as_table().num_rows == 3 + with pytest.raises(ValueError) as own: + raw.content_hash() + with pytest.raises(type(own.value)) as formed: + out.content_hash() + assert str(formed.value) == str(own.value) + + +def test_a_downstream_pod_keeps_the_name_of_the_pod_given_the_repeat() -> None: + """Verification of 79e86762 (P3): the refusal names the operator that got the + repeated operand; a pod downstream of it adds no name of its own in its place.""" + d, d2 = _data_tags_only(), _data_tags_only() + w = _data_tags_and_data() + downstream = { + "Join over Rejoin": ( + lambda: Join()(Rejoin()(d, d2), w.select_data_columns(["x"])), + "Rejoin", + "Join", + ), + "function pod over Rejoin": ( + lambda: _identity.pod(Rejoin()(d, d2)), + "Rejoin", + "Join", + ), + "Rejoin over Join": (lambda: Rejoin()(Join()(d, d2)), "Join", "Rejoin"), + } + for build, given, downstream_name in downstream.values(): + with pytest.raises(InputValidationError) as err: + build().content_hash() + message = str(err.value) + assert f"{given}: the same stream" in message + assert f"{downstream_name}: the same stream" not in message + + +def test_a_function_pod_given_one_stream_twice_names_the_function_and_its_join() -> ( + None +): + """The function pod's own inputs repeat: the message names the function as context + and keeps the name of the join that formed the set.""" + d, d2 = _data_tags_only(), _data_tags_only() + with pytest.raises(InputValidationError) as err: + _identity.pod(d, d2).content_hash() + assert "'_identity'" in str(err.value) + assert "Join: the same stream" in str(err.value) From 09351e1a503831e2e3895612943207e6c004837f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 06:51:57 -0800 Subject: [PATCH 06/11] fix(operators): a join's input check lets an upstream repeated-operand refusal through (ITL-1419) Verification of a59c55b7: Join.validate_nonzero_inputs wrapped every error in a plain InputValidationError, so a Join or a two-input function pod over a Rejoin given one stream twice lost the RepeatedOperandError type (and the function pod's caller context was bypassed). Join and SemiJoin now re-raise it as it is; MergeJoin already let InputValidationError through. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1419.md | 3 +- src/orcapod/core/operators/join.py | 6 ++++ src/orcapod/core/operators/semijoin.py | 7 +++- tests/test_pipeline/test_edge_positions.py | 40 ++++++++++++++++++++++ 4 files changed, 54 insertions(+), 2 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index f981d4005..7f72b2f56 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -5,7 +5,8 @@ separate streams such as two sources with one source id and schema) is refused with `RepeatedOperandError` (an `InputValidationError`), naming the operator that got the repeated operand (a pod downstream of it, and a function pod whose join got it, add - context and never replace the name) and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, + context and never replace the name, and a join whose input check meets it lets it + through with its type) and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, November 26, 2026). Such a pod forms its identity from its operands as a set, so `Join()(d)` and `Join()(d, d2)` had one identity, stored path and cache entry but different rows (a stream whose only data columns are data-tags, joined with itself, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 66dd66ddf..c52609bef 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -202,9 +202,15 @@ def kernel_id(self) -> tuple[str, ...]: def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None: """Validate that input streams are compatible for joining.""" + from orcapod.core.operators.repeated_operands import RepeatedOperandError + # TODO: add more helpful validation try: self.output_schema(*streams) + except RepeatedOperandError: + # An input's own refusal (one stream given twice upstream, ITL-1419) passes + # through as it is: its type and the pod that got the repeat. + raise except Exception as e: raise InputValidationError(f"Input streams are not compatible: {e}") from e diff --git a/src/orcapod/core/operators/semijoin.py b/src/orcapod/core/operators/semijoin.py index d2a379f50..5c330afc5 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -301,11 +301,16 @@ def validate_binary_inputs( SemiJoinIgnoredColumnWarning: Once per operator and set of names, when the inputs share a name that is not a tag on both sides (ITL-1088). """ + from orcapod.core.operators.repeated_operands import RepeatedOperandError + try: self._validated_common_keys: tuple[str, ...] = self._checked_match_keys( left_stream, right_stream ) - + except RepeatedOperandError: + # An input's own refusal (one stream given twice upstream, ITL-1419) passes + # through as it is: its type and the pod that got the repeat. + raise except Exception as e: raise InputValidationError( f"Input streams are not compatible for semi-join: {e}" diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index b986636f4..f8c582dff 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -597,3 +597,43 @@ def test_a_function_pod_given_one_stream_twice_names_the_function_and_its_join() _identity.pod(d, d2).content_hash() assert "'_identity'" in str(err.value) assert "Join: the same stream" in str(err.value) + + +OVER_REJOIN = { + "Join over Rejoin": lambda rejoined, w, **kw: Join()( + rejoined, w.select_data_columns(["x"]), **kw + ), + "two-input function pod over Rejoin": lambda rejoined, w, **kw: _identity.pod( + rejoined, w.select_data_columns(["x"]), **kw + ), + "SemiJoin over Rejoin": lambda rejoined, w, **kw: SemiJoin()(rejoined, w, **kw), +} + + +@pytest.mark.parametrize("in_job", [False, True], ids=["standalone", "in_job"]) +@pytest.mark.parametrize("case", sorted(OVER_REJOIN)) +def test_a_join_over_a_repeated_rejoin_raises_the_rejoin_refusal( + case: str, in_job: bool +) -> None: + """Verification of a59c55b7 (P3): a join whose input check meets the upstream + refusal lets it through as it is (its type and the pod that got the repeat), not + wrapped in a plain ``InputValidationError``; a function pod adds its context. The + ``Rejoin`` is built outside the job (inside, recording it is refused first, before + any step over it).""" + from orcapod.core.operators.repeated_operands import RepeatedOperandError + + d, d2, w = _data_tags_only(), _data_tags_only(), _data_tags_and_data() + rejoined = Rejoin()(d, d2) + with pytest.raises(RepeatedOperandError) as err: + if in_job: + job = PipelineJob(name="refused", database=InMemoryArrowDatabase()) + with job: + OVER_REJOIN[case](rejoined, w, label="after") + else: + OVER_REJOIN[case](rejoined, w).content_hash() + assert err.value.pod == "Rejoin" + message = str(err.value) + assert message.startswith(f"Rejoin: the {REFUSAL.split('.*')[0]}") + assert "Join: the same stream" not in message.replace("Rejoin: the same", "") + if case.startswith("two-input function pod"): + assert "in the inputs of the function pod of '_identity'" in message From 12dc5f06960c45966f64b17a4534a12e681d4f1a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Thu, 26 Nov 2026 07:22:58 -0800 Subject: [PATCH 07/11] test(pipeline): an ordered self-join over a stream with data-tags runs in a job (ITL-1419) CodeRabbit on PR 587 (review-body nitpick): MergeJoin(t, t) and SemiJoin(t, t) over a stream with two data-tags and two data columns, in two layouts, sync and async, give the standalone rows, Arrow schema, keys and data-tags. Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_edge_positions.py | 47 ++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index f8c582dff..f0badd408 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -637,3 +637,50 @@ def test_a_join_over_a_repeated_rejoin_raises_the_rejoin_refusal( assert "Join: the same stream" not in message.replace("Rejoin: the same", "") if case.startswith("two-input function pod"): assert "in the inputs of the function pod of '_identity'" in message + + +def _data_tag_source(layout: str) -> Any: + """Two data-tags (``id``, ``key``: tags that are also data columns) and two data + columns (``x``, ``y``), in two table layouts and tag orders.""" + columns = { + "id": pa.array([1, 1, 2], pa.int64()), + "key": pa.array(["p", "q", "p"], pa.large_string()), + "x": pa.array([1, 2, 3], pa.int64()), + "y": pa.array([10, 20, 30], pa.int64()), + } + if layout == "tags_id_key": + order, tags = ["id", "key", "x", "y"], ["id", "key"] + else: + order, tags = ["y", "key", "x", "id"], ["key", "id"] + table = pa.table({name: columns[name] for name in order}) + return sources.ArrowTableSource( + table, tag_columns=tags, tag_only_columns=False, source_id="t" + ) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("layout", LAYOUTS) +@pytest.mark.parametrize("operator", sorted(OPERATORS)) +def test_one_data_tag_stream_twice_runs_in_a_job_with_the_standalone_schema( + operator: str, layout: str, mode: str +) -> None: + """CodeRabbit on PR 587: the ordered self-join over a stream with data-tags runs in a + job, sync and async, with the standalone rows, Arrow schema and column roles: the + two positions keep each column's role (tag, data-tag, data) and type.""" + from orcapod.core.data_tags import stream_data_tags + + t = _data_tag_source(layout) + standalone = OPERATORS[operator]()(t, t) + expected = standalone.as_table(all_info=True) + job = PipelineJob(name="data_tags", database=InMemoryArrowDatabase()) + with job: + OPERATORS[operator]()(t, t, label="step") + _run(job, mode) + table = job.step.as_table(all_info=True) + assert _rows(table) == _rows(expected) + assert {f.name: f.type for f in table.schema} == { + f.name: f.type for f in expected.schema + } + assert job.step.keys() == standalone.keys() + assert stream_data_tags(job.step) == stream_data_tags(standalone) + assert stream_data_tags(standalone) # the data-tags are kept, in both roles From f526dd454a5e690473395ff9969b1f90001d64ef Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 00:40:46 -0800 Subject: [PATCH 08/11] docs(operators): word the repeated-operand refusal as a stopgap until ITL-1511 (ITL-1419) Wording only: the error message, docstrings, the changelog fragment and the plan say that a commutative pod taking one stream more than once is not supported yet and name ITL-1511. No behaviour or hash change. Co-Authored-By: Claude Fable 5.2 --- changelog.d/ITL-1419.md | 14 +++--- docs/dev/plans/itl-1419-edge-positions.md | 11 +++-- src/orcapod/core/function_pod.py | 5 +- src/orcapod/core/operators/base.py | 3 +- src/orcapod/core/operators/join.py | 3 +- src/orcapod/core/operators/rejoin.py | 7 +-- .../core/operators/repeated_operands.py | 47 ++++++++++--------- tests/test_pipeline/test_edge_positions.py | 5 +- 8 files changed, 56 insertions(+), 39 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 7f72b2f56..a21cb6e60 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -2,12 +2,14 @@ - A commutative operator (`Join`, `Rejoin`, a commutative binary operator) or a function pod given one stream more than once (two operands of one identity: one object, or two - separate streams such as two sources with one source id and schema) is refused with + separate streams such as two sources with one source id and schema) is not supported + yet: for now it is refused with `RepeatedOperandError` (an `InputValidationError`), naming the operator that got the repeated operand (a pod downstream of it, and a function pod whose join got it, add context and never replace the name, and a join whose input check meets it lets it - through with its type) and the stream, and pointing to `MergeJoin` (ITL-1419; decided on the developer's behalf, - November 26, 2026). Such a pod forms its identity from its operands as a set, so + through with its type) and the stream, and pointing to `MergeJoin` (ITL-1419; developer, November 27, 2026: a stopgap until ITL-1511). + The refusal is temporary: a commutative operator taking one stream more than once is + meaningful, and ITL-1511 is to allow it before 0.4.0. Today such a pod forms its identity from its operands as a set, so `Join()(d)` and `Join()(d, d2)` had one identity, stored path and cache entry but different rows (a stream whose only data columns are data-tags, joined with itself, repeated every row whose key repeats; in a job, which rows were kept, or whether a later @@ -17,10 +19,10 @@ computed without forming the identity (standalone `Join()(d, d).as_table()`, or a function pod's rows over several inputs) are computed as before. An operand whose identity cannot be computed (a raw stream holding a value that cannot be - hashed) raises what hashing it raises; the rule adds no error of its own. Inputs that + hashed) raises what hashing it raises; the refusal adds no error of its own. Inputs that share a data column are still refused first, when the step is built (overlapping data - columns). To join a stream with itself, use `MergeJoin()(d, d)`, whose inputs are - ordered. + columns). Until ITL-1511, to join a stream with itself, use `MergeJoin()(d, d)`, whose + inputs are ordered. ### Fixed diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index 7b4ee87dd..55316c663 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -16,7 +16,12 @@ with one predecessor: the sync orchestrator hands the operator one stream ("Bina requires exactly two input streams"), the async one one reader. Pinned by `tests/test_pipeline/test_loaded_argument_order.py::test_one_stream_given_twice_fails_to_run_in_a_job`. -## One stream given twice to a commutative pod: refused +## One stream given twice to a commutative pod: refused for now (a stopgap until ITL-1511) + +The refusal below is temporary, not a principle. A commutative operator taking one stream +more than once is meaningful, and ITL-1511 ("Allow a commutative operator to take one stream +more than once: multiset identity and the unique/repeat toggle") is to allow it; it must be +settled before 0.4.0. Independent review of the first head found that a commutative operator hashes its operands as a set, so `Join()(d)` and `Join()(d, d)` (where `d` has no data column besides its @@ -27,7 +32,7 @@ missed two separate sources of one identity (standalone hashes still collided, a recorded over them compiled in one order and failed in the other), and that the check added its own error for an operand that cannot be hashed. -Decided on the developer's behalf (2026-11-26): refuse exactly where the identity is formed +Developer, November 27, 2026: a stopgap until ITL-1511. Until then, refuse exactly where the identity is formed from the operands as a set. `core/operators/repeated_operands.operand_set` builds that set and raises `RepeatedOperandError` (an `InputValidationError`) when two operands have one identity (they are equal as the set compares them). `Join.argument_symmetry` (so also @@ -98,7 +103,7 @@ New file `tests/test_pipeline/test_edge_positions.py`, inputs with two tag and t another at 1 and the reverse, give the standalone rows. - A source node's observer events are the same for `MergeJoin(A, A)` as for `MergeJoin(A, B)` per source (one start and end per run). -- `Join`, `Rejoin` and a function pod given one stream twice are refused, standalone and +- `Join`, `Rejoin` and a function pod given one stream twice are refused (for now: ITL-1511), standalone and at recording, in both recording orders, sync and async; `Join(a)` has position `None`. - The saved file of a job with `MergeJoin(A, A)` has one edge pair and `inputs` `[A, A]`; saving a loaded job writes the same bytes. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index 6e1d4485a..babc8fafc 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -879,8 +879,9 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou """The symmetry of the join the pod puts its inputs through. Raises: - RepeatedOperandError: If two inputs have one identity (ITL-1419): the join - that formed the set is named, and this function added as context. + RepeatedOperandError: If two inputs have one identity (ITL-1419; not + supported yet, a stopgap until ITL-1511): the join that formed the set + is named, and this function added as context. """ from orcapod.core.operators.repeated_operands import RepeatedOperandError diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index 3426201d7..a87478e77 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -309,7 +309,8 @@ def validate_inputs(self, *streams: StreamProtocol) -> None: def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: if self.is_commutative(): - # return as symmetric group, refusing one stream twice (ITL-1419) + # return as symmetric group, refusing one stream twice for now + # (ITL-1419; a stopgap until ITL-1511) from orcapod.core.operators.repeated_operands import ( RepeatedOperandError, operand_set, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index c52609bef..f177decc1 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -225,7 +225,8 @@ def argument_symmetry(self, streams: Collection) -> ArgumentGroup: Raises: RepeatedOperandError: If two inputs have one identity (ITL-1419): a set - cannot tell ``Join(d)`` from ``Join(d, d)``. + cannot tell ``Join(d)`` from ``Join(d, d)``. Not supported yet, a + stopgap until ITL-1511. """ from orcapod.core.operators.repeated_operands import ( RepeatedOperandError, diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index fbf32d487..4ad21ff88 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -278,9 +278,10 @@ class Rejoin(Join): and renaming, ``AddTags``, function pods) and no ``Join``, ``GroupBy`` or ``Batch``. Data columns must be disjoint, as in ``Join``, and a data-tag in several inputs is one column. These refusals are read from the inputs' columns, none from their rows. - As for ``Join``, the inputs form a set, so one stream given twice (two inputs of one - identity) is refused when the identity is formed, by hashing the result or recording - the step (``RepeatedOperandError``, ITL-1419): give each branch once. + As for ``Join``, the inputs form a set today, so one stream given twice (two inputs of + one identity) is not supported yet: it is refused when the identity is formed, by + hashing the result or recording the step (``RepeatedOperandError``, ITL-1419; a + stopgap until ITL-1511). For now give each branch once. 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 diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index 9368f208e..4eb8a3330 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -1,17 +1,19 @@ -"""A commutative pod is never given one stream twice (ITL-1419). - -A pod whose identity is formed from its operands as a set (``Join``, ``Rejoin``, a -commutative binary operator, a function pod, which joins its inputs) would give -``Join()(d)`` and ``Join()(d, d2)`` one identity, one stored path and one cache entry, -when ``d2`` is ``d`` or a separate stream of ``d``'s identity, yet different rows (a stream -joined with itself repeats every row whose key repeats). So the set is formed in one -place, ``operand_set``, which refuses two operands of one identity, the hash the set is -built from (decided on the developer's behalf, November 26, 2026). Whatever forms the -identity meets the refusal: hashing a stream standalone, recording a step in a pipeline, -compiling it. An ordered operator (``MergeJoin``, ``SemiJoin``) takes one stream twice: -its positions are part of its identity. - -The rule adds no error of its own for an operand whose identity cannot be computed (a raw +"""A commutative pod does not take one stream twice yet (ITL-1419; a stopgap until ITL-1511). + +Giving a commutative operator one stream more than once is meaningful, and ITL-1511 is to +allow it (a multiset identity and the unique/repeat toggle). It is refused for now because +of how the identity is formed today: a pod whose identity is formed from its operands as a +set (``Join``, ``Rejoin``, a commutative binary operator, a function pod, which joins its +inputs) would give ``Join()(d)`` and ``Join()(d, d2)`` one identity, one stored path and +one cache entry, when ``d2`` is ``d`` or a separate stream of ``d``'s identity, yet +different rows (a stream joined with itself repeats every row whose key repeats). So the +set is formed in one place, ``operand_set``, which for now refuses two operands of one +identity, the hash the set is built from (developer, November 27, 2026: a stopgap until +ITL-1511). Whatever forms the identity meets the refusal: hashing a stream standalone, +recording a step in a pipeline, compiling it. An ordered operator (``MergeJoin``, +``SemiJoin``) takes one stream twice: its positions are part of its identity. + +The refusal adds no error of its own for an operand whose identity cannot be computed (a raw stream holding a value that cannot be hashed): it raises what hashing that stream raises. """ @@ -24,9 +26,10 @@ class RepeatedOperandError(InputValidationError): - """Two operands of a commutative pod have one identity. + """Two operands of a commutative pod have one identity, which is not supported yet. - The message names the pod that got the repeated operand, set once by the pod whose + A stopgap: ITL-1511 is to allow a commutative operator to take one stream more than + once. The message names the pod that got the repeated operand, set once by the pod whose own operands repeat (``named``) and never replaced. A pod further down, or a function pod whose join got the operands, can only add context (``add_context``): what the repeated operand is part of. @@ -78,7 +81,7 @@ def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol Raises: RepeatedOperandError: If two operands have one identity (they are equal, as a - set compares them), one object or two, unnamed: the caller names its pod + set compares them), one object or two (not supported yet: ITL-1511), unnamed: the caller names its pod (``err.named(...)``). An error met while hashing an operand (raised by a pod upstream) is already named and passes through. """ @@ -92,10 +95,12 @@ def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol else f"{first.label!r} and {stream.label!r}" ) raise RepeatedOperandError( - f"the same stream ({names}, one identity) is given more than once. Its " - "inputs form a set, so a repeated input would change the rows but not " - "the identity. Give each stream once; to join a stream with itself, use " - "MergeJoin, whose inputs are ordered: MergeJoin()(stream, stream)." + f"the same stream ({names}, one identity) is given more than once, " + "which is not supported yet (ITL-1511 is to allow it). Today its inputs " + "form a set, so a repeated input would change the rows but not the " + "identity. For now give each stream once; to join a stream with itself " + "in argument order, use MergeJoin, whose inputs are ordered: " + "MergeJoin()(stream, stream)." ) seen[stream] = stream return frozenset(seen) diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index f0badd408..6640d5ff8 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -3,7 +3,8 @@ An edge is ``(upstream, node, position)``: one upstream given to two inputs of an ordered operator is two edges, so ``MergeJoin()(a, a)`` and ``SemiJoin()(a, a)`` run in a job as they run standalone. ``Join``, ``Rejoin`` and a function pod given one stream twice are -refused by the operator (or the pod's join) itself, standalone and in a job. +refused by the operator (or the pod's join) itself, standalone and in a job, for now (a +stopgap until ITL-1511). Inputs have two tag columns (``id``, ``key``) and two data columns (``x``, ``y``), in two layouts (tag order and column order swapped). @@ -337,7 +338,7 @@ def _identity(id: int | None) -> int | None: "same_object": lambda make: (lambda s: (s, s))(make()), "equal_sources": lambda make: (make(), make()), } -REFUSAL = r"same stream.*more than once.*MergeJoin" +REFUSAL = r"same stream.*more than once.*not supported yet.*ITL-1511.*MergeJoin" def _refusal(pod: str) -> str: From 2619c82f316eb6809412f77d79aad5b74361cf9a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 11:43:57 -0800 Subject: [PATCH 09/11] docs(pipeline): record the repeated-input stopgap and edge limits (ITL-1419) --- changelog.d/ITL-1419.md | 58 ++++++++----------- docs/concepts/operators.md | 10 ++++ docs/concepts/pipeline-job.md | 9 +++ docs/dev/plans/itl-1419-edge-positions.md | 39 +++++++------ .../core/operators/repeated_operands.py | 12 ++-- src/orcapod/pipeline/base.py | 4 +- 6 files changed, 72 insertions(+), 60 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index a21cb6e60..4cea731b0 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -1,46 +1,38 @@ ### Breaking changes and migration - A commutative operator (`Join`, `Rejoin`, a commutative binary operator) or a function - pod given one stream more than once (two operands of one identity: one object, or two - separate streams such as two sources with one source id and schema) is not supported - yet: for now it is refused with - `RepeatedOperandError` (an `InputValidationError`), naming the operator that got the - repeated operand (a pod downstream of it, and a function pod whose join got it, add - context and never replace the name, and a join whose input check meets it lets it - through with its type) and the stream, and pointing to `MergeJoin` (ITL-1419; developer, November 27, 2026: a stopgap until ITL-1511). - The refusal is temporary: a commutative operator taking one stream more than once is - meaningful, and ITL-1511 is to allow it before 0.4.0. Today such a pod forms its identity from its operands as a set, so - `Join()(d)` and `Join()(d, d2)` had one identity, stored path and cache entry but - different rows (a stream whose only data columns are data-tags, joined with itself, - repeated every row whose key repeats; in a job, which rows were kept, or whether a later - step compiled at all, depended on the order the steps were recorded in). The refusal is - where that set is formed, the operator's `argument_symmetry`, so it is met wherever the - identity is: hashing the result, recording the step in a pipeline, compiling it. Rows - computed without forming the identity (standalone `Join()(d, d).as_table()`, or a - function pod's rows over several inputs) are computed as before. An - operand whose identity cannot be computed (a raw stream holding a value that cannot be - hashed) raises what hashing it raises; the refusal adds no error of its own. Inputs that - share a data column are still refused first, when the step is built (overlapping data - columns). Until ITL-1511, to join a stream with itself, use `MergeJoin()(d, d)`, whose - inputs are ordered. + pod raises `RepeatedOperandError` (an `InputValidationError`) when it forms its identity + from an operand set with two inputs of the same identity. This includes two separately + built sources with the same source ID and schema. The developer approved the refusal + on 2026-11-27 as a stopgap until ITL-1511 allows repeats with a unique/repeat toggle. + Previously `Join()(d)` and `Join()(d, d2)` could share a content hash and cache entry + despite yielding different rows when `d2` shared `d`'s identity. The error names the + pod that received the repeated inputs and points to the ordered `MergeJoin()(d, d)` + for self-joins. An operand whose identity cannot be computed raises its existing + hashing error. Overlapping data columns still raise an error when the step is built. ### Fixed - A job runs an ordered operator given one stream for both inputs, `MergeJoin()(a, a)` and `SemiJoin()(a, a)` (ITL-1419, stage 1 of ITL-1472). A pipeline's graph edges now - carry their input position, `(upstream, node, position)`: the argument index for an - ordered operator, none for a commutative one (also with one input), 0 for a function or - side-effect pod. Both orchestrators give a node one input per edge, so the operator gets - its two inputs, sync and async, in a job made from a `Pipeline` or a `PipelineJob`, after - `PipelineJob.load` and through `node.run()`; before, the run raised "BinaryOperator - requires exactly two input streams". No hash, stored path, stored column or saved file - changes: a saved file still lists each `(upstream, node)` pair once, and the positions - are rebuilt from an operator's saved `inputs` list. + carry their input position, `(upstream, node, position)`. The position is the argument + index for an ordered operator, `None` for a commutative one (also with one input), and + 0 for a function or side-effect pod. Both orchestrators give a node one input per + edge, so both inputs reach the operator when it runs in a job made from a `Pipeline` + or a `PipelineJob`, after `PipelineJob.load` and through `node.run()`. Positions + exist in memory. A saved file still lists each `(upstream, node)` pair once, and the + loader reconstructs positions from the operator's saved `inputs` list. When ITL-1511 + allows repeats, identical edges will get occurrence numbers so each edge can be + identified individually. ### Known limitations -- `diagram()` draws one line for the two inputs of `MergeJoin()(a, a)`: drawing one line - per positioned edge is left to stage 2 of ITL-1472. +- Standalone row computation such as `Join()(d, d).as_table()` or a function pod's row + read over several inputs can skip identity formation and proceed. The same invocation + in a job raises `RepeatedOperandError`. The developer accepted this discrepancy as + part of the stopgap. ITL-1511 will remove it. +- `diagram()` draws one line for the two inputs of `MergeJoin()(a, a)`. ITL-1530 tracks + drawing both lines. - An operator a loaded file keeps read-only (its config cannot be rebuilt) has its inputs - positioned by argument index, also when it is commutative; such a node never runs. + positioned by argument index, also when it is commutative. Such a node never runs. Saved positions are stage 2 of ITL-1472. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 013370f38..343b6374a 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -103,6 +103,16 @@ order, so `Join()(a, b)` and `Join()(b, a)` have the same columns in the same or ordered operators such as `SemiJoin` and `MergeJoin` keep operand order; either way, address columns by name rather than by position. +A commutative operator such as `Join` or `Rejoin`, or a function pod, raises +`RepeatedOperandError` when it forms its identity from an operand set containing the same +stream twice. Two separately built sources with the same source ID and schema count as one +identity. Use the ordered `MergeJoin()(d, d)` for a self-join in a job. + +The developer approved this stopgap on 2026-11-27. A standalone row read such as +`Join()(d, d).as_table()` or a function pod's row read over several inputs can proceed when +it skips identity formation. The same invocation is refused in a job. ITL-1511 will allow +repeated operands with a unique/repeat toggle and remove this discrepancy. + ```python from orcapod.sources import DictSource from orcapod.operators import Join diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 41a19df1b..db140f479 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -380,6 +380,15 @@ Every job also carries its blueprint as `job.pipeline`. ## Seeing the graph +In memory, a job keeps one edge per input. Ordered operators use argument indices, so +`MergeJoin()(a, a)` runs with two edges, at positions 0 and 1. Commutative operators use +`None` for the position, even with one input. ITL-1511 will give identical edges occurrence +numbers when repeated operands are allowed, so each edge can be identified individually. +Saved pipelines reconstruct positions from the saved input lists. + +`diagram()` currently draws one line for the two inputs of `MergeJoin()(a, a)`. ITL-1530 +tracks drawing both lines. + !!! caution "In development" `Pipeline.diagram()`, `PipelineJob.diagram()`, `PipelineDiagram` and its methods and arguments, the look of the picture and the notebook display may change in any release diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index 55316c663..5f7ff7d28 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -32,29 +32,30 @@ missed two separate sources of one identity (standalone hashes still collided, a recorded over them compiled in one order and failed in the other), and that the check added its own error for an operand that cannot be hashed. -Developer, November 27, 2026: a stopgap until ITL-1511. Until then, refuse exactly where the identity is formed -from the operands as a set. `core/operators/repeated_operands.operand_set` builds that set +On 2026-11-27 the developer approved refusing repeated operands as a stopgap until +ITL-1511. The refusal occurs when the pod forms its identity from its operands as a set. +`core/operators/repeated_operands.operand_set` builds that set and raises `RepeatedOperandError` (an `InputValidationError`) when two operands have one -identity (they are equal as the set compares them). `Join.argument_symmetry` (so also +identity (they are equal as the set compares them). This includes two separately built +sources with the same source ID and schema. `Join.argument_symmetry` (so also `Rejoin`), the commutative branch of `BinaryOperator.argument_symmetry` and the function pod's `argument_symmetry` call it. The error names the operator whose own operands repeat (`RepeatedOperandError.named`, set once); a pod downstream, and a function pod whose join got the operands, add context (`add_context`) and never replace that name (verification -of the third head). Whatever forms the identity meets the refusal: hashing, recording, -compiling; a function pod never forms it on the row path. No separate check remains. An operand whose identity cannot be -computed raises what hashing it raises. Rows computed without forming the identity -(standalone `as_table()`) are computed as before. - -A commutative operator's inputs have no position also when it has one input (`Join()(a)`): -only a function or side-effect pod gets position 0 for its one input. +of the third head). Hashing, recording and compiling form the identity. An operand whose +identity cannot be computed raises its existing hashing error. Standalone row reads such as +`Join()(d, d).as_table()` or a function pod's row read over several inputs can proceed +when they skip identity formation. A job refuses the same invocation. The developer +accepted this discrepancy as part of the stopgap, and ITL-1511 will remove it. ## Change 1. **One rule for positions** (new `src/orcapod/pipeline/edges.py`): `input_positions(pod, inputs)` gives each input of an operator its argument index when the operator's `argument_symmetry` is a tuple (`MergeJoin`, `SemiJoin`: 0 and 1) and `None` when it is a - `frozenset` (`Join`, `Rejoin`, with any number of inputs); a function or side-effect pod's - one input is at 0. Used by + `frozenset` (`Join`, `Rejoin`, even with one input). A function or side-effect pod's + one input is at 0. Positions exist in memory. When ITL-1511 allows repeats, each + identical edge will get an occurrence number so it can be identified individually. Used by `_record_invocation`, `compile`, the `PipelineJob` rebuild of a blueprint and the loader. 2. **Hash-level edges are triples.** `_graph_edges` becomes a sorted list of `(upstream key, node key, position)`. `_hash_graph` (networkx, used for topological order and @@ -76,13 +77,12 @@ only a function or side-effect pod gets position 0 for its one input. events are unchanged. 6. **Held rows** (`node.run()`, the state rule) feed every position alike: the sync orchestrator reads `outputs[upstream]` per edge, the async one sends the held rows to every edge reader. -7. **Diagram: left to stage 2.** The diagram keys its edges by node pair and role - (`(start, end, constrains)`) and routes them in the layout code, so two lines for - `MergeJoin(A, A)` need parallel-edge routing there, not a change in the edge listing - (coordinator, 2026-11-26: leave it to stage 2 if it reaches layout code). +7. **Diagram.** `diagram()` draws one line for both inputs of `MergeJoin(A, A)` because + the diagram keys its edges by node pair and role (`(start, end, constrains)`). + ITL-1530 tracks routing parallel edges in the layout. `SemiJoin(A, A)` already draws two lines (plain and constraining, ITL-1455). -Not in this stage: any public name (`job.edges`), any restriction, any change to a refusal, and +Not in this stage: any public name (`job.edges`), any restriction, and nothing in the id code of `core/nodes/function_node.py` / `operator_node.py` (ITL-1466). ## Hashes @@ -103,8 +103,9 @@ New file `tests/test_pipeline/test_edge_positions.py`, inputs with two tag and t another at 1 and the reverse, give the standalone rows. - A source node's observer events are the same for `MergeJoin(A, A)` as for `MergeJoin(A, B)` per source (one start and end per run). -- `Join`, `Rejoin` and a function pod given one stream twice are refused (for now: ITL-1511), standalone and - at recording, in both recording orders, sync and async; `Join(a)` has position `None`. +- Exercise `RepeatedOperandError` when hashing and recording `Join`, `Rejoin` and function + pods with repeated operands (ITL-1511), including both recording orders and sync and + async jobs. - The saved file of a job with `MergeJoin(A, A)` has one edge pair and `inputs` `[A, A]`; saving a loaded job writes the same bytes. - `test_one_stream_given_twice_fails_to_run_in_a_job` becomes the test that it runs. diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index 4eb8a3330..f52e8762c 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -26,13 +26,13 @@ class RepeatedOperandError(InputValidationError): - """Two operands of a commutative pod have one identity, which is not supported yet. + """The operand set for a pod's identity contains two inputs with one identity. - A stopgap: ITL-1511 is to allow a commutative operator to take one stream more than - once. The message names the pod that got the repeated operand, set once by the pod whose - own operands repeat (``named``) and never replaced. A pod further down, or a function - pod whose join got the operands, can only add context (``add_context``): what the - repeated operand is part of. + The developer approved this stopgap on 2026-11-27 until ITL-1511 adds a unique/repeat + toggle. A job forms the identity and raises this error, while a standalone row read + can skip identity formation. The message names the pod whose own operands repeat + (``named``). A downstream pod or a function pod whose join got the repeated inputs + can attach context with ``add_context``. Args: reason: What is repeated and what to do instead. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 213f275e4..d3e3eec36 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -344,8 +344,8 @@ def _record_invocation(self, invocation: PodInvocation) -> None: read one source under two restrictions (ITL-1218), whatever streams lead there. Nothing is recorded then. InputValidationError: If the pod is commutative and two of its inputs have - one identity: forming the invocation's identity refuses it - (``repeated_operands.operand_set``, ITL-1419). Nothing is recorded then. + one identity. Forming the invocation's identity raises + ``RepeatedOperandError`` as a stopgap until ITL-1511. """ from orcapod.pipeline.restrictions import require_one_restriction From 479b80f6d7e741a922af75901ffa511d56f69c4b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:08:59 -0800 Subject: [PATCH 10/11] fix(pipeline): validate operator argument symmetry centrally (ITL-1419) --- changelog.d/ITL-1419.md | 14 +- docs/dev/plans/itl-1419-edge-positions.md | 27 ++-- src/orcapod/core/function_pod.py | 7 +- src/orcapod/core/nodes/operator_node.py | 7 +- src/orcapod/core/operators/base.py | 17 +-- src/orcapod/core/operators/join.py | 19 +-- .../core/operators/repeated_operands.py | 130 +++++++++--------- .../core/operators/static_output_pod.py | 8 +- src/orcapod/core/streams/base.py | 7 +- src/orcapod/pipeline/edges.py | 28 ++-- src/orcapod/pipeline/pod_invocation.py | 4 +- src/orcapod/pipeline/serialization.py | 11 +- tests/test_pipeline/test_edge_positions.py | 85 ++++++++++-- .../test_loaded_argument_order.py | 17 +++ 14 files changed, 228 insertions(+), 153 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 4cea731b0..429d515aa 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -1,15 +1,16 @@ ### Breaking changes and migration -- A commutative operator (`Join`, `Rejoin`, a commutative binary operator) or a function - pod raises `RepeatedOperandError` (an `InputValidationError`) when it forms its identity - from an operand set with two inputs of the same identity. This includes two separately - built sources with the same source ID and schema. The developer approved the refusal +- Reading argument symmetry raises `RepeatedOperandError` (an `InputValidationError`) + when an unordered group collapses repeated inputs. This applies to built-in and + custom operators, including `Rejoin` and the join used by a function pod. Two inputs + with the same identity count as repeats. The developer approved the refusal on 2026-11-27 as a stopgap until ITL-1511 allows repeats with a unique/repeat toggle. Previously `Join()(d)` and `Join()(d, d2)` could share a content hash and cache entry despite yielding different rows when `d2` shared `d`'s identity. The error names the pod that received the repeated inputs and points to the ordered `MergeJoin()(d, d)` for self-joins. An operand whose identity cannot be computed raises its existing - hashing error. Overlapping data columns still raise an error when the step is built. + hashing error in either argument order, even when another input repeats. Overlapping + data columns still raise an error when the step is built. ### Fixed @@ -17,7 +18,8 @@ and `SemiJoin()(a, a)` (ITL-1419, stage 1 of ITL-1472). A pipeline's graph edges now carry their input position, `(upstream, node, position)`. The position is the argument index for an ordered operator, `None` for a commutative one (also with one input), and - 0 for a function or side-effect pod. Both orchestrators give a node one input per + 0 for a function or side-effect pod. An operator using a nested ordered group also + keeps its argument indices. Both orchestrators give a node one input per edge, so both inputs reach the operator when it runs in a job made from a `Pipeline` or a `PipelineJob`, after `PipelineJob.load` and through `node.run()`. Positions exist in memory. A saved file still lists each `(upstream, node)` pair once, and the diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index 5f7ff7d28..a292e1066 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -33,17 +33,14 @@ recorded over them compiled in one order and failed in the other), and that the added its own error for an operand that cannot be hashed. On 2026-11-27 the developer approved refusing repeated operands as a stopgap until -ITL-1511. The refusal occurs when the pod forms its identity from its operands as a set. -`core/operators/repeated_operands.operand_set` builds that set -and raises `RepeatedOperandError` (an `InputValidationError`) when two operands have one -identity (they are equal as the set compares them). This includes two separately built -sources with the same source ID and schema. `Join.argument_symmetry` (so also -`Rejoin`), the commutative branch of `BinaryOperator.argument_symmetry` and the function -pod's `argument_symmetry` call it. The error names the operator whose own operands repeat -(`RepeatedOperandError.named`, set once); a pod downstream, and a function pod whose join -got the operands, add context (`add_context`) and never replace that name (verification -of the third head). Hashing, recording and compiling form the identity. An operand whose -identity cannot be computed raises its existing hashing error. Standalone row reads such as +ITL-1511. `core/operators/repeated_operands.read_argument_symmetry` reads the operator's +grouping and raises `RepeatedOperandError` (an `InputValidationError`) if an unordered +group has collapsed repeated operands. The check applies to built-in and custom +operators because it reads their result. The error names the operator whose own +operands repeat. A downstream pod or the function pod whose join received the operands +can add context with `add_context`. Hashing, recording and compiling form the identity. +Set formation completes before checking for collapsed operands, so the existing hashing +error for an unhashable operand wins in either argument order. Standalone row reads such as `Join()(d, d).as_table()` or a function pod's row read over several inputs can proceed when they skip identity formation. A job refuses the same invocation. The developer accepted this discrepancy as part of the stopgap, and ITL-1511 will remove it. @@ -51,9 +48,11 @@ accepted this discrepancy as part of the stopgap, and ITL-1511 will remove it. ## Change 1. **One rule for positions** (new `src/orcapod/pipeline/edges.py`): `input_positions(pod, - inputs)` gives each input of an operator its argument index when the operator's - `argument_symmetry` is a tuple (`MergeJoin`, `SemiJoin`: 0 and 1) and `None` when it is a - `frozenset` (`Join`, `Rejoin`, even with one input). A function or side-effect pod's + inputs)` gives each input of an operator its argument index for ordered groups + (`MergeJoin`, `SemiJoin`: 0 and 1), including nested ordered groups. A flat + `frozenset` of the inputs gives each position `None` (`Join`, `Rejoin`, even with + one input). This is the same distinction used by the legacy loader. Changes to how + operators declare symmetry are tracked separately in ITL-1548. A function or side-effect pod's one input is at 0. Positions exist in memory. When ITL-1511 allows repeats, each identical edge will get an occurrence number so it can be identified individually. Used by `_record_invocation`, `compile`, the `PipelineJob` rebuild of a blueprint and the loader. diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py index babc8fafc..a7fa68dcb 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -883,10 +883,13 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou supported yet, a stopgap until ITL-1511): the join that formed the set is named, and this function added as context. """ - from orcapod.core.operators.repeated_operands import RepeatedOperandError + from orcapod.core.operators.repeated_operands import ( + RepeatedOperandError, + read_argument_symmetry, + ) try: - return self.multi_stream_handler().argument_symmetry(streams) + return read_argument_symmetry(self.multi_stream_handler(), streams) except RepeatedOperandError as err: err.add_context( f"the inputs of the function pod of {self.canonical_function_name!r}" diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index b2134184a..af49757a7 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -262,7 +262,12 @@ def identity_structure(self) -> Any: return self.pipeline_identity_structure() def pipeline_identity_structure(self) -> Any: - return (self._operator, self._operator.argument_symmetry(self._input_streams)) + from orcapod.core.operators.repeated_operands import read_argument_symmetry + + return ( + self._operator, + read_argument_symmetry(self._operator, self._input_streams), + ) # ------------------------------------------------------------------ # Read-only overrides (for deserialized nodes without live operator) diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index a87478e77..fca54e396 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -309,21 +309,8 @@ def validate_inputs(self, *streams: StreamProtocol) -> None: def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: if self.is_commutative(): - # return as symmetric group, refusing one stream twice for now - # (ITL-1419; a stopgap until ITL-1511) - from orcapod.core.operators.repeated_operands import ( - RepeatedOperandError, - operand_set, - ) - - try: - return operand_set(streams) - except RepeatedOperandError as err: - # Named here only when this operator's own operands repeat. - raise err.named(type(self).__name__) from None - else: - # return as ordered group - return tuple(streams) + return frozenset(streams) + return tuple(streams) async def async_execute( self, diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index f177decc1..40e43cb0a 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -221,23 +221,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: - """The inputs as a set: ``Join`` is commutative. - - Raises: - RepeatedOperandError: If two inputs have one identity (ITL-1419): a set - cannot tell ``Join(d)`` from ``Join(d, d)``. Not supported yet, a - stopgap until ITL-1511. - """ - from orcapod.core.operators.repeated_operands import ( - RepeatedOperandError, - operand_set, - ) - - try: - return operand_set(streams) - except RepeatedOperandError as err: - # Named here only when this join's own operands repeat (ITL-1419). - raise err.named(type(self).__name__) from None + """The inputs as a set because ``Join`` is commutative.""" + return frozenset(streams) def output_schema( self, diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index f52e8762c..446e1641e 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -1,106 +1,108 @@ -"""A commutative pod does not take one stream twice yet (ITL-1419; a stopgap until ITL-1511). - -Giving a commutative operator one stream more than once is meaningful, and ITL-1511 is to -allow it (a multiset identity and the unique/repeat toggle). It is refused for now because -of how the identity is formed today: a pod whose identity is formed from its operands as a -set (``Join``, ``Rejoin``, a commutative binary operator, a function pod, which joins its -inputs) would give ``Join()(d)`` and ``Join()(d, d2)`` one identity, one stored path and -one cache entry, when ``d2`` is ``d`` or a separate stream of ``d``'s identity, yet -different rows (a stream joined with itself repeats every row whose key repeats). So the -set is formed in one place, ``operand_set``, which for now refuses two operands of one -identity, the hash the set is built from (developer, November 27, 2026: a stopgap until -ITL-1511). Whatever forms the identity meets the refusal: hashing a stream standalone, -recording a step in a pipeline, compiling it. An ordered operator (``MergeJoin``, -``SemiJoin``) takes one stream twice: its positions are part of its identity. - -The refusal adds no error of its own for an operand whose identity cannot be computed (a raw -stream holding a value that cannot be hashed): it raises what hashing that stream raises. +"""Validate an operand group when a pod's argument symmetry is read (ITL-1419). + +The developer approved refusing collapsed operands as a stopgap until ITL-1511 adds +multiset identity and the unique/repeat toggle. Hashing and job recording read the +group. A standalone row read can skip identity formation. The group is built first +so hashing errors propagate before the repeated-operand check. """ from __future__ import annotations from collections.abc import Collection +from typing import Protocol from orcapod.errors import InputValidationError -from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol + + +class SymmetryDeclaring(Protocol): + """A pod that can describe the grouping of its inputs.""" + + def argument_symmetry( + self, streams: Collection[StreamProtocol] + ) -> ArgumentGroup: ... class RepeatedOperandError(InputValidationError): - """The operand set for a pod's identity contains two inputs with one identity. + """The operand group for a pod's identity lost a repeated operand. The developer approved this stopgap on 2026-11-27 until ITL-1511 adds a unique/repeat toggle. A job forms the identity and raises this error, while a standalone row read - can skip identity formation. The message names the pod whose own operands repeat - (``named``). A downstream pod or a function pod whose join got the repeated inputs - can attach context with ``add_context``. + can skip identity formation. The message names the pod whose own operands repeat. + Downstream pods can attach context with ``add_context``. Args: reason: What is repeated and what to do instead. - pod: The operator or function that got the repeated operand, or ``None`` until - that pod names itself. + pod: The operator or function that got the repeated operand. """ - def __init__(self, reason: str, pod: str | None = None) -> None: + def __init__(self, reason: str, pod: str) -> None: self.reason: str = reason - self.pod: str | None = pod + self.pod: str = pod self.context: list[str] = [] super().__init__(self._message()) def _message(self) -> str: - message = f"{self.pod}: {self.reason}" if self.pod else self.reason + message = f"{self.pod}: {self.reason}" if self.context: message += f" (in {'; '.join(self.context)})" return message - def named(self, pod: str) -> RepeatedOperandError: - """This error, naming ``pod`` as the one that got the repeated operand, unless - a pod is already named (the error then comes from upstream and is returned as - it is).""" - if self.pod is not None: - return self - named = RepeatedOperandError(self.reason, pod=pod) - named.context = list(self.context) - named.args = (named._message(),) - return named - def add_context(self, context: str) -> None: - """Say what the repeated operand is part of (``"the inputs of ..."``); the named - pod is kept.""" + """Append context while keeping the name of the pod whose input repeated.""" self.context.append(context) self.args = (self._message(),) -def operand_set(streams: Collection[StreamProtocol]) -> frozenset[StreamProtocol]: - """The operands of a commutative pod as the set its identity is formed from. +def _operand_count(group: ArgumentGroup) -> int: + if isinstance(group, (tuple, frozenset)): + return sum(_operand_count(member) for member in group) + return 1 + + +def read_argument_symmetry( + pod: SymmetryDeclaring, streams: Collection[StreamProtocol] +) -> ArgumentGroup: + """Read a pod's operand group and check that it retains every operand. Args: - streams: The operands. + pod: The pod declaring the operand group. + streams: The original operands. Returns: - The operands as a ``frozenset``. + The operand group as declared by the pod. Raises: - RepeatedOperandError: If two operands have one identity (they are equal, as a - set compares them), one object or two (not supported yet: ITL-1511), unnamed: the caller names its pod - (``err.named(...)``). An error met while hashing an operand (raised by a - pod upstream) is already named and passes through. + RepeatedOperandError: If set formation loses an operand (ITL-1511). """ + group = pod.argument_symmetry(streams) + if _operand_count(group) >= len(streams): + return group + seen: dict[StreamProtocol, StreamProtocol] = {} + repeated_labels: set[str] = set() for stream in streams: first = seen.get(stream) - if first is not None: - names = ( - repr(stream.label) - if first is stream or first.label == stream.label - else f"{first.label!r} and {stream.label!r}" - ) - raise RepeatedOperandError( - f"the same stream ({names}, one identity) is given more than once, " - "which is not supported yet (ITL-1511 is to allow it). Today its inputs " - "form a set, so a repeated input would change the rows but not the " - "identity. For now give each stream once; to join a stream with itself " - "in argument order, use MergeJoin, whose inputs are ordered: " - "MergeJoin()(stream, stream)." - ) - seen[stream] = stream - return frozenset(seen) + if first is None: + seen[stream] = stream + else: + repeated_labels.update((first.label, stream.label)) + names = " and ".join(repr(label) for label in sorted(repeated_labels)) + detail = f" ({names}, one identity)" if names else "" + raise RepeatedOperandError( + f"the same stream{detail} is given more than once, which is not supported yet " + "(ITL-1511 is to allow it). Today its inputs form a set, so a repeated input " + "would change the rows but not the identity. For now give each stream once; " + "to join a stream with itself in argument order, use MergeJoin, whose inputs " + "are ordered: MergeJoin()(stream, stream).", + pod=type(pod).__name__, + ) + + +def is_flat_commutative( + group: ArgumentGroup, streams: Collection[StreamProtocol] +) -> bool: + """Return whether the group is a set of the input streams themselves.""" + return isinstance(group, frozenset) and {id(member) for member in group} == { + id(stream) for stream in streams + } diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index f829d44a5..5cc7de69f 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1861,17 +1861,21 @@ def pipeline_hash(self, hasher=None) -> ContentHash: return super().pipeline_hash(hasher) def identity_structure(self) -> Any: + from orcapod.core.operators.repeated_operands import read_argument_symmetry + self._pod._note_provisional_identity_use() # a direct read is a use (ITL-1279) structure = (self._pod,) if self._upstreams: - structure += (self._pod.argument_symmetry(self._upstreams),) + structure += (read_argument_symmetry(self._pod, self._upstreams),) return structure def pipeline_identity_structure(self) -> Any: + from orcapod.core.operators.repeated_operands import read_argument_symmetry + self._pod._note_provisional_identity_use() # a direct read is a use (ITL-1279) structure = (self._pod,) if self._upstreams: - structure += (self._pod.argument_symmetry(self._upstreams),) + structure += (read_argument_symmetry(self._pod, self._upstreams),) return structure @property diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..358b8e64e 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -760,8 +760,13 @@ def producer(self) -> PodProtocol | None: ... def upstreams(self) -> tuple[StreamProtocol, ...]: ... def identity_structure(self) -> Any: + from orcapod.core.operators.repeated_operands import read_argument_symmetry + if self.producer is not None: - return (self.producer, self.producer.argument_symmetry(self.upstreams)) + return ( + self.producer, + read_argument_symmetry(self.producer, self.upstreams), + ) raise NotImplementedError("StreamBase.identity_structure") diff --git a/src/orcapod/pipeline/edges.py b/src/orcapod/pipeline/edges.py index 491c9cf21..57a75f749 100644 --- a/src/orcapod/pipeline/edges.py +++ b/src/orcapod/pipeline/edges.py @@ -19,8 +19,14 @@ from __future__ import annotations -from collections.abc import Collection, Iterable, Sequence -from typing import TYPE_CHECKING, Any, Protocol, TypeVar, cast +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, Any, TypeVar, cast + +from orcapod.core.operators.repeated_operands import ( + SymmetryDeclaring, + is_flat_commutative, + read_argument_symmetry, +) if TYPE_CHECKING: from orcapod.pipeline.dag import GraphProtocol @@ -33,22 +39,14 @@ commutative one, whose inputs have no position.""" -class _SymmetryDeclaring(Protocol): - """A pod, as far as positions read it: its argument symmetry.""" - - def argument_symmetry(self, streams: Collection[StreamProtocol]) -> object: ... - - def input_positions( - pod: _SymmetryDeclaring | None, inputs: Sequence[object] + pod: SymmetryDeclaring | None, inputs: Sequence[object] ) -> tuple[Position, ...]: """The position of each of ``inputs`` of ``pod``. - For an operator, the kind of ``pod.argument_symmetry(inputs)`` decides, with any - number of inputs: a ``tuple`` (ordered: ``MergeJoin``, ``SemiJoin``, a unary - operator) gives each input its argument index, a ``frozenset`` (commutative: - ``Join``, ``Rejoin``, also given one input) gives every input ``None``. Only the - kind of the returned group is read. A function pod is recorded with its one + A flat set of the inputs (commutative: ``Join``, ``Rejoin``, even with one input) + gives every input ``None``. Other groups, including nested groups, preserve + each input's argument index. A function pod is recorded with its one (joined) input and a side-effect pod takes one input: position 0. A pod that is not known (``None``: a node a loaded file keeps read-only, or of a kind this version does not restore) has its inputs in the argument order the file gives, so each its @@ -67,7 +65,7 @@ def input_positions( if not isinstance(pod, StaticOutputOperatorPod) or not inputs: return tuple(range(len(inputs))) streams = cast("Sequence[StreamProtocol]", inputs) - if isinstance(pod.argument_symmetry(streams), frozenset): + if is_flat_commutative(read_argument_symmetry(pod, streams), streams): return (None,) * len(inputs) return tuple(range(len(inputs))) diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py index 5569222dc..cac18efb9 100644 --- a/src/orcapod/pipeline/pod_invocation.py +++ b/src/orcapod/pipeline/pod_invocation.py @@ -76,7 +76,9 @@ def identity_structure(self) -> Any: This matches the identity structure of the corresponding compiled node, ensuring hash equality between invocation and node. """ - return (self._pod, self._pod.argument_symmetry(self._input_streams)) + from orcapod.core.operators.repeated_operands import read_argument_symmetry + + return (self._pod, read_argument_symmetry(self._pod, self._input_streams)) def pipeline_identity_structure(self) -> Any: """Return same as ``identity_structure()``.""" diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index abbebf83d..f0428e031 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -84,6 +84,10 @@ def require_positively_commutative( ValueError: If the operator is not positively known to be commutative. """ from orcapod.core.operators.base import BinaryOperator + from orcapod.core.operators.repeated_operands import ( + is_flat_commutative, + read_argument_symmetry, + ) # A binary operator given one stream twice has one edge in a legacy file (an edge # list cannot repeat an edge), so its two inputs cannot be restored (CodeRabbit on @@ -107,13 +111,10 @@ def require_positively_commutative( if operator is None or len(input_streams) != len(input_keys): raise refusal try: - symmetry = operator.argument_symmetry(input_streams) + symmetry = read_argument_symmetry(operator, 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}: + if not is_flat_commutative(symmetry, input_streams): raise refusal diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index 6640d5ff8..476fda2ea 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -2,9 +2,8 @@ An edge is ``(upstream, node, position)``: one upstream given to two inputs of an ordered operator is two edges, so ``MergeJoin()(a, a)`` and ``SemiJoin()(a, a)`` run in a job as -they run standalone. ``Join``, ``Rejoin`` and a function pod given one stream twice are -refused by the operator (or the pod's join) itself, standalone and in a job, for now (a -stopgap until ITL-1511). +they run standalone. Reading argument symmetry for ``Join``, ``Rejoin``, or a function +pod's join refuses repeated operands as a stopgap until ITL-1511. Inputs have two tag columns (``id``, ``key``) and two data columns (``x``, ``y``), in two layouts (tag order and column order swapped). @@ -14,17 +13,23 @@ import asyncio import json +from collections.abc import Collection +from importlib.util import find_spec from pathlib import Path from typing import Any import pyarrow as pa import pytest +from typing_extensions import override from orcapod import Pipeline, PipelineJob, function_pod, sources from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod.core.operators.repeated_operands import RepeatedOperandError +from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase -from orcapod.errors import InputValidationError +from orcapod.errors import InconsistentSourceError, InputValidationError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator +from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol LAYOUTS = ["tags_id_key", "tags_key_id"] @@ -296,7 +301,7 @@ def events_of(twice: bool) -> list[tuple[str, str]]: # ── what stays refused ─────────────────────────────────────────────────────── -def _data_tags_only(name: str = "d") -> Any: +def _data_tags_only(name: str = "d") -> sources.ArrowTableSource: """A source whose one tag is a data-tag and which has no other data column: no data column overlaps when it is given twice. ``id`` repeats a value, so ``Join(d, d)`` would give 5 rows where ``Join(d)`` gives 3.""" @@ -426,11 +431,9 @@ def test_a_step_over_a_repeated_join_is_refused_in_either_order( assert job.once.as_table().num_rows == 3 -def _raw_with_map(values: list[int]) -> Any: +def _raw_with_map(values: list[int]) -> ArrowTableStream: """A raw stream (no source) with a map data column: its identity hashes its rows, and a map value cannot be hashed.""" - from orcapod.core.streams.arrow_table_stream import ArrowTableStream - table = pa.table( { "id": pa.array(values, pa.int64()), @@ -621,8 +624,6 @@ def test_a_join_over_a_repeated_rejoin_raises_the_rejoin_refusal( wrapped in a plain ``InputValidationError``; a function pod adds its context. The ``Rejoin`` is built outside the job (inside, recording it is refused first, before any step over it).""" - from orcapod.core.operators.repeated_operands import RepeatedOperandError - d, d2, w = _data_tags_only(), _data_tags_only(), _data_tags_and_data() rejoined = Rejoin()(d, d2) with pytest.raises(RepeatedOperandError) as err: @@ -685,3 +686,67 @@ def test_one_data_tag_stream_twice_runs_in_a_job_with_the_standalone_schema( assert job.step.keys() == standalone.keys() assert stream_data_tags(job.step) == stream_data_tags(standalone) assert stream_data_tags(standalone) # the data-tags are kept, in both roles + + +@pytest.mark.skipif( + find_spec("orcapod.pipeline.source_consistency") is None, + reason="Requires the source consistency rule introduced by PR 577", +) +def test_ordered_inputs_cannot_alias_distinct_sources() -> None: + """Refuse a second source object before an ordered job can alias its inputs.""" + left = sources.ArrowTableSource( + pa.table({"id": [1], "key": ["k"], "x": [1]}), + tag_columns=["key"], + tag_only_columns=True, + source_id="same", + record_id_columns=["id"], + ) + right = sources.ArrowTableSource( + pa.table({"id": [2], "key": ["k"], "x": [2]}), + tag_columns=["key"], + tag_only_columns=True, + source_id="same", + record_id_columns=["id"], + ) + assert left is not right + assert left.content_hash() == right.content_hash() + assert MergeJoin()(left, right).as_table()["x"].to_pylist() == [[1, 2]] + + job = PipelineJob(database=InMemoryArrowDatabase()) + with job, pytest.raises(InconsistentSourceError): + _ = MergeJoin()(left, right, label="step") + assert "step" not in job.nodes + + +class OwnJoin(Join): + """An extension declaring its own flat commutative group.""" + + @override + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: + """Describe the operands as a commutative group.""" + return frozenset(streams) + + +def test_custom_commutative_operator_cannot_collapse_a_repeated_identity() -> None: + d = _data_tags_only() + repeated = OwnJoin()(d, d) + assert repeated.as_table().num_rows == 5 + assert OwnJoin()(d).as_table().num_rows == 3 + for form_identity in (repeated.content_hash, repeated.pipeline_hash): + with pytest.raises(RepeatedOperandError, match=rf"OwnJoin: the {REFUSAL}"): + _ = form_identity() + job = PipelineJob(database=InMemoryArrowDatabase()) + with job, pytest.raises(RepeatedOperandError, match=rf"OwnJoin: the {REFUSAL}"): + _ = OwnJoin()(d, d, label="step") + assert "step" not in job.nodes + + +def test_hashing_error_has_precedence_over_repeat_in_both_orders() -> None: + d = _data_tags_only() + raw = _raw_with_map([1, 2]) + with pytest.raises(ValueError) as own: + _ = raw.content_hash() + for inputs in ((d, d, raw), (raw, d, d)): + with pytest.raises(type(own.value)) as formed: + _ = Join()(*inputs).content_hash() + assert str(formed.value) == str(own.value) diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index 8b8aedc01..c5733b848 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -271,6 +271,23 @@ def argument_symmetry(self, streams: Collection[Any]) -> Any: register_operator("NestedMergeJoin", NestedMergeJoin) +def test_nested_ordered_edges_keep_both_positions_after_load(tmp_path: Path) -> None: + a = _inputs(tmp_path)["a"] + db = DeltaTableDatabase(tmp_path / "db") + job = PipelineJob(database=db) + with job: + _ = NestedMergeJoin()(a, a, label="step") + blueprint = job.pipeline + blueprint_path = tmp_path / "nested.pipeline.json" + blueprint.save(blueprint_path) + job_path = tmp_path / "nested.job.json" + job.save(job_path) + loaded_job = PipelineJob.load(job_path, database=db) + + for graph in (job, blueprint, Pipeline.load(blueprint_path), loaded_job): + assert [position for _, _, position in graph._graph_edges] == [0, 1] # pyright: ignore[reportPrivateUsage] + + def _legacy_custom( tmp_path: Path, make: Callable[[dict[str, Any]], Any], blueprint: bool ) -> tuple[Path, Path, PipelineJob]: From e2b7596a302d1043d8a741cc1aa29bde74f686f7 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Fri, 27 Nov 2026 15:20:49 -0800 Subject: [PATCH 11/11] fix(pipeline): scope repeat checks to flat unordered inputs (ITL-1419) --- changelog.d/ITL-1419.md | 2 +- docs/concepts/operators.md | 4 + docs/dev/plans/itl-1419-edge-positions.md | 5 +- .../core/operators/repeated_operands.py | 21 ++-- tests/test_pipeline/test_edge_positions.py | 112 +++++++++++++++++- 5 files changed, 131 insertions(+), 13 deletions(-) diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md index 429d515aa..88e121556 100644 --- a/changelog.d/ITL-1419.md +++ b/changelog.d/ITL-1419.md @@ -1,7 +1,7 @@ ### Breaking changes and migration - Reading argument symmetry raises `RepeatedOperandError` (an `InputValidationError`) - when an unordered group collapses repeated inputs. This applies to built-in and + when a flat unordered group collapses repeated inputs. This applies to built-in and custom operators, including `Rejoin` and the join used by a function pod. Two inputs with the same identity count as repeats. The developer approved the refusal on 2026-11-27 as a stopgap until ITL-1511 allows repeats with a unique/repeat toggle. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index 343b6374a..3183accef 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -113,6 +113,10 @@ The developer approved this stopgap on 2026-11-27. A standalone row read such as it skips identity formation. The same invocation is refused in a job. ITL-1511 will allow repeated operands with a unique/repeat toggle and remove this discrepancy. +**Known limit.** The refusal covers flat unordered declarations, including every +commutative operator Orcapod ships. Mixed or nested unordered groups are unchecked. +ITL-1548 tracks how operators declare argument symmetry alongside ITL-1511. + ```python from orcapod.sources import DictSource from orcapod.operators import Join diff --git a/docs/dev/plans/itl-1419-edge-positions.md b/docs/dev/plans/itl-1419-edge-positions.md index a292e1066..23138227a 100644 --- a/docs/dev/plans/itl-1419-edge-positions.md +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -34,9 +34,8 @@ added its own error for an operand that cannot be hashed. On 2026-11-27 the developer approved refusing repeated operands as a stopgap until ITL-1511. `core/operators/repeated_operands.read_argument_symmetry` reads the operator's -grouping and raises `RepeatedOperandError` (an `InputValidationError`) if an unordered -group has collapsed repeated operands. The check applies to built-in and custom -operators because it reads their result. The error names the operator whose own +grouping and raises `RepeatedOperandError` (an `InputValidationError`) if a flat +unordered group has collapsed repeated operands. The error names the operator whose own operands repeat. A downstream pod or the function pod whose join received the operands can add context with `add_context`. Hashing, recording and compiling form the identity. Set formation completes before checking for collapsed operands, so the existing hashing diff --git a/src/orcapod/core/operators/repeated_operands.py b/src/orcapod/core/operators/repeated_operands.py index 446e1641e..3c4ad88e8 100644 --- a/src/orcapod/core/operators/repeated_operands.py +++ b/src/orcapod/core/operators/repeated_operands.py @@ -11,6 +11,8 @@ from collections.abc import Collection from typing import Protocol +from typing_extensions import override + from orcapod.errors import InputValidationError from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol @@ -53,17 +55,16 @@ def add_context(self, context: str) -> None: self.context.append(context) self.args = (self._message(),) - -def _operand_count(group: ArgumentGroup) -> int: - if isinstance(group, (tuple, frozenset)): - return sum(_operand_count(member) for member in group) - return 1 + @override + def __reduce__(self) -> tuple[object, ...]: + """Rebuild from the constructor fields and keep the contextual message.""" + return (type(self), (self.reason, self.pod), {**vars(self), "args": self.args}) def read_argument_symmetry( pod: SymmetryDeclaring, streams: Collection[StreamProtocol] ) -> ArgumentGroup: - """Read a pod's operand group and check that it retains every operand. + """Read a pod's operand group and check for collapse in a flat unordered group. Args: pod: The pod declaring the operand group. @@ -73,10 +74,14 @@ def read_argument_symmetry( The operand group as declared by the pod. Raises: - RepeatedOperandError: If set formation loses an operand (ITL-1511). + RepeatedOperandError: If the flat set of inputs loses an operand (ITL-1511). """ group = pod.argument_symmetry(streams) - if _operand_count(group) >= len(streams): + if not isinstance(group, frozenset) or len(group) >= len(streams): + return group + # A flat set takes all inputs. A nested set does not tell us which inputs went + # into each group before set formation (ITL-1548). + if any(isinstance(member, (tuple, frozenset)) for member in group): return group seen: dict[StreamProtocol, StreamProtocol] = {} diff --git a/tests/test_pipeline/test_edge_positions.py b/tests/test_pipeline/test_edge_positions.py index 476fda2ea..77447f2aa 100644 --- a/tests/test_pipeline/test_edge_positions.py +++ b/tests/test_pipeline/test_edge_positions.py @@ -13,10 +13,11 @@ import asyncio import json +import pickle from collections.abc import Collection from importlib.util import find_spec from pathlib import Path -from typing import Any +from typing import Any, ClassVar import pyarrow as pa import pytest @@ -24,12 +25,14 @@ from orcapod import Pipeline, PipelineJob, function_pod, sources from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod.core.operators.base import BinaryOperator from orcapod.core.operators.repeated_operands import RepeatedOperandError from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.errors import InconsistentSourceError, InputValidationError from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol +from orcapod.types import ColumnConfig, Schema LAYOUTS = ["tags_id_key", "tags_key_id"] @@ -741,6 +744,113 @@ def test_custom_commutative_operator_cannot_collapse_a_repeated_identity() -> No assert "step" not in job.nodes +class LeftOnly(BinaryOperator): + """An ordered binary operator whose right operand has no effect.""" + + DATA_TAGS_ISSUE: ClassVar[str | None] = None + + @override + def identity_structure(self) -> tuple[str, ...]: + return ("LeftOnly",) + + @override + def is_commutative(self) -> bool: + return False + + @override + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: + left, _ = streams + return (left,) + + @override + def validate_binary_inputs( + self, left_stream: StreamProtocol, right_stream: StreamProtocol + ) -> None: + pass + + @override + def binary_output_schema( + self, + left_stream: StreamProtocol, + right_stream: StreamProtocol, + *, + columns: ColumnConfig | dict[str, Any] | None = None, + all_info: bool = False, + ) -> tuple[Schema, Schema]: + return left_stream.output_schema(columns=columns, all_info=all_info) + + @override + def binary_static_process( + self, left_stream: StreamProtocol, right_stream: StreamProtocol + ) -> StreamProtocol: + return left_stream + + +@pytest.mark.parametrize("repeat", [False, True]) +def test_ordered_operator_can_omit_an_operand_from_its_identity(repeat: bool) -> None: + left = _a(LAYOUTS[0]) + right = left if repeat else _b(LAYOUTS[0]) + output = LeftOnly()(left, right) + _ = output.content_hash() + _ = output.pipeline_hash() + job = PipelineJob(database=InMemoryArrowDatabase()) + with job: + _ = LeftOnly()(left, right, label="step") + _ = job.run() + expected = _rows(left.as_table()) + assert _rows(output.as_table()) == expected + assert _rows(job.step.as_table()) == expected + + +class NestedMergeJoin(MergeJoin): + """A single unordered member containing both ordered inputs.""" + + @override + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: + return frozenset((tuple(streams),)) + + +def test_repeat_in_nested_ordered_group_keeps_both_positions() -> None: + stream = _data_tags_only() + expected = _rows(NestedMergeJoin()(stream, stream).as_table()) + job = PipelineJob(database=InMemoryArrowDatabase()) + with job: + _ = NestedMergeJoin()(stream, stream, label="joined") + _ = job.run() + assert [position for _, _, position in _edges_by_label(job)] == [0, 1] + assert _rows(job.joined.as_table()) == expected + + +class MixedJoin(Join): + """A join with an unordered pair and a separate, ordered third input.""" + + @override + def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup: + first, second, third = streams + return (frozenset((first, second)), third) + + +def test_mixed_group_collapse_is_outside_the_stopgap() -> None: + """The raw set discards the membership history needed to check the pair.""" + first = _data_tags_only("first") + third = _data_tags_only("third") + output = MixedJoin()(first, first, third) + _ = output.content_hash() + _ = output.pipeline_hash() + + +def test_repeated_operand_error_preserves_its_pod_and_message_when_pickled() -> None: + first, second = _data_tags_only(), _data_tags_only() + with pytest.raises(RepeatedOperandError) as caught: + _ = _identity.pod(first, second).content_hash() + original = caught.value + restored: object = pickle.loads(pickle.dumps(original)) + assert isinstance(restored, RepeatedOperandError) + assert restored.pod == original.pod == "Join" + assert str(restored) == str(original) + assert restored.context == original.context + + def test_hashing_error_has_precedence_over_repeat_in_both_orders() -> None: d = _data_tags_only() raw = _raw_with_map([1, 2])