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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions changelog.d/ITL-1417.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
### 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 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.
8 changes: 8 additions & 0 deletions docs/concepts/pipeline-job.md
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,14 @@ 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) 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

- A job records applications of [Function Pods](function-pods.md) and
Expand Down
25 changes: 25 additions & 0 deletions docs/dev/design_issues/ITL-1417-AO1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
## `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 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`.
37 changes: 36 additions & 1 deletion src/orcapod/pipeline/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -130,6 +132,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,
Expand Down Expand Up @@ -168,6 +171,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
Expand Down Expand Up @@ -262,6 +266,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:
Expand Down Expand Up @@ -308,8 +326,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_positively_commutative,
require_nullability_records,
arrow_schema_from_texts,
deserialize_schema,
Expand Down Expand Up @@ -350,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)
Expand Down Expand Up @@ -484,7 +506,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, [])
)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
upstream_nodes = tuple(
reconstructed[h] for h in up_hashes if h in reconstructed
)
Expand Down Expand Up @@ -542,6 +571,11 @@ def load(cls, path: str | Path) -> "Pipeline":
exc,
)
operator = None
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,
Expand Down Expand Up @@ -579,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():
Expand Down
7 changes: 6 additions & 1 deletion src/orcapod/pipeline/job.py
Original file line number Diff line number Diff line change
Expand Up @@ -1841,7 +1841,12 @@ 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 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
Expand Down
71 changes: 71 additions & 0 deletions src/orcapod/pipeline/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,82 @@
# 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
# 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).
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_positively_commutative(
operator: Any,
input_streams: tuple[Any, ...],
input_keys: list[str],
label: str | None,
) -> None:
"""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).
Its argument order cannot be known, so an operator node with two or more
different inputs is accepted only when it is positively known to be fully
commutative: the operator is available, and ``argument_symmetry``, called as its
contract requires (on the rebuilt input streams), returns a flat ``frozenset`` of
exactly those inputs. A binary operator with other than two edges (one stream
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.

Args:
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 is not positively known to be commutative.
"""
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 "
"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 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:
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:
"""Refuse a saved file whose format version is not the one this Orcapod writes.
Expand Down
Loading
Loading