From 310c45d89fc3964435aa367482733030a9d4144f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:02:06 -0800 Subject: [PATCH 1/5] fix(pipeline): refuse shadowed job steps (ITL-1767) --- changelog.d/ITL-1767.md | 3 + docs/concepts/pipeline-job.md | 5 + .../design_issues/ITL-1767-PJCOLLISION1.md | 16 ++ src/orcapod/pipeline/base.py | 4 + src/orcapod/pipeline/job.py | 49 +++- .../test_pipeline/test_shadowed_job_steps.py | 211 ++++++++++++++++++ 6 files changed, 281 insertions(+), 7 deletions(-) create mode 100644 changelog.d/ITL-1767.md create mode 100644 docs/dev/design_issues/ITL-1767-PJCOLLISION1.md create mode 100644 tests/test_pipeline/test_shadowed_job_steps.py diff --git a/changelog.d/ITL-1767.md b/changelog.d/ITL-1767.md new file mode 100644 index 000000000..9d3bb2f66 --- /dev/null +++ b/changelog.d/ITL-1767.md @@ -0,0 +1,3 @@ +### Changed + +- Job compilation now rejects distinct steps that would share one execution graph vertex and lose one step's current-run rows, including a direct self-join alongside a join over two slots bound to the same source (ITL-1767). diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 677cfaa2a..5d4569603 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -457,6 +457,11 @@ print(job_c.nodes["bmi"].as_table().num_rows) Every job also carries its blueprint as `job.pipeline`. +## Job graph limitations + +Orcapod rejects distinct steps that would share one execution graph vertex and lose a step’s current-run rows (ITL-1767), so put a direct self-join and its two-slot equivalent in separate jobs or use just one form. + + ## Seeing the graph !!! caution "In development" diff --git a/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md new file mode 100644 index 000000000..0f2384128 --- /dev/null +++ b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md @@ -0,0 +1,16 @@ +## `src/orcapod/pipeline/job.py` — job execution graph identity + +### PJCOLLISION1 — Equal steps in separate slots share one execution vertex +**Status:** open +**Severity:** high +**Issue:** ITL-1767 + +The capture graph keeps steps over different named source declarations. After those +slots are bound, a direct self-join and a two-slot join can compare equal as keys +in the execution graph, and a step below either join can do the same. Both steps +are visible in `job.nodes`, but only one receives current-run rows. Identical +unary pods over different slots bound to the same source have the same problem. + +Job compilation now refuses distinct steps that share an execution vertex. +Sharing the source itself still works. The follow-up is to let both steps run +and read their rows independently. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index a65c271dc..6b57b710d 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -718,6 +718,7 @@ def compile(self) -> None: i += 1 node_map = self._ordered_node_map(node_map, self._hash_graph) + self._validate_compiled_nodes(node_map.values()) self._persistent_node_map = node_map self._nodes.clear() self._nodes.update((node.label, node) for node in node_map.values()) @@ -761,6 +762,9 @@ def compile(self) -> None: self._compiled = True + def _validate_compiled_nodes(self, nodes: Iterable[NodeT]) -> None: + """Check the newly compiled nodes before publishing them.""" + @staticmethod def _ordered_node_map( nodes: dict[str, Any], graph: nx.DiGraph[str] diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index af81177ee..d122ba809 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -104,6 +104,24 @@ def _backend(database: WriteDatabase) -> WriteDatabase: return database +def _refuse_shadowed_steps(nodes: Iterable[JobNode]) -> None: + """Refuse distinct steps that would share an object-keyed DAG vertex (ITL-1767).""" + steps: dict[JobNode, JobNode] = {} + for node in nodes: + # Source slots can safely read the same source. Steps hold their own run + # rows and each needs a vertex to receive them. Use the DAG's own Python + # key semantics: equal content hashes alone do not imply equal keys. + if isinstance(node, SourceJobNode): + continue + previous = steps.setdefault(node, node) + if previous is not node: + raise ValueError( + f"Steps {previous.label!r} and {node.label!r} have the same " + "identity in this job, so one would read the other's rows. " + "Put them in separate jobs or use only one of the two forms (ITL-1767)." + ) + + def _supports_attachment_enrollment(database: WriteDatabase) -> bool: """Recognize stores whose durable rows we can distinguish from pending ones.""" return isinstance( @@ -451,6 +469,10 @@ def compile(self) -> None: If ``_database`` is set, distributes databases to all function and operator job nodes. + + Raises: + ValueError: If distinct steps would share a vertex in the job graph + and one would lose its current-run rows (ITL-1767). """ previous_slots = [ node @@ -484,6 +506,9 @@ def compile(self) -> None: if self._database is not None: self._distribute_databases() + def _validate_compiled_nodes(self, nodes: Iterable[JobNode]) -> None: + _refuse_shadowed_steps(nodes) + # ------------------------------------------------------------------ # compiled_pipeline — lazy cache # ------------------------------------------------------------------ @@ -599,7 +624,8 @@ def from_pipeline( A new ``PipelineJob`` ready to run (or ``bind()`` further). Raises: - ValueError: If *pipeline* has not been compiled. + ValueError: If *pipeline* has not been compiled or the supplied + bindings would make distinct steps share a job graph vertex (ITL-1767). """ from orcapod.core.nodes.source_node import SourceNodeBase @@ -636,6 +662,7 @@ def from_pipeline( # Bind concrete sources and distribute databases. if bound_sources: job.bind(sources=bound_sources) + _refuse_shadowed_steps(job._persistent_node_map.values()) if database is not None: job._distribute_databases() @@ -1570,9 +1597,6 @@ def _prepare_run( (f"node {node.label!r}", node) for node in self._persistent_node_map.values() ) - # Once source preflight passes, stored row counts may change during the run. - self._last_run_finished = False - hash_dag: OrcaDAG[str] = OrcaDAG() for u, v in self._graph_edges: hash_dag.add_edge(u, v) @@ -1621,11 +1645,20 @@ def _prepare_run( "results with node.as_source()." ) + # Later bindings can make previously distinct graph vertices equal. + runnable_nodes = [ + node + for key, node in self._persistent_node_map.items() + if key not in excluded_hashes + ] + _refuse_shadowed_steps(runnable_nodes) + # Once preflight passes, stored row counts may change during the run. + self._last_run_finished = False + # --- Build execution OrcaDAG from existing node objects (no cloning) --- exec_dag: OrcaDAG = OrcaDAG() - for node_hash, node in self._persistent_node_map.items(): - if node_hash not in excluded_hashes: - exec_dag.add_node(node) + for node in runnable_nodes: + exec_dag.add_node(node) for u_hash, v_hash in self._graph_edges: if ( u_hash not in excluded_hashes @@ -2626,6 +2659,8 @@ def load( if isinstance(node, RunHoldingNode): node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance job_dag.add_node(node) + # Keep any existing errors raised while reconstructing the saved keys. + _refuse_shadowed_steps(job._persistent_node_map.values()) for u_hash, v_hash in job._graph_edges: u_node = job._persistent_node_map.get(u_hash) v_node = job._persistent_node_map.get(v_hash) diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py new file mode 100644 index 000000000..71b84f3fc --- /dev/null +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -0,0 +1,211 @@ +"""Job graph collisions measured on main (ec762d6a), in sync and async. + +| Steps | Shared live DAG key | Main: live / stored row counts per step | Main: reload | +| --- | --- | --- | --- | +| Direct + two-slot Join, either capture order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | +| Same function pod on two slots of one source | Slots and functions | 2/2, 0/2 | Existing error | +| Different function pods on those slots | Slots only | 2/2, 2/2 | Both readable | +| Two aliased slots joined with a third source | Slots only | 2/2, 2/2 | Both readable | +| Two-slot Join alone | Slots only | 2/2, 2/2 | Both readable | +| Direct self-Join alone | None | 2/2, 2/2 | Both readable | +| Same pipeline repeated with different labels | No second exposed step | 2/2, 2/2 on the retained branch | Both readable | +| Direct + two-slot MergeJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | +| Direct + two-slot SemiJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | +""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING, cast + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.databases import DeltaTableDatabase +from orcapod.operators import Join, MergeJoin, SemiJoin +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.sources import ArrowTableSource +from orcapod.types import CacheMode + +if TYPE_CHECKING: + from pathlib import Path + + from orcapod.protocols.core_protocols import StreamProtocol + + +@function_pod(output_keys="result") +def double(value: int) -> int: + return 2 * value + + +@function_pod(output_keys="result") +def triple(value: int) -> int: + return 3 * value + + +def _source(name: str) -> ArrowTableSource: + # Keep two data-tags so the function can read a scalar after any join. + return ArrowTableSource( + pa.table({"key": [1, 2], "value": [10, 20], "other": [30, 40]}), + tag_columns=["key", "value", "other"], + tag_only_columns=["key"], + source_id=name, + infer_nullable=True, + ) + + +def _capture( + pipeline: Pipeline | PipelineJob, case: str, *, reverse: bool = False +) -> dict[str, StreamProtocol]: + a, b = _source("a"), _source("b") + bindings: dict[str, StreamProtocol] = {"a": a} + with pipeline: + left = SourceNode.from_stream(a, name="a") + other = SourceNode.from_stream(a, name="a2") + if case in ("unary", "distinct"): + double.pod(left, label="first") + pod = double if case == "unary" else triple + pod.pod(other, label="second") + bindings["a2"] = a + elif case == "third": + third = SourceNode.from_stream(b, name="b") + double.pod(Join()(left, other, third, label="join"), label="result") + bindings.update(a2=a, b=b) + elif case == "identical": + for suffix in ("2", "1"): + double.pod(Join()(a, a, label=f"join{suffix}"), label=f"result{suffix}") + else: + operator = {"merge": MergeJoin, "semi": SemiJoin}.get(case, Join) + branches: list[tuple[str, tuple[StreamProtocol, StreamProtocol]]] = [ + ("direct", (a, a)), + ("slots", (left, other)), + ] + if reverse: + branches.reverse() + for label, inputs in branches: + if case in ("direct", "slots") and case != label: + continue + double.pod(operator()(*inputs, label=label), label=f"{label}_result") + if label == "slots": + bindings["a2"] = a + return bindings + + +_REFUSALS = [ + pytest.param( + case, reverse, id=f"{case}-{'slots-first' if reverse else 'direct-first'}" + ) + for case in ("mixed", "merge", "semi") + for reverse in (False, True) +] + [pytest.param("unary", False, id="unary")] + + +@pytest.mark.parametrize(("case", "reverse"), _REFUSALS) +@pytest.mark.parametrize("direct_capture", [False, True], ids=["blueprint", "capture"]) +def test_refuses_shadowed_steps_at_compile( + case: str, reverse: bool, direct_capture: bool, tmp_path: Path +) -> None: + database_path = tmp_path / "db" + database = DeltaTableDatabase(database_path) + labels = ("first", "second") if case == "unary" else ("direct", "slots") + message = rf"Steps '{labels[0]}' and '{labels[1]}' have the same identity.*ITL-1767" + if direct_capture: + job = PipelineJob("matrix", database=database) + bindings = _capture(job, case, reverse=reverse) + job.bind(sources=bindings) + with pytest.raises(ValueError, match=message): + job.compile() + else: + pipeline = Pipeline("matrix") + bindings = _capture(pipeline, case, reverse=reverse) + with pytest.raises(ValueError, match=message): + PipelineJob.from_pipeline(pipeline, database=database, sources=bindings) + assert not list(database_path.rglob("_delta_log")) + + +def _run(job: PipelineJob, asynchronous: bool) -> None: + if asynchronous: + asyncio.run( + job.run_async(orchestrator=AsyncPipelineOrchestrator(buffer_size=1)) + ) + else: + job.run(orchestrator=SyncPipelineOrchestrator()) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize( + ("case", "expected_results", "expected_operators"), + [ + ("distinct", {"first": [20, 40], "second": [30, 60]}, set()), + ("third", {"result": [20, 40]}, {"join"}), + ("slots", {"slots_result": [20, 40]}, {"slots"}), + ("direct", {"direct_result": [20, 40]}, {"direct"}), + ("identical", {"result1": [20, 40]}, {"join1"}), + ], +) +def test_working_cases_run_and_reload( + case: str, + expected_results: dict[str, list[int]], + expected_operators: set[str], + asynchronous: bool, + tmp_path: Path, +) -> None: + database = DeltaTableDatabase(tmp_path / "db") + pipeline = Pipeline("matrix") + bindings = _capture(pipeline, case) + job = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings) + assert { + label for label, node in job.nodes.items() if node.node_type != "source" + } == (expected_results.keys() | expected_operators) + for label in expected_operators: + node = cast("OperatorJobNode", job.nodes[label]) + node.attach_databases( + pipeline_database=database.at("matrix"), cache_mode=CacheMode.LOG + ) + + _run(job, asynchronous) + path = tmp_path / "job.json" + job.save(path) + loaded = PipelineJob.load(path) + + for label, expected in expected_results.items(): + assert sorted(job.nodes[label].as_table()["result"].to_pylist()) == expected + assert job.nodes[label].get_all_records().num_rows == len(expected) + assert loaded.nodes[label].get_all_records().num_rows == len(expected) + for label in expected_operators: + assert job.nodes[label].as_table().num_rows == 2 + assert job.nodes[label].get_all_records().num_rows == 2 + assert loaded.nodes[label].get_all_records().num_rows == 2 + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_rechecks_when_later_bindings_make_steps_equal( + asynchronous: bool, tmp_path: Path +) -> None: + pipeline = Pipeline("matrix") + bindings = _capture(pipeline, "unary") + job = cast( + "PipelineJob", + PipelineJob.from_invocations(pipeline.to_invocations(), name="matrix"), + ) + database_path = tmp_path / "db" + job.bind(database=DeltaTableDatabase(database_path), sources=bindings) + + with pytest.raises( + ValueError, match="Steps 'first' and 'second' have the same identity" + ): + _run(job, asynchronous) + assert not list(database_path.rglob("_delta_log")) + + +def test_load_keeps_existing_refusal_of_colliding_stubs(tmp_path: Path) -> None: + pipeline = Pipeline("matrix") + bindings = _capture(pipeline, "unary") + job = PipelineJob.from_pipeline(pipeline) + job.bind(sources=bindings) + path = tmp_path / "job.json" + job.save(path) + with pytest.raises(NotImplementedError, match=r"StreamBase\.identity_structure"): + PipelineJob.load(path) From eafe9a0e7430b37562e10f2d1508b9827e85dc42 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 15:38:22 -0800 Subject: [PATCH 2/5] fix(pipeline): preserve read-only job loading --- src/orcapod/pipeline/job.py | 4 ++-- tests/test_pipeline/test_shadowed_job_steps.py | 4 ++++ 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index d122ba809..1e56d588d 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -2654,13 +2654,13 @@ def load( # node map. This makes job.dag consistent with the compiled-job path # (where compile() builds _node_graph from job nodes). # Callers needing blueprint nodes for rendering use job.pipeline.dag. + # Stored views read the persistent nodes directly. Check for shadowed + # steps if a load-only run builds an execution graph to fill live views. job_dag: OrcaDAG = OrcaDAG() for node in job._persistent_node_map.values(): if isinstance(node, RunHoldingNode): node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance job_dag.add_node(node) - # Keep any existing errors raised while reconstructing the saved keys. - _refuse_shadowed_steps(job._persistent_node_map.values()) for u_hash, v_hash in job._graph_edges: u_node = job._persistent_node_map.get(u_hash) v_node = job._persistent_node_map.get(v_hash) diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index 71b84f3fc..d8d53dd1d 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -11,6 +11,10 @@ | Same pipeline repeated with different labels | No second exposed step | 2/2, 2/2 on the retained branch | Both readable | | Direct + two-slot MergeJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | | Direct + two-slot SemiJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | +| Pending job with equal operators on aliased slots | Slots and operators | No run | Both slots and steps restored | + +The pending read-only case is covered by +`test_password_removal_preserves_source_object_consistency` in `test_saved_credentials.py`. """ from __future__ import annotations From a02f24ae315d0a5cf7ecc92e8a3c04595345dbe3 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 16:12:49 -0800 Subject: [PATCH 3/5] fix(pipeline): preserve recovery from rejected captures --- src/orcapod/pipeline/base.py | 12 +++++--- src/orcapod/pipeline/job.py | 30 ++++++++++++++----- .../test_pipeline/test_shadowed_job_steps.py | 3 ++ .../test_source_object_registration.py | 5 +++- 4 files changed, 37 insertions(+), 13 deletions(-) diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 6b57b710d..6b6ed8d26 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -598,6 +598,12 @@ def compile(self) -> None: ValueError: If one source is read under two different restrictions (ITL-1218), judged from what the recorded streams read now. """ + self._compile_nodes() + + def _compile_nodes( + self, validate_nodes: Callable[[Iterable[NodeT]], None] | None = None + ) -> None: + """Build and publish compiled nodes, optionally checking them first.""" import networkx as _nx from orcapod.pipeline.restrictions import require_one_restriction @@ -718,7 +724,8 @@ def compile(self) -> None: i += 1 node_map = self._ordered_node_map(node_map, self._hash_graph) - self._validate_compiled_nodes(node_map.values()) + if validate_nodes is not None: + validate_nodes(node_map.values()) self._persistent_node_map = node_map self._nodes.clear() self._nodes.update((node.label, node) for node in node_map.values()) @@ -762,9 +769,6 @@ def compile(self) -> None: self._compiled = True - def _validate_compiled_nodes(self, nodes: Iterable[NodeT]) -> None: - """Check the newly compiled nodes before publishing them.""" - @staticmethod def _ordered_node_map( nodes: dict[str, Any], graph: nx.DiGraph[str] diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 1e56d588d..dfec241bb 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -7,7 +7,7 @@ import logging import sys import uuid -from collections.abc import Iterable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Sequence from copy import deepcopy from dataclasses import dataclass from itertools import chain @@ -313,6 +313,7 @@ def __init__( self._unresolved_database: dict[str, Any] | None = None self._execution_context = execution_context self._auto_compile = auto_compile + self._has_uncompiled_invocations = False # name → bound concrete source (user-facing API: job.sources). self._sources: dict[str, cp.StreamProtocol] = {} # Saved configs for untouched slots whose sources could not be rebuilt on load. @@ -346,7 +347,17 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None: self, exc_type, exc_value, traceback ) if exc_type is None and self._auto_compile: - self.compile() + if not self._compiled or self._has_uncompiled_invocations: + self.compile() + else: + # A block that accepted no invocations can leave bindings partway + # through a restore. Keep the normal refresh, and check the + # bindings on an explicit compile or before running. + self._compile_job() + + def _record_invocation(self, invocation: PodInvocation) -> None: + super()._record_invocation(invocation) + self._has_uncompiled_invocations = True def _input_graph_key(self, upstream: cp.StreamProtocol) -> str: """Reuse an active slot's recorded key when capturing from that slot.""" @@ -456,8 +467,7 @@ def _source_node_from_recording(self, key: str) -> SourceJobNode: def compile(self) -> None: """Compile recorded invocations into a frozen DAG of job nodes. - Delegates to ``AbstractPipelineBase.compile()`` which uses - ``source_node_class``, ``function_node_class``, and + The base class uses ``source_node_class``, ``function_node_class``, and ``operator_node_class`` to create job node instances. Concrete source bindings already in ``_sources`` are preserved. @@ -474,12 +484,19 @@ def compile(self) -> None: ValueError: If distinct steps would share a vertex in the job graph and one would lose its current-run rows (ITL-1767). """ + self._compile_job(_refuse_shadowed_steps) + + def _compile_job( + self, validate_nodes: Callable[[Iterable[JobNode]], None] | None = None + ) -> None: + """Rebuild the graph and wire the compiled job's bindings and databases.""" previous_slots = [ node for node in self._persistent_node_map.values() if isinstance(node, SourceJobNode) ] - super().compile() + self._compile_nodes(validate_nodes) + self._has_uncompiled_invocations = False for slot in previous_slots: slot._set_binding_owner(None) # pyright: ignore[reportPrivateUsage] # the replaced slot no longer belongs to this job @@ -506,9 +523,6 @@ def compile(self) -> None: if self._database is not None: self._distribute_databases() - def _validate_compiled_nodes(self, nodes: Iterable[JobNode]) -> None: - _refuse_shadowed_steps(nodes) - # ------------------------------------------------------------------ # compiled_pipeline — lazy cache # ------------------------------------------------------------------ diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index d8d53dd1d..8354b73ee 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -12,9 +12,12 @@ | Direct + two-slot MergeJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | | Direct + two-slot SemiJoin, either order | Slots, joins and functions | 2/2, 0/2 on both levels | Existing error | | Pending job with equal operators on aliased slots | Slots and operators | No run | Both slots and steps restored | +| Temporarily aliased slots during recovery from a rejected capture | Slots and functions until restored | Correct rows after restoration | — | The pending read-only case is covered by `test_password_removal_preserves_source_object_consistency` in `test_saved_credentials.py`. +Slot restoration is covered by `test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows` +in `test_source_object_registration.py`. """ from __future__ import annotations diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index 24cf7221f..2ce13f80b 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -305,12 +305,15 @@ def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> N total.pod(_source(tmp_path, "dict", slot), label=f"total_{slot}") source = _source(tmp_path, "csv", "shared") job.bind(sources={"a": source, "b": source}) - job.run() path = tmp_path / "job.json" job.save(path) with pytest.raises(NotImplementedError, match="StreamBase.identity_structure"): PipelineJob.load(path, database=db) + with pytest.raises( + ValueError, match="Steps 'total_a' and 'total_b' have the same identity" + ): + job.run() @pytest.mark.parametrize("kind", ["equal", "different", "csv"]) From f306701d4142832a7e58f652087830bb16e4185a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 16:17:42 -0800 Subject: [PATCH 4/5] docs(hashing): update the compile call site inventory --- docs/reference/hashing.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index ae1a5c41e..7fc382e4a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -460,7 +460,7 @@ id is a hash (site 8b). |---|---| | 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._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `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_nodes`, `pipeline/base.py:AbstractPipelineBase._compile_nodes..`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `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 capture keys (ITL-1590) | `pipeline/pod_invocation.py:PodInvocation.capture_keys` | | in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` | | in-memory key for an in-flight function result (ITL-1101) | `core/cached_function_pod.py:CachedFunctionPod._async_process_once` | From 4a433aa45c8db59c40de31c654b5cd50650fd929 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sun, 29 Nov 2026 20:01:59 -0800 Subject: [PATCH 5/5] fix(pipeline): clarify and verify job step collision refusal --- changelog.d/ITL-1767.md | 2 +- docs/concepts/pipeline-job.md | 5 +- .../design_issues/ITL-1767-PJCOLLISION1.md | 3 +- src/orcapod/pipeline/job.py | 4 +- .../test_pipeline/test_shadowed_job_steps.py | 132 ++++++++++++++---- 5 files changed, 115 insertions(+), 31 deletions(-) diff --git a/changelog.d/ITL-1767.md b/changelog.d/ITL-1767.md index 9d3bb2f66..29ed8ae96 100644 --- a/changelog.d/ITL-1767.md +++ b/changelog.d/ITL-1767.md @@ -1,3 +1,3 @@ ### Changed -- Job compilation now rejects distinct steps that would share one execution graph vertex and lose one step's current-run rows, including a direct self-join alongside a join over two slots bound to the same source (ITL-1767). +- Job compilation now refuses distinct steps that would share an execution graph vertex (ITL-1767). This includes a direct self-join alongside a join over two slots bound to one source, and the same function pod applied to both slots. Put the conflicting steps in separate jobs or use just one form. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 5d4569603..90dde0c30 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -459,7 +459,10 @@ Every job also carries its blueprint as `job.pipeline`. ## Job graph limitations -Orcapod rejects distinct steps that would share one execution graph vertex and lose a step’s current-run rows (ITL-1767), so put a direct self-join and its two-slot equivalent in separate jobs or use just one form. +Orcapod refuses to build a job graph when distinct steps would share an execution vertex (ITL-1767). +This includes a direct self-join alongside a join of two slots bound to the same source, or the +same function pod applied to both slots. Put the conflicting steps in separate jobs or use just +one form in the job. ## Seeing the graph diff --git a/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md index 0f2384128..78ea0c2ab 100644 --- a/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md +++ b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md @@ -11,6 +11,7 @@ in the execution graph, and a step below either join can do the same. Both steps are visible in `job.nodes`, but only one receives current-run rows. Identical unary pods over different slots bound to the same source have the same problem. -Job compilation now refuses distinct steps that share an execution vertex. +**Mitigation:** Job compilation refuses distinct steps that share an execution +vertex, even when no keys match or both steps already hold current results. Sharing the source itself still works. The follow-up is to let both steps run and read their rows independently. diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index dfec241bb..6ad997c6e 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -117,8 +117,8 @@ def _refuse_shadowed_steps(nodes: Iterable[JobNode]) -> None: if previous is not node: raise ValueError( f"Steps {previous.label!r} and {node.label!r} have the same " - "identity in this job, so one would read the other's rows. " - "Put them in separate jobs or use only one of the two forms (ITL-1767)." + "identity in this job (ITL-1767). Put them in separate jobs or use " + "only one of the two forms." ) diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index 8354b73ee..755406d3b 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -14,8 +14,6 @@ | Pending job with equal operators on aliased slots | Slots and operators | No run | Both slots and steps restored | | Temporarily aliased slots during recovery from a rejected capture | Slots and functions until restored | Correct rows after restoration | — | -The pending read-only case is covered by -`test_password_removal_preserves_source_object_consistency` in `test_saved_credentials.py`. Slot restoration is covered by `test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows` in `test_source_object_registration.py`. """ @@ -23,17 +21,20 @@ from __future__ import annotations import asyncio +import re from typing import TYPE_CHECKING, cast import pyarrow as pa import pytest from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode from orcapod.core.nodes.operator_node import OperatorJobNode +from orcapod.core.operators.column_selection import SelectDataColumns from orcapod.databases import DeltaTableDatabase from orcapod.operators import Join, MergeJoin, SemiJoin from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator -from orcapod.sources import ArrowTableSource +from orcapod.sources import ArrowTableSource, CSVSource from orcapod.types import CacheMode if TYPE_CHECKING: @@ -52,10 +53,16 @@ def triple(value: int) -> int: return 3 * value -def _source(name: str) -> ArrowTableSource: +def _source(name: str, *, null_keys: bool = False) -> ArrowTableSource: # Keep two data-tags so the function can read a scalar after any join. return ArrowTableSource( - pa.table({"key": [1, 2], "value": [10, 20], "other": [30, 40]}), + pa.table( + { + "key": pa.array([None, None] if null_keys else [1, 2], type=pa.int64()), + "value": [10, 20], + "other": [30, 40], + } + ), tag_columns=["key", "value", "other"], tag_only_columns=["key"], source_id=name, @@ -64,17 +71,24 @@ def _source(name: str) -> ArrowTableSource: def _capture( - pipeline: Pipeline | PipelineJob, case: str, *, reverse: bool = False + pipeline: Pipeline | PipelineJob, + case: str, + *, + reverse: bool = False, + null_keys: bool = False, ) -> dict[str, StreamProtocol]: - a, b = _source("a"), _source("b") + a, b = _source("a", null_keys=null_keys), _source("b") bindings: dict[str, StreamProtocol] = {"a": a} with pipeline: left = SourceNode.from_stream(a, name="a") other = SourceNode.from_stream(a, name="a2") if case in ("unary", "distinct"): - double.pod(left, label="first") - pod = double if case == "unary" else triple - pod.pod(other, label="second") + second = double if case == "unary" else triple + function_branches = [("first", left, double), ("second", other, second)] + if reverse: + function_branches.reverse() + for label, source, pod in function_branches: + _ = pod.pod(source, label=label) bindings["a2"] = a elif case == "third": third = SourceNode.from_stream(b, name="b") @@ -106,7 +120,16 @@ def _capture( ) for case in ("mixed", "merge", "semi") for reverse in (False, True) -] + [pytest.param("unary", False, id="unary")] +] + [pytest.param("unary", reverse, id=f"unary-{reverse}") for reverse in (False, True)] + + +def _refusal_message(case: str) -> str: + first, second = ("first", "second") if case == "unary" else ("direct", "slots") + labels = rf"(?:'{first}' and '{second}'|'{second}' and '{first}')" + return ( + rf"Steps {labels} have the same identity in this job \(ITL-1767\)\. " + + re.escape("Put them in separate jobs or use only one of the two forms.") + ) @pytest.mark.parametrize(("case", "reverse"), _REFUSALS) @@ -116,8 +139,7 @@ def test_refuses_shadowed_steps_at_compile( ) -> None: database_path = tmp_path / "db" database = DeltaTableDatabase(database_path) - labels = ("first", "second") if case == "unary" else ("direct", "slots") - message = rf"Steps '{labels[0]}' and '{labels[1]}' have the same identity.*ITL-1767" + message = _refusal_message(case) if direct_capture: job = PipelineJob("matrix", database=database) bindings = _capture(job, case, reverse=reverse) @@ -128,17 +150,20 @@ def test_refuses_shadowed_steps_at_compile( pipeline = Pipeline("matrix") bindings = _capture(pipeline, case, reverse=reverse) with pytest.raises(ValueError, match=message): - PipelineJob.from_pipeline(pipeline, database=database, sources=bindings) + _ = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings) assert not list(database_path.rglob("_delta_log")) -def _run(job: PipelineJob, asynchronous: bool) -> None: +def _run(job: PipelineJob, asynchronous: bool, *, load_only: bool = False) -> None: if asynchronous: - asyncio.run( - job.run_async(orchestrator=AsyncPipelineOrchestrator(buffer_size=1)) + _ = asyncio.run( + job.run_async( + orchestrator=AsyncPipelineOrchestrator(buffer_size=1), + load_only=load_only, + ) ) else: - job.run(orchestrator=SyncPipelineOrchestrator()) + _ = job.run(orchestrator=SyncPipelineOrchestrator(), load_only=load_only) @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) @@ -188,11 +213,12 @@ def test_working_cases_run_and_reload( @pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize(("case", "reverse"), _REFUSALS) def test_rechecks_when_later_bindings_make_steps_equal( - asynchronous: bool, tmp_path: Path + case: str, reverse: bool, asynchronous: bool, tmp_path: Path ) -> None: pipeline = Pipeline("matrix") - bindings = _capture(pipeline, "unary") + bindings = _capture(pipeline, case, reverse=reverse) job = cast( "PipelineJob", PipelineJob.from_invocations(pipeline.to_invocations(), name="matrix"), @@ -200,19 +226,73 @@ def test_rechecks_when_later_bindings_make_steps_equal( database_path = tmp_path / "db" job.bind(database=DeltaTableDatabase(database_path), sources=bindings) - with pytest.raises( - ValueError, match="Steps 'first' and 'second' have the same identity" - ): + with pytest.raises(ValueError, match=_refusal_message(case)): _run(job, asynchronous) assert not list(database_path.rglob("_delta_log")) -def test_load_keeps_existing_refusal_of_colliding_stubs(tmp_path: Path) -> None: +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +@pytest.mark.parametrize("reverse", [False, True], ids=["direct-first", "slots-first"]) +@pytest.mark.parametrize("scenario", ["null-keys", "both-current"]) +def test_step_collision_is_independent_of_rows_and_run_state( + scenario: str, reverse: bool, asynchronous: bool, tmp_path: Path +) -> None: + pipeline = Pipeline("matrix") + bindings = _capture( + pipeline, "mixed", reverse=reverse, null_keys=scenario == "null-keys" + ) + database = DeltaTableDatabase(tmp_path / "db") + if scenario == "null-keys": + with pytest.raises(ValueError, match=_refusal_message("mixed")): + _ = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings) + job = PipelineJob.from_pipeline(pipeline, database=database) + job.bind(sources=bindings) + expected = 0 if scenario == "null-keys" else 2 + for label in ("direct_result", "slots_result"): + node = cast("FunctionJobNode", job.nodes[label]) + _ = node.run() + assert node.as_table().num_rows == expected + assert node.holds_current_run() + + with pytest.raises(ValueError, match=_refusal_message("mixed")): + _run(job, asynchronous) + + +@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"]) +def test_pending_operator_steps_on_aliased_slots_can_be_saved_and_loaded( + asynchronous: bool, tmp_path: Path +) -> None: + data_path = tmp_path / "rows.csv" + _ = data_path.write_text("key,value\n1,10\n2,20\n") + source = CSVSource( + str(data_path), source_id="shared", tag_columns=["key"], tag_only_columns=True + ) + database = DeltaTableDatabase(tmp_path / "db") + with PipelineJob("matrix", database=database) as job: + for slot, label in (("a", "first"), ("b", "second")): + _ = SelectDataColumns(["value"])( + SourceNode.from_stream(source, name=slot), label=label + ) + job.bind(sources={"a": source, "b": source}) + path = tmp_path / "job.json" + job.save(path) + + loaded = PipelineJob.load(path) + assert loaded.sources["a"] is loaded.sources["b"] + assert set(loaded.nodes) == {"a", "b", "first", "second"} + with pytest.raises(ValueError, match=_refusal_message("unary")): + _run(loaded, asynchronous, load_only=True) + + +@pytest.mark.parametrize(("case", "reverse"), _REFUSALS) +def test_load_keeps_existing_refusal_of_colliding_stubs( + case: str, reverse: bool, tmp_path: Path +) -> None: pipeline = Pipeline("matrix") - bindings = _capture(pipeline, "unary") + bindings = _capture(pipeline, case, reverse=reverse) job = PipelineJob.from_pipeline(pipeline) job.bind(sources=bindings) path = tmp_path / "job.json" job.save(path) with pytest.raises(NotImplementedError, match=r"StreamBase\.identity_structure"): - PipelineJob.load(path) + _ = PipelineJob.load(path)