From 556aa101984b701e8e40cb3df6476597615f7485 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 20:55:36 -0800 Subject: [PATCH 1/4] fix(pipeline): a loaded job gives an ordered operator its inputs in argument order (ITL-1417) A saved job lists each operator's inputs in argument order under 'inputs', and both loaders build an operator's inputs from it; a file saved before, holding MergeJoin or SemiJoin over two inputs, is refused at load. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1417.md | 9 + docs/concepts/pipeline-job.md | 7 + docs/dev/design_issues/ITL-1417-AO1.md | 21 ++ src/orcapod/pipeline/graph.py | 31 ++- src/orcapod/pipeline/job.py | 5 +- src/orcapod/pipeline/serialization.py | 41 ++++ .../test_loaded_argument_order.py | 211 ++++++++++++++++++ 7 files changed, 323 insertions(+), 2 deletions(-) create mode 100644 changelog.d/ITL-1417.md create mode 100644 docs/dev/design_issues/ITL-1417-AO1.md create mode 100644 tests/test_pipeline/test_loaded_argument_order.py diff --git a/changelog.d/ITL-1417.md b/changelog.d/ITL-1417.md new file mode 100644 index 000000000..e0b828e9d --- /dev/null +++ b/changelog.d/ITL-1417.md @@ -0,0 +1,9 @@ +### Fixed + +- A saved and loaded job could run `MergeJoin` or `SemiJoin` with its two inputs swapped + when another step over its second input had been recorded first: the loader took an + operator's inputs in the order the steps were recorded. A saved job now lists each + operator's inputs in argument order (`inputs` in the node's entry), and loading uses that + list. A job file saved before this fix that holds `MergeJoin` or `SemiJoin` over two + inputs is refused at load, with a message to save it again from its code; a file with only + commutative operators (`Join`, `Rejoin`) loads as before. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 625400b73..9056c757f 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -422,6 +422,13 @@ database that holds other rows than the file expects) are in `Pipeline.save(path)` and `Pipeline.load(path)` save and load a blueprint. +The file lists each operator's inputs in the order they were given, so a loaded +`MergeJoin(left, right)` or `SemiJoin(left, right)` takes `left` first, as the live job did. +A file saved by an Orcapod older than this rule (before ITL-1417) that holds one of these +two operators over two inputs cannot say which input comes first, and loading it raises +`ValueError`; build the job from its code and save it again. A file whose operators are all +commutative (`Join`, `Rejoin`) loads as before. + ## How it connects to other concepts - A job records applications of [Function Pods](function-pods.md) and diff --git a/docs/dev/design_issues/ITL-1417-AO1.md b/docs/dev/design_issues/ITL-1417-AO1.md new file mode 100644 index 000000000..8816722d9 --- /dev/null +++ b/docs/dev/design_issues/ITL-1417-AO1.md @@ -0,0 +1,21 @@ +## `src/orcapod/pipeline/job.py` — reading a loaded `PipelineJob` + +### AO1 — A loaded job could run MergeJoin or SemiJoin with its inputs swapped +**Status:** resolved +**Severity:** critical +**Issue:** ITL-1417 + +A saved job listed an operator's inputs only through the edge list, whose order follows +the order the steps were recorded in, and both loaders (`Pipeline.load`, `PipelineJob.load`) +gave the operator its inputs in that order (the job loader through the hash graph's +predecessors, which a copy reorders again). With another step over the second input recorded +first, a loaded `MergeJoin(left, right)` ran as `MergeJoin(right, left)`: a job run with +`load_only=True` returned `[[100, 1], [101, 2]]` where the live job had `[[1, 100], [2, 101]]`. +`SemiJoin` kept the wrong side. Commutative operators (`Join`, `Rejoin`) were not affected. +Found while building ITL-1387. + +**Fix:** every saved operator node lists its inputs' keys in argument order under `inputs` +(format 0.4.0, added within the version), and both loaders build an operator's inputs from +that list. A file saved before has no list: an ordered operator over two different inputs is +refused at load (its order cannot be known), a commutative one loads as before. +`tests/test_pipeline/test_loaded_argument_order.py`. diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 997b0a3dd..abc6fbc5f 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -130,6 +130,7 @@ def save(self, path: str | Path) -> None: import json as _json from orcapod.pipeline.serialization import ( FALL_THROUGH_TAGS_KEY, + OPERATOR_INPUTS_KEY, PIPELINE_FORMAT_VERSION, serialize_arrow_schemas, serialize_output_schema, @@ -168,6 +169,7 @@ def save(self, path: str | Path) -> None: raise retained[key] = stored nodes: dict[str, Any] = {} + key_of = {id(node): key for key, node in self._persistent_node_map.items()} for content_hash_str, node in self._persistent_node_map.items(): try: type_converter = node.data_context.type_converter @@ -262,6 +264,20 @@ def save(self, path: str | Path) -> None: descriptor[FALL_THROUGH_TAGS_KEY] = list(node.declared_data_tags()) case OperatorNode(): + # The inputs in argument order (ITL-1417): an ordered operator + # (MergeJoin, SemiJoin) is rebuilt from this list, never from the + # edge list, whose order follows the order steps were recorded in. + inputs = [ + key_of[id(upstream)] + for upstream in node.upstreams + if id(upstream) in key_of + ] + if not inputs and OPERATOR_INPUTS_KEY in node._descriptor: + # A loaded read-only node holds no inputs: its saved list is + # written back as it is, so saving again keeps the entry. + inputs = list(node._descriptor[OPERATOR_INPUTS_KEY]) + if inputs: + descriptor[OPERATOR_INPUTS_KEY] = inputs if node._operator is not None: descriptor["operator_config"] = node._operator.to_config() elif "operator_config" in node._descriptor: @@ -308,8 +324,10 @@ def load(cls, path: str | Path) -> "Pipeline": import json as _json from orcapod.pipeline.serialization import ( FALL_THROUGH_TAGS_KEY, + OPERATOR_INPUTS_KEY, PIPELINE_FORMAT_VERSION, require_current_format, + require_known_argument_order, require_nullability_records, arrow_schema_from_texts, deserialize_schema, @@ -484,7 +502,14 @@ def load(cls, path: str | Path) -> "Pipeline": reconstructed[node_hash] = node elif node_type == "operator": - up_hashes = upstream_map.get(node_hash, []) + # The inputs in argument order (ITL-1417); a file saved before the + # list was written gives only the edges, in recording order. + saved_inputs = descriptor.get(OPERATOR_INPUTS_KEY) + up_hashes = ( + list(saved_inputs) + if saved_inputs is not None + else upstream_map.get(node_hash, []) + ) upstream_nodes = tuple( reconstructed[h] for h in up_hashes if h in reconstructed ) @@ -542,6 +567,10 @@ def load(cls, path: str | Path) -> "Pipeline": exc, ) operator = None + if saved_inputs is None and operator is not None: + require_known_argument_order( + operator, up_hashes, descriptor.get("label") + ) node = OperatorNode.from_descriptor( descriptor, operator=operator, diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index ea3f5570f..127dfccc3 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1808,6 +1808,7 @@ def load( # is the source of truth. expected_rows: dict[str, int] = run_block.get("expected_rows", {}) + bp_key_of = {id(bp): h for h, bp in pipeline._persistent_node_map.items()} for node_hash in _nx.topological_sort(job._hash_graph): bp_node = pipeline._persistent_node_map.get(node_hash) if bp_node is None: @@ -1841,7 +1842,9 @@ def load( elif isinstance(bp_node, _OperatorNode): descriptor = getattr(bp_node, "_descriptor", None) or {} - preds = list(job._hash_graph.predecessors(node_hash)) + # The inputs in the blueprint node's order, its argument order + # (ITL-1417); a graph's predecessors do not keep that order. + preds = [bp_key_of[id(up)] for up in bp_node.upstreams] input_streams = tuple( job._persistent_node_map[p] for p in preds diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 29142a2b6..933e23d09 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -40,11 +40,52 @@ # whole fields. Every source config that takes the option writes # ``tag_only_columns`` and every function node writes ``fall_through_tags``; # a load refuses a file without them (ITL-1159, ITL-1019). +# Each operator node lists its inputs in argument order under ``inputs`` +# (ITL-1417, added within 0.4.0: a file without it still loads, except an +# ordered operator over two inputs, which is refused). # A file of an earlier format (0.1.0 to 0.3.0) is refused at load, never read in its # old grammar: load and save had not been used in production (developer, 2026-11-21). # Taking such files to the current format is the migration tool's work (ITL-1048). PIPELINE_FORMAT_VERSION = "0.4.0" +#: The key of an operator node's inputs in a saved file, their keys in argument order +#: (ITL-1417). Written for every operator node within format 0.4.0: a file saved +#: before it has none, and its edges list the inputs in the order the steps were +#: recorded, not in argument order. +OPERATOR_INPUTS_KEY = "inputs" + + +def require_known_argument_order( + operator: Any, input_keys: list[str], label: str | None +) -> None: + """Refuse to rebuild an ordered operator whose argument order a file does not give. + + A file saved before ``OPERATOR_INPUTS_KEY`` was written lists an operator's + inputs only through its edges, in the order the steps were recorded (ITL-1417). + For a commutative operator (``Join``) the order does not matter; for an ordered + one (``MergeJoin``, ``SemiJoin``) over two different inputs it cannot be known, so + the file is refused rather than read with a guessed order. + + Args: + operator: The rebuilt operator. + input_keys: The keys of its inputs, in edge order. + label: The node's label, for the message. + + Raises: + ValueError: If the operator takes its inputs in order and the file does not + say which comes first. + """ + if len(set(input_keys)) < 2: + return + if not isinstance(operator.argument_symmetry(tuple(input_keys)), tuple): + return + raise ValueError( + f"The saved job's node {label!r} ({type(operator).__name__}) takes its inputs " + "in order, and the file does not say which comes first: it was saved before " + "Orcapod wrote each operator's inputs in argument order (ITL-1417), so loading " + "it could swap them. Build the job from its code and save it again." + ) + def require_current_format(version: str, current: str) -> None: """Refuse a saved file whose format version is not the one this Orcapod writes. diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py new file mode 100644 index 000000000..15b579000 --- /dev/null +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -0,0 +1,211 @@ +"""A loaded job gives an ordered operator its inputs in argument order (ITL-1417). + +``MergeJoin`` and ``SemiJoin`` take their inputs in order. A saved job used to be rebuilt +with an operator's inputs in the order its edges were listed, which follows the order +the steps were recorded in: with another step over the second input recorded first, a +loaded ``MergeJoin(left, right)`` ran as ``MergeJoin(right, left)``. The saved file now +lists each operator's inputs in argument order (``inputs``), and a file saved before +that is refused when it holds an ordered operator over two inputs. +""" + +from __future__ import annotations + +import asyncio +import inspect +import json +from collections.abc import Callable +from pathlib import Path +from typing import Any + +import pytest + +from orcapod import PipelineJob, operators, sources +from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod.core.operators.base import BinaryOperator, NonZeroInputOperator +from orcapod.databases import DeltaTableDatabase +from orcapod.pipeline.serialization import OPERATOR_INPUTS_KEY + +ORDERED = {"MergeJoin", "SemiJoin"} +COMMUTATIVE = {"Join", "Rejoin"} + + +def test_every_multi_input_operator_is_classified() -> None: + """The operators whose argument order matters are exactly ``ORDERED``; a new + multi-input operator fails here until it is classified and has a case below.""" + ordered: set[str] = set() + commutative: set[str] = set() + for name in operators.__all__: + cls = getattr(operators, name) + if not inspect.isclass(cls) or not issubclass( + cls, (BinaryOperator, NonZeroInputOperator) + ): + continue + # Placeholders stand for two different streams: only the kind of the + # returned group (tuple: ordered, frozenset: commutative) is read. + two_inputs: Any = ("a", "b") + symmetry = cls().argument_symmetry(two_inputs) + (ordered if isinstance(symmetry, tuple) else commutative).add(name) + assert ordered == ORDERED + assert commutative == COMMUTATIVE + + +def _csv(tmp_path: Path, name: str, rows: str) -> Any: + path = tmp_path / f"{name}.csv" + path.write_text(rows) + return sources.CSVSource( + str(path), tag_columns=["id"], tag_only_columns=True, source_id=name + ) + + +def _inputs(tmp_path: Path) -> dict[str, Any]: + """Three CSV sources over one key; ``left`` and ``right`` share the data column + ``x``, ``third`` has its own.""" + return { + "left": _csv(tmp_path, "left", "id,x,y\n1,1,10\n2,2,20\n3,3,30\n"), + "right": _csv(tmp_path, "right", "id,x,z\n1,100,0\n2,101,0\n"), + "third": _csv(tmp_path, "third", "id,w\n1,7\n2,8\n"), + } + + +# Each case: the operator's name and the step over the inputs. ``left`` and ``right`` +# are the two inputs of a binary operator, in argument order; the order is visible in +# the rows (MergeJoin's lists, SemiJoin's kept side). +CASES: dict[str, Callable[[dict[str, Any]], Any]] = { + "MergeJoin": lambda s: MergeJoin()(s["left"], s["right"], label="step"), + "SemiJoin": lambda s: SemiJoin()(s["left"], s["right"], label="step"), + "Join": lambda s: Join()( + s["left"].select_data_columns(["y"]), s["third"], label="step" + ), + "Rejoin": lambda s: Rejoin()( + s["left"].select_data_columns(["x"]), + s["left"].select_data_columns(["y"]), + label="step", + ), + # Three inputs: a commutative Join of three, then an ordered MergeJoin over it. + "Join3_then_MergeJoin": lambda s: MergeJoin()( + Join()( + s["left"].select_data_columns(["x"]), + s["third"], + s["left"].select_data_columns(["y"]), + label="joined", + ), + s["right"].select_data_columns(["x"]), + label="step", + ), +} + + +def _rows(table: Any) -> list[str]: + return sorted(repr(sorted(row.items())) for row in table.to_pylist()) + + +def _build( + tmp_path: Path, case: str, other_use_first: bool +) -> tuple[PipelineJob, Path]: + """The job, with another step over ``right`` recorded before or after the case.""" + streams = _inputs(tmp_path) + db_path = tmp_path / "db" + job = PipelineJob(name="ordered", database=DeltaTableDatabase(db_path)) + with job: + if other_use_first: + streams["right"].select_data_columns(["z"], label="other_use") + CASES[case](streams) + if not other_use_first: + streams["right"].select_data_columns(["z"], label="other_use") + return job, db_path + + +def _run(job: PipelineJob, mode: str, **kwargs: Any) -> None: + if mode == "sync": + job.run(**kwargs) + else: + asyncio.run(job.run_async(**kwargs)) + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("other_use_first", [False, True]) +@pytest.mark.parametrize("case", sorted(CASES)) +def test_a_loaded_job_gives_the_rows_of_the_live_job( + case: str, other_use_first: bool, mode: str, tmp_path: Path +) -> None: + """Live rows equal the rows of the saved and loaded job run with + ``load_only=True``, whatever order the steps were recorded in.""" + job, db_path = _build(tmp_path, case, other_use_first) + _run(job, mode) + live = _rows(job.step.as_table()) + job.save(tmp_path / "job.json") + loaded = PipelineJob.load( + tmp_path / "job.json", database=DeltaTableDatabase(db_path) + ) + _run(loaded, mode, load_only=True) + assert _rows(loaded.step.as_table()) == live + + +@pytest.mark.parametrize("other_use_first", [False, True]) +@pytest.mark.parametrize("case", ["MergeJoin", "SemiJoin"]) +def test_the_saved_file_lists_an_operators_inputs_in_argument_order( + case: str, other_use_first: bool, tmp_path: Path +) -> None: + job, _ = _build(tmp_path, case, other_use_first) + job.save(tmp_path / "job.json") + nodes = json.loads((tmp_path / "job.json").read_text())["pipeline"]["nodes"] + label_of = {key: node["label"] for key, node in nodes.items()} + step = next(node for node in nodes.values() if node["label"] == "step") + assert [label_of[key] for key in step[OPERATOR_INPUTS_KEY]] == ["left", "right"] + + +def _strip_inputs(path: Path) -> None: + """Make the file one saved before ITL-1417: no ``inputs`` on any operator.""" + data = json.loads(path.read_text()) + for node in data["pipeline"]["nodes"].values(): + node.pop(OPERATOR_INPUTS_KEY, None) + path.write_text(json.dumps(data)) + + +@pytest.mark.parametrize("other_use_first", [False, True]) +@pytest.mark.parametrize("case", ["MergeJoin", "SemiJoin", "Join3_then_MergeJoin"]) +def test_a_file_saved_before_the_fix_with_an_ordered_operator_is_refused( + case: str, other_use_first: bool, tmp_path: Path +) -> None: + """An ordered operator over two inputs in a file without ``inputs``: the order + cannot be known, so the load refuses rather than guess.""" + job, db_path = _build(tmp_path, case, other_use_first) + job.save(tmp_path / "job.json") + _strip_inputs(tmp_path / "job.json") + with pytest.raises(ValueError, match="does not say which comes first"): + PipelineJob.load(tmp_path / "job.json", database=DeltaTableDatabase(db_path)) + + +@pytest.mark.parametrize("other_use_first", [False, True]) +@pytest.mark.parametrize("case", ["Join", "Rejoin"]) +def test_a_file_saved_before_the_fix_with_commutative_operators_still_loads( + case: str, other_use_first: bool, tmp_path: Path +) -> None: + """A commutative operator does not depend on its input order: such an old file + loads and gives the live rows.""" + job, db_path = _build(tmp_path, case, other_use_first) + job.run() + live = _rows(job.step.as_table()) + job.save(tmp_path / "job.json") + _strip_inputs(tmp_path / "job.json") + loaded = PipelineJob.load( + tmp_path / "job.json", database=DeltaTableDatabase(db_path) + ) + loaded.run(load_only=True) + assert _rows(loaded.step.as_table()) == live + + +def test_a_loaded_file_saves_again_with_the_same_inputs(tmp_path: Path) -> None: + """Saving a loaded job again writes the same ``inputs`` and edges.""" + job, db_path = _build(tmp_path, "MergeJoin", True) + job.save(tmp_path / "first.json") + loaded = PipelineJob.load( + tmp_path / "first.json", database=DeltaTableDatabase(db_path) + ) + loaded.save(tmp_path / "second.json") + first = json.loads((tmp_path / "first.json").read_text())["pipeline"] + second = json.loads((tmp_path / "second.json").read_text())["pipeline"] + assert second["edges"] == first["edges"] + assert { + key: node.get(OPERATOR_INPUTS_KEY) for key, node in second["nodes"].items() + } == {key: node.get(OPERATOR_INPUTS_KEY) for key, node in first["nodes"].items()} From 556effa25f4331cb7654f03aaf7003ecc27c9065 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:17:46 -0800 Subject: [PATCH 2/4] fix(pipeline): a legacy job file loads a multi-input operator only when it is known to be commutative (ITL-1417) Answer the independent review: the symmetry is asked of the rebuilt input streams, a nested group or an operator kept read-only is refused, and a loaded read-only node keeps its inputs. Every finding has a test. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1417.md | 8 +- docs/concepts/pipeline-job.md | 9 +- docs/dev/design_issues/ITL-1417-AO1.md | 8 +- src/orcapod/pipeline/graph.py | 14 +- src/orcapod/pipeline/job.py | 10 +- src/orcapod/pipeline/serialization.py | 50 ++- .../test_loaded_argument_order.py | 375 ++++++++++++++---- 7 files changed, 372 insertions(+), 102 deletions(-) diff --git a/changelog.d/ITL-1417.md b/changelog.d/ITL-1417.md index e0b828e9d..37d093ee4 100644 --- a/changelog.d/ITL-1417.md +++ b/changelog.d/ITL-1417.md @@ -4,6 +4,8 @@ when another step over its second input had been recorded first: the loader took an operator's inputs in the order the steps were recorded. A saved job now lists each operator's inputs in argument order (`inputs` in the node's entry), and loading uses that - list. A job file saved before this fix that holds `MergeJoin` or `SemiJoin` over two - inputs is refused at load, with a message to save it again from its code; a file with only - commutative operators (`Join`, `Rejoin`) loads as before. + list. A job file saved before this fix loads an operator over two or more inputs only when + the operator is known to be commutative (`Join`, `Rejoin`, or a custom operator whose + `argument_symmetry` on its inputs is a flat `frozenset` of them); any other (`MergeJoin`, + `SemiJoin`, an operator kept read-only on load) is refused with a message to save the job + again from its code. Loaded read-only nodes keep their inputs. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 9056c757f..e4c6c1816 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -424,10 +424,11 @@ database that holds other rows than the file expects) are in The file lists each operator's inputs in the order they were given, so a loaded `MergeJoin(left, right)` or `SemiJoin(left, right)` takes `left` first, as the live job did. -A file saved by an Orcapod older than this rule (before ITL-1417) that holds one of these -two operators over two inputs cannot say which input comes first, and loading it raises -`ValueError`; build the job from its code and save it again. A file whose operators are all -commutative (`Join`, `Rejoin`) loads as before. +A file saved by an Orcapod older than this rule (before ITL-1417) cannot say which input +comes first, so loading it raises `ValueError` when it holds an operator over two or more +inputs that is not known to be commutative (`MergeJoin`, `SemiJoin`, or an operator that +cannot be rebuilt in this process); build the job from its code and save it again. A file +whose multi-input operators are all commutative (`Join`, `Rejoin`) loads as before. ## How it connects to other concepts diff --git a/docs/dev/design_issues/ITL-1417-AO1.md b/docs/dev/design_issues/ITL-1417-AO1.md index 8816722d9..4c2d9be19 100644 --- a/docs/dev/design_issues/ITL-1417-AO1.md +++ b/docs/dev/design_issues/ITL-1417-AO1.md @@ -16,6 +16,10 @@ Found while building ITL-1387. **Fix:** every saved operator node lists its inputs' keys in argument order under `inputs` (format 0.4.0, added within the version), and both loaders build an operator's inputs from -that list. A file saved before has no list: an ordered operator over two different inputs is -refused at load (its order cannot be known), a commutative one loads as before. +that list. A file saved before has no list: an operator over two or more different inputs +loads only when it is positively known to be commutative (available, and its +`argument_symmetry` on the rebuilt inputs is a flat `frozenset` of them); anything else is +refused at load (its order cannot be known). Review of the PR (Codex): the check asks the +symmetry of the rebuilt streams, not hash strings; a nested group and a read-only operator +are refused; a read-only node keeps its inputs. `tests/test_pipeline/test_loaded_argument_order.py`. diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index abc6fbc5f..2d81d8d0d 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -89,6 +89,8 @@ def __init__( """ super().__init__(name=name, tracker_manager=tracker_manager) self._auto_compile = auto_compile + # A loaded blueprint's operator input keys in argument order (ITL-1417). + self._loaded_input_keys: dict[str, list[str]] = {} # ------------------------------------------------------------------ # Context manager — respects auto_compile flag @@ -327,7 +329,7 @@ def load(cls, path: str | Path) -> "Pipeline": OPERATOR_INPUTS_KEY, PIPELINE_FORMAT_VERSION, require_current_format, - require_known_argument_order, + require_positively_commutative, require_nullability_records, arrow_schema_from_texts, deserialize_schema, @@ -368,6 +370,8 @@ def load(cls, path: str | Path) -> "Pipeline": upstream_map.setdefault(down_hash, []).append(up_hash) 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]] = {} for node_hash in topo_order: descriptor = nodes_data.get(node_hash) @@ -567,10 +571,11 @@ def load(cls, path: str | Path) -> "Pipeline": exc, ) operator = None - if saved_inputs is None and operator is not None: - require_known_argument_order( - operator, up_hashes, descriptor.get("label") + if saved_inputs is None: + require_positively_commutative( + operator, upstream_nodes, up_hashes, descriptor.get("label") ) + loaded_input_keys[node_hash] = list(up_hashes) node = OperatorNode.from_descriptor( descriptor, operator=operator, @@ -608,6 +613,7 @@ def load(cls, path: str | Path) -> "Pipeline": if isinstance(descriptor.get("output_schema"), dict) } pipeline._persistent_node_map = dict(reconstructed) + pipeline._loaded_input_keys = loaded_input_keys nodes_by_label: dict[str, GraphNode] = {} for node in reconstructed.values(): diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 127dfccc3..514107360 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -1808,7 +1808,6 @@ def load( # is the source of truth. expected_rows: dict[str, int] = run_block.get("expected_rows", {}) - bp_key_of = {id(bp): h for h, bp in pipeline._persistent_node_map.items()} for node_hash in _nx.topological_sort(job._hash_graph): bp_node = pipeline._persistent_node_map.get(node_hash) if bp_node is None: @@ -1842,9 +1841,12 @@ def load( elif isinstance(bp_node, _OperatorNode): descriptor = getattr(bp_node, "_descriptor", None) or {} - # The inputs in the blueprint node's order, its argument order - # (ITL-1417); a graph's predecessors do not keep that order. - preds = [bp_key_of[id(up)] for up in bp_node.upstreams] + # The inputs in argument order, as the file gives them (ITL-1417); a + # graph's predecessors do not keep that order. A read-only node keeps + # its inputs too, as before. + preds = pipeline._loaded_input_keys.get( # pyright: ignore[reportPrivateUsage] # set by Pipeline.load for this loader + node_hash + ) or list(job._hash_graph.predecessors(node_hash)) input_streams = tuple( job._persistent_node_map[p] for p in preds diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index 933e23d09..cd030054f 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -42,7 +42,7 @@ # a load refuses a file without them (ITL-1159, ITL-1019). # Each operator node lists its inputs in argument order under ``inputs`` # (ITL-1417, added within 0.4.0: a file without it still loads, except an -# ordered operator over two inputs, which is refused). +# operator over two or more inputs not known to be commutative, refused). # A file of an earlier format (0.1.0 to 0.3.0) is refused at load, never read in its # old grammar: load and save had not been used in production (developer, 2026-11-21). # Taking such files to the current format is the migration tool's work (ITL-1048). @@ -55,36 +55,52 @@ OPERATOR_INPUTS_KEY = "inputs" -def require_known_argument_order( - operator: Any, input_keys: list[str], label: str | None +def require_positively_commutative( + operator: Any, + input_streams: tuple[Any, ...], + input_keys: list[str], + label: str | None, ) -> None: - """Refuse to rebuild an ordered operator whose argument order a file does not give. + """Accept an operator of a legacy file only when it is known to be commutative. A file saved before ``OPERATOR_INPUTS_KEY`` was written lists an operator's inputs only through its edges, in the order the steps were recorded (ITL-1417). - For a commutative operator (``Join``) the order does not matter; for an ordered - one (``MergeJoin``, ``SemiJoin``) over two different inputs it cannot be known, so - the file is refused rather than read with a guessed order. + Its argument order cannot be known, so an operator node with two or more + different inputs is accepted only when it is positively known to be fully + commutative: the operator is available, and ``argument_symmetry``, called as its + contract requires (on the rebuilt input streams), returns a flat ``frozenset`` of + exactly those inputs. Anything else (the call raises, a tuple, a nested group, an + operator that is not available, an input not restored) is refused: when in doubt, + refuse. Args: - operator: The rebuilt operator. + operator: The rebuilt operator, or ``None`` when it is not available. + input_streams: The rebuilt input nodes. input_keys: The keys of its inputs, in edge order. label: The node's label, for the message. Raises: - ValueError: If the operator takes its inputs in order and the file does not - say which comes first. + ValueError: If the operator is not positively known to be commutative. """ if len(set(input_keys)) < 2: return - if not isinstance(operator.argument_symmetry(tuple(input_keys)), tuple): - return - raise ValueError( - f"The saved job's node {label!r} ({type(operator).__name__}) takes its inputs " - "in order, and the file does not say which comes first: it was saved before " - "Orcapod wrote each operator's inputs in argument order (ITL-1417), so loading " - "it could swap them. Build the job from its code and save it again." + refusal = ValueError( + f"The saved job's node {label!r} has several inputs, and the file does not say " + "in which order: it was saved before Orcapod wrote each operator's inputs in " + "argument order (ITL-1417), and the operator is not known to be commutative, " + "so loading it could swap them. Build the job from its code and save it again." ) + if operator is None or len(input_streams) != len(input_keys): + raise refusal + try: + symmetry = operator.argument_symmetry(input_streams) + except Exception as exc: + raise refusal from exc + if not isinstance(symmetry, frozenset): + raise refusal + members = cast("frozenset[Any]", symmetry) + if {id(member) for member in members} != {id(stream) for stream in input_streams}: + raise refusal def require_current_format(version: str, current: str) -> None: diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index 15b579000..4720f3a00 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -4,8 +4,9 @@ with an operator's inputs in the order its edges were listed, which follows the order the steps were recorded in: with another step over the second input recorded first, a loaded ``MergeJoin(left, right)`` ran as ``MergeJoin(right, left)``. The saved file now -lists each operator's inputs in argument order (``inputs``), and a file saved before -that is refused when it holds an ordered operator over two inputs. +lists each operator's inputs in argument order (``inputs``). A file saved before that (a +legacy file) loads an operator over two or more inputs only when the operator is +positively known to be commutative; anything else is refused. """ from __future__ import annotations @@ -13,20 +14,24 @@ import asyncio import inspect import json -from collections.abc import Callable +import subprocess +import sys +from collections.abc import Callable, Collection from pathlib import Path from typing import Any import pytest -from orcapod import PipelineJob, operators, sources -from orcapod.core.operators import Join, MergeJoin, Rejoin, SemiJoin +from orcapod import Pipeline, PipelineJob, operators, sources +from orcapod.core.operators import Index, Join, MergeJoin, Rejoin, SemiJoin from orcapod.core.operators.base import BinaryOperator, NonZeroInputOperator from orcapod.databases import DeltaTableDatabase -from orcapod.pipeline.serialization import OPERATOR_INPUTS_KEY +from orcapod.pipeline.serialization import OPERATOR_INPUTS_KEY, register_operator +from orcapod.types import CacheMode ORDERED = {"MergeJoin", "SemiJoin"} COMMUTATIVE = {"Join", "Rejoin"} +LEGACY_REFUSAL = "does not say in which order" def test_every_multi_input_operator_is_classified() -> None: @@ -49,47 +54,48 @@ def test_every_multi_input_operator_is_classified() -> None: assert commutative == COMMUTATIVE -def _csv(tmp_path: Path, name: str, rows: str) -> Any: +# ── inputs: two tags, two data columns (several-items rule) ────────────────── + + +def _csv(tmp_path: Path, name: str, header: str, rows: str) -> Any: path = tmp_path / f"{name}.csv" - path.write_text(rows) + path.write_text(f"id,key,{header}\n{rows}") return sources.CSVSource( - str(path), tag_columns=["id"], tag_only_columns=True, source_id=name + str(path), tag_columns=["id", "key"], tag_only_columns=True, source_id=name ) def _inputs(tmp_path: Path) -> dict[str, Any]: - """Three CSV sources over one key; ``left`` and ``right`` share the data column - ``x``, ``third`` has its own.""" + """``a`` and ``b`` share both data columns (``x``, ``y``); ``c`` has its own.""" return { - "left": _csv(tmp_path, "left", "id,x,y\n1,1,10\n2,2,20\n3,3,30\n"), - "right": _csv(tmp_path, "right", "id,x,z\n1,100,0\n2,101,0\n"), - "third": _csv(tmp_path, "third", "id,w\n1,7\n2,8\n"), + "a": _csv(tmp_path, "a", "x,y", "1,10,1,10\n2,20,2,20\n3,30,3,30\n"), + "b": _csv(tmp_path, "b", "x,y", "1,10,100,1000\n2,20,101,1001\n"), + "c": _csv(tmp_path, "c", "z,w", "1,10,42,43\n2,20,44,45\n"), } -# Each case: the operator's name and the step over the inputs. ``left`` and ``right`` -# are the two inputs of a binary operator, in argument order; the order is visible in -# the rows (MergeJoin's lists, SemiJoin's kept side). -CASES: dict[str, Callable[[dict[str, Any]], Any]] = { - "MergeJoin": lambda s: MergeJoin()(s["left"], s["right"], label="step"), - "SemiJoin": lambda s: SemiJoin()(s["left"], s["right"], label="step"), - "Join": lambda s: Join()( - s["left"].select_data_columns(["y"]), s["third"], label="step" +# Each case builds ``step`` from its first and second argument; the order is visible +# in the rows (MergeJoin's lists, SemiJoin's kept side). +CASES: dict[str, Callable[[Any, Any, dict[str, Any]], Any]] = { + "MergeJoin": lambda first, second, s: MergeJoin()(first, second, label="step"), + "SemiJoin": lambda first, second, s: SemiJoin()(first, second, label="step"), + "Join": lambda first, second, s: Join()( + first.select_data_columns(["y"]), s["c"], label="step" ), - "Rejoin": lambda s: Rejoin()( - s["left"].select_data_columns(["x"]), - s["left"].select_data_columns(["y"]), + "Rejoin": lambda first, second, s: Rejoin()( + first.select_data_columns(["x"]), + first.select_data_columns(["y"]), label="step", ), # Three inputs: a commutative Join of three, then an ordered MergeJoin over it. - "Join3_then_MergeJoin": lambda s: MergeJoin()( + "Join3_then_MergeJoin": lambda first, second, s: MergeJoin()( Join()( - s["left"].select_data_columns(["x"]), - s["third"], - s["left"].select_data_columns(["y"]), + first.select_data_columns(["x"]), + s["c"], + first.select_data_columns(["y"]), label="joined", ), - s["right"].select_data_columns(["x"]), + second.select_data_columns(["x"]), label="step", ), } @@ -100,18 +106,26 @@ def _rows(table: Any) -> list[str]: def _build( - tmp_path: Path, case: str, other_use_first: bool + tmp_path: Path, case: str, other_use_first: bool, reverse: bool = False ) -> tuple[PipelineJob, Path]: - """The job, with another step over ``right`` recorded before or after the case.""" + """The job, with another step over the second argument recorded before or after + the case, and the arguments in either order; ``step`` stores its rows.""" streams = _inputs(tmp_path) + first, second = ( + (streams["b"], streams["a"]) if reverse else (streams["a"], streams["b"]) + ) db_path = tmp_path / "db" - job = PipelineJob(name="ordered", database=DeltaTableDatabase(db_path)) + db = DeltaTableDatabase(db_path) + job = PipelineJob(name="ordered", database=db) with job: if other_use_first: - streams["right"].select_data_columns(["z"], label="other_use") - CASES[case](streams) + second.select_data_columns(["y"], label="other_use") + CASES[case](first, second, streams) if not other_use_first: - streams["right"].select_data_columns(["z"], label="other_use") + second.select_data_columns(["y"], label="other_use") + job.nodes["step"].attach_databases( + pipeline_database=db.at("ordered"), cache_mode=CacheMode.LOG + ) return job, db_path @@ -122,67 +136,97 @@ def _run(job: PipelineJob, mode: str, **kwargs: Any) -> None: asyncio.run(job.run_async(**kwargs)) +def _identity(node: Any) -> tuple[Any, ...]: + return (node.content_hash(), node.pipeline_hash()) + + @pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["a_b", "b_a"]) @pytest.mark.parametrize("other_use_first", [False, True]) @pytest.mark.parametrize("case", sorted(CASES)) -def test_a_loaded_job_gives_the_rows_of_the_live_job( - case: str, other_use_first: bool, mode: str, tmp_path: Path +def test_a_loaded_job_gives_the_rows_and_identity_of_the_live_job( + case: str, other_use_first: bool, reverse: bool, mode: str, tmp_path: Path ) -> None: - """Live rows equal the rows of the saved and loaded job run with - ``load_only=True``, whatever order the steps were recorded in.""" - job, db_path = _build(tmp_path, case, other_use_first) + """Live rows (with system tags and source info) equal the rows of the saved and + loaded job run with ``load_only=True``, and so do its content hash, pipeline hash + and stored table (read through ``as_source``, which reads the stored path), + whatever order the steps were recorded in and the arguments given in.""" + job, db_path = _build(tmp_path, case, other_use_first, reverse) _run(job, mode) - live = _rows(job.step.as_table()) + live_rows = _rows(job.step.as_table(all_info=True)) + live_stored = _rows(job.step.as_source().as_table()) job.save(tmp_path / "job.json") loaded = PipelineJob.load( tmp_path / "job.json", database=DeltaTableDatabase(db_path) ) _run(loaded, mode, load_only=True) - assert _rows(loaded.step.as_table()) == live + assert _rows(loaded.step.as_table(all_info=True)) == live_rows + assert _identity(loaded.step) == _identity(job.step) + assert _rows(loaded.step.as_source().as_table()) == live_stored +@pytest.mark.parametrize("reverse", [False, True], ids=["a_b", "b_a"]) @pytest.mark.parametrize("other_use_first", [False, True]) @pytest.mark.parametrize("case", ["MergeJoin", "SemiJoin"]) def test_the_saved_file_lists_an_operators_inputs_in_argument_order( - case: str, other_use_first: bool, tmp_path: Path + case: str, other_use_first: bool, reverse: bool, tmp_path: Path ) -> None: - job, _ = _build(tmp_path, case, other_use_first) + job, _ = _build(tmp_path, case, other_use_first, reverse) job.save(tmp_path / "job.json") nodes = json.loads((tmp_path / "job.json").read_text())["pipeline"]["nodes"] label_of = {key: node["label"] for key, node in nodes.items()} step = next(node for node in nodes.values() if node["label"] == "step") - assert [label_of[key] for key in step[OPERATOR_INPUTS_KEY]] == ["left", "right"] + expected = ["b", "a"] if reverse else ["a", "b"] + assert [label_of[key] for key in step[OPERATOR_INPUTS_KEY]] == expected + + +def test_a_loaded_file_saves_again_with_the_same_inputs(tmp_path: Path) -> None: + """Saving a loaded job again writes the same ``inputs`` and edges.""" + job, db_path = _build(tmp_path, "MergeJoin", True) + job.save(tmp_path / "first.json") + loaded = PipelineJob.load( + tmp_path / "first.json", database=DeltaTableDatabase(db_path) + ) + loaded.save(tmp_path / "second.json") + first = json.loads((tmp_path / "first.json").read_text())["pipeline"] + second = json.loads((tmp_path / "second.json").read_text())["pipeline"] + assert second["edges"] == first["edges"] + assert { + key: node.get(OPERATOR_INPUTS_KEY) for key, node in second["nodes"].items() + } == {key: node.get(OPERATOR_INPUTS_KEY) for key, node in first["nodes"].items()} + +# ── legacy files (saved before ITL-1417: main's saved form, no ``inputs``) ─── -def _strip_inputs(path: Path) -> None: - """Make the file one saved before ITL-1417: no ``inputs`` on any operator.""" + +def _strip_inputs(path: Path, *, job_file: bool = True) -> None: + """Make the file one saved before ITL-1417 (main's saved form): no ``inputs``.""" data = json.loads(path.read_text()) - for node in data["pipeline"]["nodes"].values(): + nodes = data["pipeline"]["nodes"] if job_file else data["nodes"] + for node in nodes.values(): node.pop(OPERATOR_INPUTS_KEY, None) path.write_text(json.dumps(data)) @pytest.mark.parametrize("other_use_first", [False, True]) @pytest.mark.parametrize("case", ["MergeJoin", "SemiJoin", "Join3_then_MergeJoin"]) -def test_a_file_saved_before_the_fix_with_an_ordered_operator_is_refused( +def test_a_legacy_file_with_an_ordered_operator_is_refused( case: str, other_use_first: bool, tmp_path: Path ) -> None: - """An ordered operator over two inputs in a file without ``inputs``: the order - cannot be known, so the load refuses rather than guess.""" job, db_path = _build(tmp_path, case, other_use_first) job.save(tmp_path / "job.json") _strip_inputs(tmp_path / "job.json") - with pytest.raises(ValueError, match="does not say which comes first"): + with pytest.raises(ValueError, match=LEGACY_REFUSAL): PipelineJob.load(tmp_path / "job.json", database=DeltaTableDatabase(db_path)) @pytest.mark.parametrize("other_use_first", [False, True]) @pytest.mark.parametrize("case", ["Join", "Rejoin"]) -def test_a_file_saved_before_the_fix_with_commutative_operators_still_loads( +def test_a_legacy_file_with_commutative_operators_still_loads( case: str, other_use_first: bool, tmp_path: Path ) -> None: - """A commutative operator does not depend on its input order: such an old file - loads and gives the live rows.""" + """A commutative operator does not depend on its input order: such a legacy file + loads, as on main, and gives the live rows.""" job, db_path = _build(tmp_path, case, other_use_first) job.run() live = _rows(job.step.as_table()) @@ -195,17 +239,212 @@ def test_a_file_saved_before_the_fix_with_commutative_operators_still_loads( assert _rows(loaded.step.as_table()) == live -def test_a_loaded_file_saves_again_with_the_same_inputs(tmp_path: Path) -> None: - """Saving a loaded job again writes the same ``inputs`` and edges.""" - job, db_path = _build(tmp_path, "MergeJoin", True) - job.save(tmp_path / "first.json") +class SchemaAwareJoin(Join): + """A commutative custom operator that inspects its input streams, as the + ``argument_symmetry`` contract allows (Codex review of PR 513, finding 1).""" + + def argument_symmetry(self, streams: Collection[Any]) -> Any: + for stream in streams: + stream.output_schema() + return super().argument_symmetry(streams) + + +class SchemaAwareSemiJoin(SemiJoin): + """An ordered custom operator that inspects its input streams (finding 1).""" + + def argument_symmetry(self, streams: Collection[Any]) -> Any: + for stream in streams: + stream.output_schema() + return super().argument_symmetry(streams) + + +class NestedMergeJoin(MergeJoin): + """An ordered operator stating its order as a nested group, which the + ``argument_symmetry`` contract allows (finding 2).""" + + def argument_symmetry(self, streams: Collection[Any]) -> Any: + return frozenset((tuple(streams),)) + + +register_operator("SchemaAwareJoin", SchemaAwareJoin) +register_operator("SchemaAwareSemiJoin", SchemaAwareSemiJoin) +register_operator("NestedMergeJoin", NestedMergeJoin) + + +def _legacy_custom( + tmp_path: Path, make: Callable[[dict[str, Any]], Any], blueprint: bool +) -> tuple[Path, Path, PipelineJob]: + streams = _inputs(tmp_path) + db_path = tmp_path / "db" + job = PipelineJob(name="custom", database=DeltaTableDatabase(db_path)) + with job: + streams["b"].select_data_columns(["y"], label="other_use") + make(streams) + job.run() + path = tmp_path / ("pipeline.json" if blueprint else "job.json") + if blueprint: + job.pipeline.save(path) + else: + job.save(path) + _strip_inputs(path, job_file=not blueprint) + return path, db_path, job + + +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +def test_a_legacy_custom_commutative_operator_that_reads_its_streams_loads( + blueprint: bool, tmp_path: Path +) -> None: + """Finding 1: the symmetry is asked on the rebuilt input streams, never on hash + strings, so a commutative operator that inspects them loads as on main.""" + path, db_path, job = _legacy_custom( + tmp_path, + lambda s: SchemaAwareJoin()( + s["a"].select_data_columns(["y"]), s["c"], label="step" + ), + blueprint, + ) + if blueprint: + assert "step" in Pipeline.load(path).nodes + else: + loaded = PipelineJob.load(path, database=DeltaTableDatabase(db_path)) + loaded.run(load_only=True) + assert _rows(loaded.step.as_table()) == _rows(job.step.as_table()) + + +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +@pytest.mark.parametrize( + "make", + [ + pytest.param( + lambda s: SchemaAwareSemiJoin()(s["a"], s["b"], label="step"), + id="ordered_reads_streams", + ), + pytest.param( + lambda s: NestedMergeJoin()(s["a"], s["b"], label="step"), id="nested" + ), + ], +) +def test_a_legacy_custom_operator_not_known_commutative_is_refused( + make: Callable[[dict[str, Any]], Any], blueprint: bool, tmp_path: Path +) -> None: + """Findings 1 and 2: an ordered operator that inspects its streams, or one stating + its order as a nested group, is refused with the migration error (never an + ``AttributeError``, never loaded with a guessed order).""" + path, db_path, _ = _legacy_custom(tmp_path, make, blueprint) + with pytest.raises(ValueError, match=LEGACY_REFUSAL): + if blueprint: + Pipeline.load(path) + else: + PipelineJob.load(path, database=DeltaTableDatabase(db_path)) + + +_WRITER_ONLY = """from dataclasses import dataclass +from pathlib import Path +import sys +from orcapod import PipelineJob, function_pod, sources +from orcapod.core.operators import {operator} +from orcapod.databases import DeltaTableDatabase + + +@dataclass +class WriterOnly: + value: int + + +@function_pod(output_keys=("payload", "x")) +def make_payload(x: int) -> tuple[WriterOnly, int]: + return WriterOnly(x), x + + +root = Path(sys.argv[1]) +(root / "a.csv").write_text("id,key,x\\n1,10,1\\n2,20,2\\n") +(root / "b.csv").write_text("id,key,y\\n1,10,100\\n2,20,101\\n") +a, b = (sources.CSVSource(str(root / f"{{n}}.csv"), tag_columns=["id", "key"], + tag_only_columns=True, source_id=n) for n in ("a", "b")) +job = PipelineJob(name="unknown", database=DeltaTableDatabase(root / "store")) +with job: + b.select_data_columns(["y"], label="other_use") + {operator}()(make_payload.pod(a, label="producer"), b, label="step") +job.run() +job.save(root / "job.json") +job.pipeline.save(root / "pipeline.json") +""" + + +def _write_unregistered(tmp_path: Path, operator: str) -> None: + script = tmp_path / "writer.py" + script.write_text(_WRITER_ONLY.format(operator=operator)) + subprocess.run([sys.executable, str(script), str(tmp_path)], check=True) + + +@pytest.mark.parametrize("operator", ["MergeJoin", "Join"]) +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +def test_a_legacy_operator_kept_read_only_is_refused( + operator: str, blueprint: bool, tmp_path: Path +) -> None: + """Finding 3: an operator over a type this process has not registered is kept as + a read-only stub, so nothing proves it commutative: a legacy file is refused (job + file and standalone blueprint), even for a Join.""" + _write_unregistered(tmp_path, operator) + path = tmp_path / ("pipeline.json" if blueprint else "job.json") + _strip_inputs(path, job_file=not blueprint) + with pytest.raises(ValueError, match=LEGACY_REFUSAL): + if blueprint: + Pipeline.load(path) + else: + PipelineJob.load(path) + + +@pytest.mark.parametrize("blueprint", [False, True], ids=["job", "blueprint"]) +def test_a_current_file_with_an_operator_kept_read_only_loads( + blueprint: bool, tmp_path: Path +) -> None: + """The same files with ``inputs`` load: the order is known.""" + _write_unregistered(tmp_path, "MergeJoin") + path = tmp_path / ("pipeline.json" if blueprint else "job.json") + loaded = Pipeline.load(path) if blueprint else PipelineJob.load(path) + assert "step" in loaded.nodes + + +@pytest.mark.parametrize("reverse", [False, True], ids=["a_b", "b_a"]) +def test_a_loaded_read_only_node_keeps_its_inputs( + reverse: bool, tmp_path: Path +) -> None: + """Finding 4: a node kept read-only on load (``Index``, ITL-1326) still names its + input, as on main; an ordered node names its inputs in argument order.""" + streams = _inputs(tmp_path) + first, second = ( + (streams["b"], streams["a"]) if reverse else (streams["a"], streams["b"]) + ) + db_path = tmp_path / "db" + job = PipelineJob(name="ro", database=DeltaTableDatabase(db_path)) + with job: + merged = MergeJoin()(first, second, label="merged") + Index("x", 0)(merged, label="indexed") + job.run() + job.save(tmp_path / "job.json") loaded = PipelineJob.load( - tmp_path / "first.json", database=DeltaTableDatabase(db_path) + tmp_path / "job.json", database=DeltaTableDatabase(db_path) ) - loaded.save(tmp_path / "second.json") - first = json.loads((tmp_path / "first.json").read_text())["pipeline"] - second = json.loads((tmp_path / "second.json").read_text())["pipeline"] - assert second["edges"] == first["edges"] - assert { - key: node.get(OPERATOR_INPUTS_KEY) for key, node in second["nodes"].items() - } == {key: node.get(OPERATOR_INPUTS_KEY) for key, node in first["nodes"].items()} + assert [up.label for up in loaded.indexed.upstreams] == ["merged"] + assert [up.label for up in loaded.merged.upstreams] == ( + ["b", "a"] if reverse else ["a", "b"] + ) + + +@pytest.mark.parametrize("mode", ["sync", "async"]) +@pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) +def test_one_stream_given_twice_fails_to_run_in_a_job( + operator: type, mode: str, tmp_path: Path +) -> None: + """Finding 5 (pre-existing on main, pinned; filed by the coordinator): 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.""" + a = _inputs(tmp_path)["a"] + assert operator()(a, a).as_table().num_rows == 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) From dc4a04d2717c81f9b91ee6730de29e47efe20bfb Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:18:33 -0800 Subject: [PATCH 3/4] test(pipeline): name ITL-1419 in the pinned repeated-input test (ITL-1417) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_loaded_argument_order.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index 4720f3a00..aa0738785 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -437,7 +437,7 @@ def test_a_loaded_read_only_node_keeps_its_inputs( def test_one_stream_given_twice_fails_to_run_in_a_job( operator: type, mode: str, tmp_path: Path ) -> None: - """Finding 5 (pre-existing on main, pinned; filed by the coordinator): a job's + """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.""" From 8e2edf4e89214ab2fc051b879e766f0024bc647d Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 22 Nov 2026 21:36:01 -0800 Subject: [PATCH 4/4] fix(pipeline): refuse a legacy binary operator given one stream twice (ITL-1417) A file saved before 'inputs' holds one edge for SemiJoin()(a, a); it was rebuilt with one input and failed with a generic arity error. It is refused with the migration error (CodeRabbit on PR 513). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/serialization.py | 18 ++++++++++++++++-- .../test_loaded_argument_order.py | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/src/orcapod/pipeline/serialization.py b/src/orcapod/pipeline/serialization.py index cd030054f..5d12fff68 100644 --- a/src/orcapod/pipeline/serialization.py +++ b/src/orcapod/pipeline/serialization.py @@ -69,7 +69,8 @@ def require_positively_commutative( different inputs is accepted only when it is positively known to be fully commutative: the operator is available, and ``argument_symmetry``, called as its contract requires (on the rebuilt input streams), returns a flat ``frozenset`` of - exactly those inputs. Anything else (the call raises, a tuple, a nested group, an + exactly those inputs. A binary operator with other than two edges (one stream + given twice) cannot have its inputs restored and is refused too. Anything else (the call raises, a tuple, a nested group, an operator that is not available, an input not restored) is refused: when in doubt, refuse. @@ -82,7 +83,13 @@ def require_positively_commutative( Raises: ValueError: If the operator is not positively known to be commutative. """ - if len(set(input_keys)) < 2: + from orcapod.core.operators.base import BinaryOperator + + # 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 + # PR 513): refused like an unknown order, never rebuilt with one input. + one_input_of_two = isinstance(operator, BinaryOperator) and len(input_keys) != 2 + if len(set(input_keys)) < 2 and not one_input_of_two: return refusal = ValueError( f"The saved job's node {label!r} has several inputs, and the file does not say " @@ -90,6 +97,13 @@ def require_positively_commutative( "argument order (ITL-1417), and the operator is not known to be commutative, " "so loading it could swap them. Build the job from its code and save it again." ) + if one_input_of_two: + raise ValueError( + f"The saved job's node {label!r} takes two inputs, and the file does not " + "say in which order nor restore both: it was saved before Orcapod wrote " + "each operator's inputs in argument order (ITL-1417), and it holds one edge " + "for one stream given twice. Build the job from its code and save it again." + ) if operator is None or len(input_streams) != len(input_keys): raise refusal try: diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index aa0738785..af154b56c 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -448,3 +448,21 @@ def test_one_stream_given_twice_fails_to_run_in_a_job( operator()(a, a, label="repeat") with pytest.raises((ValueError, IndexError)): _run(job, mode) + + +@pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) +def test_a_legacy_binary_operator_over_one_stream_is_refused( + operator: type, tmp_path: Path +) -> None: + """CodeRabbit on PR 513: a legacy file holds one edge for ``SemiJoin()(a, a)`` (an + edge list cannot repeat an edge), so the operator would be rebuilt with one input + where it takes two. Its inputs cannot be restored, so the load refuses.""" + a = _inputs(tmp_path)["a"] + db_path = tmp_path / "db" + job = PipelineJob(name="repeat", database=DeltaTableDatabase(db_path)) + with job: + operator()(a, a, label="repeat") + job.save(tmp_path / "job.json") + _strip_inputs(tmp_path / "job.json") + with pytest.raises(ValueError, match=LEGACY_REFUSAL): + PipelineJob.load(tmp_path / "job.json", database=DeltaTableDatabase(db_path))