diff --git a/changelog.d/ITL-1419.md b/changelog.d/ITL-1419.md new file mode 100644 index 000000000..88e121556 --- /dev/null +++ b/changelog.d/ITL-1419.md @@ -0,0 +1,40 @@ +### Breaking changes and migration + +- Reading argument symmetry raises `RepeatedOperandError` (an `InputValidationError`) + 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. + 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 in either argument order, even when another input repeats. 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 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. 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 + 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 + +- 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. + Saved positions are stage 2 of ITL-1472. diff --git a/docs/concepts/operators.md b/docs/concepts/operators.md index d17760bf9..f85dd7686 100644 --- a/docs/concepts/operators.md +++ b/docs/concepts/operators.md @@ -103,6 +103,20 @@ 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. + +**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/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 68672e28c..713c21d1a 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -392,6 +392,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 new file mode 100644 index 000000000..23138227a --- /dev/null +++ b/docs/dev/plans/itl-1419-edge-positions.md @@ -0,0 +1,113 @@ +# 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`. + +## 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 +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. 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. + +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 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 +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. + +## 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 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. +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.** `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, 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). +- 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. + +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/docs/reference/hashing.md b/docs/reference/hashing.md index 4c9a4af72..13ee27d39 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -397,7 +397,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 lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` | | 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..` | diff --git a/scripts/hash_audit_example.py b/scripts/hash_audit_example.py index eea141a38..571124181 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/core/function_pod.py b/src/orcapod/core/function_pod.py index 1d0f7d9ce..0b4ba62f4 100644 --- a/src/orcapod/core/function_pod.py +++ b/src/orcapod/core/function_pod.py @@ -644,8 +644,21 @@ def handle_input_streams(self, *streams: StreamProtocol) -> StreamProtocol: raise ValueError("At least one input stream is required") elif len(streams) > 1: # 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] @@ -859,7 +872,25 @@ 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; 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, + read_argument_symmetry, + ) + + try: + 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}" + ) + raise def output_schema( self, diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4f4632f3d..10b83c526 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -296,7 +296,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 f4baa10f3..acd680fec 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -342,11 +342,8 @@ 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) - else: - # return as ordered group - return tuple(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 06cdcfd26..00d7cbe1d 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 @@ -215,6 +221,7 @@ 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 because ``Join`` is commutative.""" return frozenset(streams) def output_schema( diff --git a/src/orcapod/core/operators/rejoin.py b/src/orcapod/core/operators/rejoin.py index d760f5865..4ad21ff88 100644 --- a/src/orcapod/core/operators/rejoin.py +++ b/src/orcapod/core/operators/rejoin.py @@ -277,8 +277,11 @@ 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 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 new file mode 100644 index 000000000..3c4ad88e8 --- /dev/null +++ b/src/orcapod/core/operators/repeated_operands.py @@ -0,0 +1,113 @@ +"""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 typing_extensions import override + +from orcapod.errors import InputValidationError +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 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. + 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. + """ + + def __init__(self, reason: str, pod: str) -> None: + self.reason: str = reason + self.pod: str = pod + self.context: list[str] = [] + super().__init__(self._message()) + + def _message(self) -> str: + message = f"{self.pod}: {self.reason}" + if self.context: + message += f" (in {'; '.join(self.context)})" + return message + + def add_context(self, context: str) -> None: + """Append context while keeping the name of the pod whose input repeated.""" + self.context.append(context) + self.args = (self._message(),) + + @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 for collapse in a flat unordered group. + + Args: + pod: The pod declaring the operand group. + streams: The original operands. + + Returns: + The operand group as declared by the pod. + + Raises: + RepeatedOperandError: If the flat set of inputs loses an operand (ITL-1511). + """ + group = pod.argument_symmetry(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] = {} + repeated_labels: set[str] = set() + for stream in streams: + first = seen.get(stream) + 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/semijoin.py b/src/orcapod/core/operators/semijoin.py index 18d28ea52..49b7b87c3 100644 --- a/src/orcapod/core/operators/semijoin.py +++ b/src/orcapod/core/operators/semijoin.py @@ -309,8 +309,14 @@ 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: common_keys = 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/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..54d618011 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1868,17 +1868,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/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..d3e3eec36 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 @@ -335,6 +343,9 @@ 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 identity. Forming the invocation's identity raises + ``RepeatedOperandError`` as a stopgap until ITL-1511. """ from orcapod.pipeline.restrictions import require_one_restriction @@ -352,8 +363,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 +638,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 +828,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..57a75f749 --- /dev/null +++ b/src/orcapod/pipeline/edges.py @@ -0,0 +1,136 @@ +"""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 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 + 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.""" + + +def input_positions( + pod: SymmetryDeclaring | None, inputs: Sequence[object] +) -> tuple[Position, ...]: + """The position of each of ``inputs`` of ``pod``. + + 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 + 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. + """ + 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 is_flat_commutative(read_argument_symmetry(pod, streams), streams): + 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 0b58b8f37..9af17ec30 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) @@ -584,6 +595,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, @@ -615,6 +638,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 @@ -650,7 +684,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 82f59257c..1e51f7bf7 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, @@ -833,12 +834,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 @@ -862,7 +868,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 @@ -1303,7 +1309,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: @@ -1355,7 +1361,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 @@ -2141,7 +2147,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/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 0f647fe96..2f8e4f9b9 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -91,6 +91,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 @@ -114,13 +118,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/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..77447f2aa --- /dev/null +++ b/tests/test_pipeline/test_edge_positions.py @@ -0,0 +1,862 @@ +"""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. 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). +""" + +from __future__ import annotations + +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, ClassVar + +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.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"] +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 ─────────────────────────────────────────────────────── + + +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.""" + 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} + + +REPEATS = { + "same_object": lambda make: (lambda s: (s, s))(make()), + "equal_sources": lambda make: (make(), make()), +} +REFUSAL = r"same stream.*more than once.*not supported yet.*ITL-1511.*MergeJoin" + + +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)) +@pytest.mark.parametrize("inputs", sorted(INPUTS)) +@pytest.mark.parametrize("pod", sorted(COMMUTATIVE)) +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 (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() + + +@pytest.mark.parametrize("pod", ["Join", "Rejoin"]) +def test_a_repeat_among_three_operands_is_refused(pod: str) -> None: + 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, repeat: str, repeated_first: bool, mode: str +) -> None: + """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](first, label="once") + with pytest.raises(InputValidationError, match=_refusal(pod)): + COMMUTATIVE[pod](first, second, label="twice") + if repeated_first: + 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]) -> ArrowTableStream: + """A raw stream (no source) with a map data column: its identity hashes its rows, + and a map value cannot be hashed.""" + 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() + assert MergeJoin()(d, d).as_table().num_rows == 5 + assert SemiJoin()(d, d).as_table().num_rows == 3 + + +# ── 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", "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 (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)]) + + @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") + 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 + 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] + + +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) + + +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).""" + 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 + + +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 + + +@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 + + +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]) + 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 af154b56c..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]: @@ -434,20 +451,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