diff --git a/changelog.d/ITL-1767.md b/changelog.d/ITL-1767.md new file mode 100644 index 000000000..29ed8ae96 --- /dev/null +++ b/changelog.d/ITL-1767.md @@ -0,0 +1,3 @@ +### Changed + +- 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 677cfaa2a..90dde0c30 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -457,6 +457,14 @@ print(job_c.nodes["bmi"].as_table().num_rows) Every job also carries its blueprint as `job.pipeline`. +## Job graph limitations + +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 !!! 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..78ea0c2ab --- /dev/null +++ b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md @@ -0,0 +1,17 @@ +## `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. + +**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/docs/reference/hashing.md b/docs/reference/hashing.md index 904a0ba6d..edb21d4c0 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` | diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index a65c271dc..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,6 +724,8 @@ def compile(self) -> None: i += 1 node_map = self._ordered_node_map(node_map, self._hash_graph) + 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()) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index af81177ee..6ad997c6e 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 @@ -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 (ITL-1767). Put them in separate jobs or use " + "only one of the two forms." + ) + + def _supports_attachment_enrollment(database: WriteDatabase) -> bool: """Recognize stores whose durable rows we can distinguish from pending ones.""" return isinstance( @@ -295,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. @@ -328,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.""" @@ -438,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. @@ -451,13 +479,24 @@ 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). """ + 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 @@ -599,7 +638,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 +676,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 +1611,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 +1659,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 @@ -2621,6 +2668,8 @@ 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): 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..755406d3b --- /dev/null +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -0,0 +1,298 @@ +"""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 | +| 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 | — | + +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 + +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, CSVSource +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, *, null_keys: bool = False) -> ArrowTableSource: + # Keep two data-tags so the function can read a scalar after any join. + return ArrowTableSource( + 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, + infer_nullable=True, + ) + + +def _capture( + pipeline: Pipeline | PipelineJob, + case: str, + *, + reverse: bool = False, + null_keys: bool = False, +) -> dict[str, StreamProtocol]: + 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"): + 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") + 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", 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) +@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) + message = _refusal_message(case) + 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, *, load_only: bool = False) -> None: + if asynchronous: + _ = asyncio.run( + job.run_async( + orchestrator=AsyncPipelineOrchestrator(buffer_size=1), + load_only=load_only, + ) + ) + else: + _ = job.run(orchestrator=SyncPipelineOrchestrator(), load_only=load_only) + + +@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"]) +@pytest.mark.parametrize(("case", "reverse"), _REFUSALS) +def test_rechecks_when_later_bindings_make_steps_equal( + case: str, reverse: bool, asynchronous: bool, tmp_path: Path +) -> None: + pipeline = Pipeline("matrix") + bindings = _capture(pipeline, case, reverse=reverse) + 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=_refusal_message(case)): + _run(job, asynchronous) + assert not list(database_path.rglob("_delta_log")) + + +@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, 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) diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index fe6a56809..f44ef4c9b 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -316,12 +316,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"])