From dda704bfb53d39f0d12d74006fcece420688be8a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 07:39:06 -0800 Subject: [PATCH 01/12] feat(pipeline): key compiled graphs by node hash (ITL-1848) A compiled pipeline or job holds each node under its node hash; a node hash names one node within a pipeline, and two distinct nodes with one node hash are refused, never told apart. Capture keeps main's keys and code; nodes without a node hash (custom operators and below) and loaded graphs are held under legacy: until ITL-1864. Accepted differences from main, each asserted by a main-backed differential test: R-IN (membership on a compiled DAG), R-GRAPH (graph attribute removed), R-53/54 and R-MIX (one source object through an explicit slot and directly), ROWS-37-38 (explicit slot and another source with one name), REWIRE-87 (rewiring a captured descriptor) and LOAD-DUP (a pipeline file with two nodes of one node hash). Part of ITL-1559. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1848.md | 26 + docs/api/errors.md | 2 + docs/concepts/pipeline-job.md | 12 + docs/concepts/sources.md | 9 + docs/reference/hashing.md | 2 +- src/orcapod/core/identity_chains.py | 13 +- src/orcapod/core/nodes/function_node.py | 10 + src/orcapod/core/nodes/operator_node.py | 4 + src/orcapod/core/nodes/source_node.py | 10 + src/orcapod/core/streams/base.py | 43 ++ src/orcapod/errors.py | 10 + src/orcapod/pipeline/base.py | 347 ++++++++- src/orcapod/pipeline/dag.py | 132 +++- src/orcapod/pipeline/graph.py | 31 +- src/orcapod/pipeline/graph_keys.py | 100 +++ src/orcapod/pipeline/job.py | 75 +- tests/test_core/test_tracker.py | 12 +- tests/test_hashing/test_identity_chains.py | 23 +- .../test_graph_keys_main_compatibility.py | 665 ++++++++++++++++++ tests/test_pipeline/test_pipeline.py | 39 +- .../test_pipeline_base_recording.py | 7 +- .../test_pipeline/test_shadowed_job_steps.py | 39 +- .../test_pipeline/test_source_id_conflicts.py | 8 +- .../test_source_object_registration.py | 5 +- 24 files changed, 1537 insertions(+), 87 deletions(-) create mode 100644 changelog.d/ITL-1848.md create mode 100644 src/orcapod/pipeline/graph_keys.py create mode 100644 tests/test_pipeline/test_graph_keys_main_compatibility.py diff --git a/changelog.d/ITL-1848.md b/changelog.d/ITL-1848.md new file mode 100644 index 000000000..c8f9d2665 --- /dev/null +++ b/changelog.d/ITL-1848.md @@ -0,0 +1,26 @@ +### Breaking changes and migration + +- A pipeline or job no longer has a `graph` attribute. Use `job.dag` (or `pipeline.dag`) + for the compiled graph and `job.nodes[label]` for a node. +- `node in job.dag` (and in `pipeline.dag`) answers only for the DAG's own nodes. Any other + node, stream or invocation object raises `UndefinedGraphMembershipError`, a new error in + `orcapod.errors`: look the node up by label instead (ITL-1559). + +### Changed + +- A compiled pipeline or job holds each node under its node hash, and a node hash names one + node: two distinct nodes with one node hash are refused, never told apart (ITL-1848, + part of ITL-1559). A custom operator, which has no node hash yet, and the nodes below it + keep their capture key. Saved files are unchanged; a loaded graph keeps its saved keys + until saved files record node hashes (ITL-1864). +- One source object read through an explicit slot (`SourceNode.from_stream(source, + name=...)`) and directly in one pipeline or job is refused with `InconsistentSourceError` + at the capture that brings the second form, whether the names agree or not. +- An explicit slot and another source object with the same name (two slots with one node + hash) are refused with `InconsistentSourceError` at the capture that brings the second + one; declare the second source under its own slot name. +- Setting a captured step's `upstreams` to other streams raises `InconsistentSourceError`; + build a new step for the new inputs (following such a change is ITL-1847). Setting the + same streams again is still accepted. +- Loading a saved pipeline or job in which two distinct nodes share one node hash raises + `InconsistentSourceError`. diff --git a/docs/api/errors.md b/docs/api/errors.md index 860739d66..fe8fac421 100644 --- a/docs/api/errors.md +++ b/docs/api/errors.md @@ -68,6 +68,8 @@ These exceptions and warnings report problems running pipelines, processing rows ::: orcapod.errors.PipelineJobRequiredError +::: orcapod.errors.UndefinedGraphMembershipError + ::: orcapod.errors.DataFunctionUnavailableError ::: orcapod.errors.OutputTypeError diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index 90dde0c30..c11256e6f 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -464,6 +464,18 @@ This includes a direct self-join alongside a join of two slots bound to the same same function pod applied to both slots. Put the conflicting steps in separate jobs or use just one form in the job. +Within one pipeline or job, a node hash names one node: two distinct nodes with one node +hash are refused, never told apart. A step's inputs are fixed once a pipeline or job has +captured it: setting a captured step's `upstreams` to other streams raises +`InconsistentSourceError` (following such a change is ITL-1847); build a new step for the new +inputs. Loading a saved file in which two distinct nodes share one node hash is refused too. + +The compiled graph is `job.dag` (or `pipeline.dag`), and `job.nodes[label]` gives a node by +its label. A pipeline or job has no `graph` attribute. `node in job.dag` answers for the +DAG's own nodes; for any other node, stream or invocation object it raises +`UndefinedGraphMembershipError`, since membership of a node object is not defined yet +(ITL-1559): look the node up by label instead. + ## Seeing the graph diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 82926a1d4..8ba70e6ee 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -105,6 +105,15 @@ original bindings are restored. InconsistentSourceError names the changed slots. Restore the original bindings or build a new job. A job can compile and run with its replacement bindings. ITL-1559 tracks capture after rebinding. +A slot holds one source object. Read a source either through an explicit slot +(`SourceNode.from_stream(source, name="units")`) or directly, never both in one pipeline +or job: the capture that brings the second form raises `InconsistentSourceError`, under +the same name or another. Likewise, an explicit slot `units` and another source object named +`units` would be two slots with one node hash, so the capture that brings the second one is +refused; declare the second source under its own slot name +(`SourceNode.from_stream(other, name="units_2")`). Until source equivalence is defined +(ITL-1553), pass the same object again or give each its own slot. + An output stream returned by a run uses the slot bindings that were in effect when its rows were produced. Binding any slot that feeds it makes that output stale, even if you bind A to B and then back to A, or never hashed the output before diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 686a11742..5ea1760ee 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -461,7 +461,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_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 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), `pipeline/graph_keys.py:compiled_graph_key` and `pipeline/base.py:AbstractPipelineBase._describe_capture_leaf` (a compiled node's node hash, the key the compiled graph holds it under, ITL-1848) | | 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/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 0ac6c3293..ed2142584 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -50,10 +50,19 @@ def _identity_read() -> Iterator[None]: _reading_chains.reset(token) +class UndefinedIdentityError(ValueError): + """A pipeline element cannot give its node hash in this step. + + Raised for a custom operator, and for an element whose identity would need rows + or a source callback. A compiled graph then keys the node by its capture key + (ITL-1848). + """ + + def refuse_identity_io(reason: str = "this source requires a schema") -> None: """Report why an identity read would need rows or a source callback.""" if reading_identity_chains(): - raise ValueError(f"Pipeline identity is undefined: {reason}.") + raise UndefinedIdentityError(f"Pipeline identity is undefined: {reason}.") def reading_identity_chains() -> bool: @@ -67,7 +76,7 @@ def require_builtin_operator_identity(operator: object) -> None: from orcapod.core.operators import BUILTIN_OPERATOR_TYPES if type(operator) not in BUILTIN_OPERATOR_TYPES: - raise ValueError( + raise UndefinedIdentityError( "Pipeline identity is undefined for a custom operator in this step." ) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 3518b8450..8f38eee8b 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -583,8 +583,18 @@ def upstreams(self) -> tuple[StreamProtocol, ...]: @upstreams.setter def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: + """Replace the node's input. + + Raises: + ValueError: If ``value`` does not hold exactly one stream. + InconsistentSourceError: If a live pipeline or job captured this node as + an input and ``value`` holds another input (ITL-1848); nothing + changes. + """ if len(value) != 1: raise ValueError("FunctionPod can only have one upstream") + if self._captured_rewire_is_noop(tuple(value)): + return with self._identity_lock: self._input_stream = value[0] invalidate_output_lineage() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 91e5f7b25..401842f13 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -426,11 +426,15 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: """Replace the node's inputs. Raises: + InconsistentSourceError: If a live pipeline or job captured this node as + an input and ``value`` holds other inputs (ITL-1848); nothing changes. ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source feeding ``value`` is restricted (ITL-1218); nothing changes. """ from orcapod.pipeline.restrictions import refuse_restricted_operator_cache + if self._captured_rewire_is_noop(tuple(value)): + return refuse_restricted_operator_cache(self, self.cache_mode, streams=value) with self._identity_lock: self._input_streams = value diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 7c0c1db3c..8906dbe98 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1743,8 +1743,18 @@ def from_stream( # A loaded job's slot keeps all its saved state (ITL-1138, ITL-640), # through the one method every copy of a slot uses. node._take_saved_state_of(stream) + elif name is not None: + # The stream an explicit slot was declared from: a pipeline refuses to + # capture it directly as well (ITL-1848). Only weakly held. + try: + node._declared_from = weakref.ref(stream) + except TypeError: + pass return node + # The stream a slot declared with ``from_stream`` was declared from (ITL-1848). + _declared_from: weakref.ReferenceType[StreamProtocol] | None = None + class SourceJobNode(ProvenanceMethods, SourceNodeBase): """Execution-ready source node wrapping an optional concrete stream. diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9628288fe..5ceafe7b2 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -763,6 +763,49 @@ def _was_recorded_by(self, tracker: TrackerProtocol) -> bool: """Check recording provenance without comparing stream hashes.""" return any(recording() is tracker for recording in self._recording_trackers) + # The pipelines and jobs that captured this stream as an input, or a stream + # above it (ITL-1848). Their compiled graphs hold the slot this stream names. + _capturing_graphs: tuple[ReferenceType[TrackerProtocol], ...] = () + + def _hold_for_capture(self, graph: TrackerProtocol) -> None: + """Keep this stream's inputs as they are while *graph* holds the capture.""" + held = tuple(entry for entry in self._capturing_graphs if entry() is not None) + if not any(entry() is graph for entry in held): + self._capturing_graphs = (*held, ref(graph)) + + def _captured_rewire_is_noop(self, inputs: tuple[StreamProtocol, ...]) -> bool: + """Refuse new inputs for a stream a live pipeline or job captured (ITL-1848). + + A captured stream names its slot by its content, so new inputs would rename + a slot a compiled graph already holds. Following such a change is ITL-1847. + + Args: + inputs: The proposed inputs. + + Returns: + ``True`` when the stream is held and *inputs* are its current inputs, in + the same positions: assigning them again changes nothing. ``False`` when + no live pipeline or job holds the stream. + + Raises: + InconsistentSourceError: If a live pipeline or job holds the stream and + *inputs* differ from its current inputs. + """ + if not any(entry() is not None for entry in self._capturing_graphs): + return False + current = self.upstreams + if len(inputs) == len(current) and all( + new is old for new, old in zip(inputs, current, strict=True) + ): + return True + from orcapod.errors import InconsistentSourceError + + raise InconsistentSourceError( + f"Cannot rewire {self.label!r} because a pipeline or job captured it as " + "an input (ITL-1559). Create a new descriptor for the new inputs; " + "rewiring a captured input is ITL-1847." + ) + @property def _identity_hasher(self) -> SemanticHasherProtocol: """Use the stream's structural hasher for the walk.""" diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py index 91a77a590..60fa9a800 100644 --- a/src/orcapod/errors.py +++ b/src/orcapod/errors.py @@ -97,6 +97,16 @@ class TypeIdentityError(ValueError): """ +class UndefinedGraphMembershipError(TypeError): + """Raised when ``in`` asks a compiled pipeline DAG about an object it does not hold. + + A compiled DAG (``pipeline.dag``, ``job.dag``) answers ``in`` for the node objects + it holds. Asking about any other node, stream or pod invocation, even one that + compares equal, has no defined answer yet (ITL-1559): access a node by label with + ``pipeline.nodes[label]`` or ``job.nodes[label]``. + """ + + class RecursiveTypeError(TypeError): """Raised when a class refers back to itself through its fields. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 6b6ed8d26..2c8ea7727 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -16,7 +16,15 @@ from orcapod.core.identity_chains import graph_hash from orcapod.core.nodes.function_node import FunctionNodeBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker -from orcapod.pipeline.dag import OrcaDAG +from orcapod.errors import InconsistentSourceError, InputValidationError +from orcapod.pipeline.dag import CompiledDAG, OrcaDAG +from orcapod.pipeline.graph_keys import ( + compiled_graph_key, + is_legacy_graph_key, + rekeyed, + rekeyed_edges, + shared_graph_keys, +) from orcapod.pipeline.pod_invocation import ( FunctionInvocation, OperatorInvocation, @@ -47,6 +55,7 @@ logger = logging.getLogger(__name__) NodeT = TypeVar("NodeT", bound=Hashable) +_V = TypeVar("_V") def _refuse_sources_sharing_a_slot_name( @@ -87,6 +96,54 @@ def _refuse_sources_sharing_a_slot_name( ) +@dataclass(frozen=True, slots=True) +class CaptureLeaf: + """A leaf a pipeline captured: the slot its compiled graph will hold (ITL-1848). + + Args: + capture_key: The key the leaf was recorded under. + name: The slot name the compiled graph gives it. + node_hash: The slot's node hash as text, or ``None`` when it cannot be + read at capture (compiling then decides). + described: How a refusal names the leaf (``declared slot 'x'``). + leaf: The object captured: the stream an explicit slot was declared from, + or the stream itself. ``None`` when it is not known. + declared: Whether the leaf came through an explicit slot declaration. + root: Whether the leaf is a source captured directly. + """ + + capture_key: str + name: str + node_hash: str | None + described: str + leaf: ReferenceType[Any] | None + declared: bool + root: bool + + def is_object(self, other: CaptureLeaf) -> bool: + """Whether both leaves are one live object.""" + if self.leaf is None or other.leaf is None: + return False + mine = self.leaf() + return mine is not None and mine is other.leaf() + + +def _one_object_on_two_slots(leaf: Any, first: str, second: str) -> str: + """The refusal for one object captured under an explicit name and directly.""" + from orcapod.core.sources.base import RootSource + + what = ( + f"Source {leaf.source_id!r}" + if isinstance(leaf, RootSource) + else f"Stream {leaf.label!r}" + ) + return ( + f"{what} would be read by slots {first!r} and {second!r}. One source object " + "on two slots is not supported yet (ITL-1559, step 6). Read it through one " + "slot and branch from that slot." + ) + + @dataclass(frozen=True) class InvocationGraph: """Interchange value object between Pipeline and PipelineJob. @@ -165,6 +222,16 @@ def __init__( self._upstreams: dict[str, Any] = {} # hash → source compiled node self._graph_edges: list[tuple[str, str]] = [] # edge list from _hash_graph + # --- Graph keys (ITL-1848) ----------------------------------------- + # The compiled maps above are keyed by graph keys (graph_keys.py): a node's + # node hash, pinned at the first compile of its capture key and never + # recomputed. The capture registries keep their capture keys. + self._graph_key_of: dict[str, str] = {} # capture key -> graph key + self._capture_key_of: dict[str, str] = {} # graph key -> capture key + self._pinned_slot_names: dict[str, str] = {} # capture key -> slot name + # Leaves recorded so far, by capture key, checked at each new capture. + self._capture_leaves: dict[str, CaptureLeaf] = {} + # ------------------------------------------------------------------ # Properties # ------------------------------------------------------------------ @@ -174,11 +241,6 @@ def name(self) -> tuple[str, ...]: """Pipeline name tuple.""" return self._name - @property - def graph(self) -> "nx.DiGraph": - """Directed hash graph of accumulated pipeline structure.""" - return self._hash_graph - @property def nodes(self) -> dict[str, Any]: """Copy of the compiled nodes dict (label → node).""" @@ -402,11 +464,175 @@ def _validate_invocation( # slot rebound since the last invocation changes what they read). require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) + # The rules of a compiled graph keyed by node hash (ITL-1848), checked after + # main's own checks so that their refusals come first. + leaves = self._new_capture_leaves(inputs, input_keys) if remember_streams: self._remember_capture_stream_keys(capture_streams.maps[0]) + self._capture_leaves.update((leaf.capture_key, leaf) for leaf in leaves) + new_keys = {leaf.capture_key for leaf in leaves} + for stream, input_key in zip(inputs, input_keys, strict=True): + if input_key in new_keys: + self._hold_captured(stream) return key, input_keys + # ------------------------------------------------------------------ + # Capture leaves (ITL-1848) + # ------------------------------------------------------------------ + + def _new_capture_leaves( + self, inputs: tuple[StreamProtocol, ...], input_keys: tuple[str, ...] + ) -> list[CaptureLeaf]: + """Describe the leaves this capture adds and refuse the ones A refuses. + + Refused, before anything is recorded: one object captured through an + explicit slot declaration and directly (spec rows 53, 54, 66 and 68), and a + new leaf whose slot would have the node hash of another leaf's slot (rows 37 + and 38: a node hash is unique within a pipeline). Two sources sharing one + slot name are left to main's own refusals. + + Raises: + InconsistentSourceError: Naming the slot and both leaves. + """ + staged: list[CaptureLeaf] = [] + for stream, key in zip(inputs, input_keys, strict=True): + if ( + key in self._invocation_lut + or key in self._source_streams + or any(leaf.capture_key == key for leaf in staged) + ): + continue + leaf = self._describe_capture_leaf(stream, key) + known = [*self._capture_leaves.values(), *staged] + self._refuse_one_object_twice(leaf, known) + self._refuse_shared_node_hash(leaf, known) + staged.append(leaf) + return staged + + def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLeaf: + """Describe a new leaf: the slot name and node hash compiling will give it.""" + from orcapod.core.nodes.source_node import ( + SourceNode, + SourceNodeBase, + slot_name_for, + ) + from orcapod.core.sources.base import RootSource + from orcapod.types import ContentHash + + declared = isinstance(stream, SourceNode) + if declared: + name = stream.name + described = f"declared slot {name!r}" + leaf = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from + else: + name = slot_name_for(stream, ContentHash.from_string(key)) + if isinstance(stream, RootSource): + described = f"source {stream.source_id!r}" + elif isinstance(stream, SourceNodeBase): + described = f"slot {name!r}" + elif stream.producer is None: + described = f"raw stream {name!r}" + else: + described = f"prebuilt stream {name!r}" + try: + leaf = ref(stream) + except TypeError: + leaf = None + try: + node_hash: str | None = ( + SourceNode.from_stream(stream, name=None if declared else name) + .node_hash() + .to_string() + ) + except ( + InputValidationError, + ValueError, + TypeError, + KeyError, + AttributeError, + RuntimeError, + ): + # A leaf that cannot be a slot (a joined stream's system tags): main's + # own checks refuse it, at capture or at compile, with main's error. + node_hash = None + return CaptureLeaf( + capture_key=key, + name=name, + node_hash=node_hash, + described=described, + leaf=leaf, + declared=declared, + root=isinstance(stream, RootSource), + ) + + @staticmethod + def _refuse_one_object_twice(leaf: CaptureLeaf, known: list[CaptureLeaf]) -> None: + """Refuse one object captured through a declaration and directly (R-53/54, R-MIX).""" + mixed = [ + other + for other in known + if other.declared != leaf.declared and other.is_object(leaf) + ] + if not mixed: + return + obj = leaf.leaf() if leaf.leaf is not None else None + for other in mixed: + if other.name != leaf.name: + raise InconsistentSourceError( + _one_object_on_two_slots(obj, other.name, leaf.name) + ) + raise InconsistentSourceError( + f"The same source object is already declared under slot {leaf.name!r}. " + "Use the slot declaration or capture the source directly (ITL-1559)." + ) + + @staticmethod + def _refuse_shared_node_hash(leaf: CaptureLeaf, known: list[CaptureLeaf]) -> None: + """Refuse a second leaf whose slot takes another leaf's node hash (rows 37, 38).""" + if leaf.node_hash is None: + return + for other in known: + if ( + other.node_hash != leaf.node_hash + or other.capture_key == leaf.capture_key + ): + continue + if other.root and leaf.root: + # Two sources with one slot name: main refuses them itself, when + # capturing (one content hash) or compiling (one slot name). + continue + raise InconsistentSourceError( + f"Slot {leaf.name!r} already holds {other.described}; " + f"{leaf.described} is another object under the same name. A slot " + "holds exactly one source object until source equivalence is defined " + "(ITL-1553). Pass the same object again, or declare the second one " + "under its own slot name with SourceNode.from_stream(stream, name=...)." + ) + + def _hold_captured(self, stream: StreamProtocol) -> None: + """Keep a captured leaf's inputs, and those beneath it, as they are (ITL-1848). + + The leaf names its slot by its content, so a rewire beneath it would rename + a slot this graph holds. This graph's own compiled nodes are not held. + """ + from orcapod.core.streams.base import StreamBase + + own = {id(node) for node in self._persistent_node_map.values()} + seen: set[int] = set() + pending: list[Any] = [stream] + while pending: + current = pending.pop() + if id(current) in seen or id(current) in own: + continue + seen.add(id(current)) + if isinstance(current, StreamBase): + current._hold_for_capture(self) # pyright: ignore[reportPrivateUsage] # the capturing graph holds it + try: + pending.extend(current.upstreams) + except (AttributeError, TypeError, ValueError, RuntimeError): + continue + def _input_graph_key(self, upstream: StreamProtocol) -> str: """Return the capture graph key for an invocation input.""" return graph_hash(upstream).to_string() @@ -726,13 +952,15 @@ def _compile_nodes( node_map = self._ordered_node_map(node_map, self._hash_graph) if validate_nodes is not None: validate_nodes(node_map.values()) + # Every refusal comes before anything is published (ITL-1848). + graph_keys = self._graph_keys_for(node_map) self._persistent_node_map = node_map self._nodes.clear() self._nodes.update((node.label, node) for node in node_map.values()) # 5. Build node_graph (OrcaDAG with node objects as vertices). graph_edges = sorted(self._hash_graph.edges()) - node_dag: OrcaDAG[NodeT] = OrcaDAG() + node_dag: OrcaDAG[NodeT] = CompiledDAG() for node in node_map.values(): node_dag.add_node(node) for up_hash, down_hash in graph_edges: @@ -766,9 +994,108 @@ def _compile_nodes( h: n for h, n in node_map.items() if isinstance(n, source_node_cls) } self._graph_edges = graph_edges + self._publish_graph_keys(graph_keys) + self._pinned_slot_names.update( + (key, node.name) + for key, node in node_map.items() + if isinstance(node, source_node_cls) + ) self._compiled = True + # ------------------------------------------------------------------ + # Graph keys (ITL-1848) + # ------------------------------------------------------------------ + + def _graph_keys_for(self, node_map: Mapping[str, Any]) -> dict[str, str]: + """Give each compiled node its graph key, pinned at its first compile. + + Args: + node_map: The compiled nodes by capture key, slots first. + + Returns: + Capture key to graph key. + + Raises: + InconsistentSourceError: If a slot's name or schema, or a step's node + hash, changed since its first compile (row 87; following such a + change is ITL-1847), or two distinct nodes would share one node + hash. + """ + keys: dict[str, str] = {} + for capture_key, node in node_map.items(): + current = compiled_graph_key(node, capture_key) + pinned = self._graph_key_of.get(capture_key) + if pinned is None or is_legacy_graph_key(pinned): + keys[capture_key] = current if pinned is None else pinned + continue + if pinned != current: + if capture_key in self._pinned_slot_names: + raise InconsistentSourceError( + "Cannot recompile source slot " + f"{self._pinned_slot_names[capture_key]!r}: its name or schema " + f"changed since it was captured (now {node.name!r}) " + "(ITL-1559). Build a new pipeline or job; following such a " + "change is ITL-1847." + ) + raise InconsistentSourceError( + f"Cannot recompile step {node.label!r}: its node hash changed " + "since it was captured (ITL-1559). Build a new pipeline or job; " + "following such a change is ITL-1847." + ) + keys[capture_key] = pinned + self._require_one_node_per_graph_key(node_map, keys) + return keys + + @staticmethod + def _require_one_node_per_graph_key( + nodes: Mapping[str, Any], keys: Mapping[str, str | None] + ) -> None: + """A node hash is unique within a pipeline: refuse two nodes under one key. + + Asserted at every compile, and when a graph is built from another or loaded + (ITL-1848). Never resolved by a tie-break. + + Args: + nodes: The nodes by capture key. + keys: Each capture key's graph key (``None``: a node without one). + + Raises: + InconsistentSourceError: Naming both nodes. + """ + for _, first, second in shared_graph_keys(keys): + raise InconsistentSourceError( + f"Nodes {nodes[first].label!r} and {nodes[second].label!r} are two " + "distinct nodes with one node hash. A node hash is unique within a " + "pipeline (ITL-1559): give the slots different names, or build the " + "pipeline again with this version of Orcapod." + ) + + def _publish_graph_keys(self, keys: Mapping[str, str]) -> None: + """Re-key the compiled maps, given by capture key, to their graph keys.""" + self._persistent_node_map = rekeyed(self._persistent_node_map, keys) + self._node_lut = rekeyed(self._node_lut, keys) + self._upstreams = rekeyed(self._upstreams, keys) + self._graph_edges = rekeyed_edges(self._graph_edges, keys) + self._graph_key_of.update(keys) + self._capture_key_of = {graph: capture for capture, graph in keys.items()} + + def _capture_key(self, graph_key: str) -> str: + """The capture key of a compiled node's graph key.""" + return self._capture_key_of.get(graph_key, graph_key) + + def _compiled_key(self, capture_key: str) -> str: + """The graph key of a capture key.""" + return self._graph_key_of.get(capture_key, capture_key) + + def _capture_keyed(self, mapping: Mapping[str, _V]) -> dict[str, _V]: + """A compiled map re-keyed by capture keys, in its order.""" + return rekeyed(mapping, self._capture_key_of) + + def _capture_keyed_edges(self) -> list[tuple[str, str]]: + """The compiled edge list by capture keys, in its order.""" + return rekeyed_edges(self._graph_edges, self._capture_key_of) + @staticmethod def _ordered_node_map( nodes: dict[str, Any], graph: nx.DiGraph[str] @@ -828,7 +1155,7 @@ def to_invocations(self) -> InvocationGraph: # from _hash_graph align with inv_by_node_hash. inv_by_node_hash: dict[str, PodInvocation] = {} - for node_hash, node in self._persistent_node_map.items(): + for node_hash, node in self._capture_keyed(self._persistent_node_map).items(): if isinstance(node, source_node_cls): source_streams[ graph_hash(cast("IdentityChainProtocol", node)).to_string() @@ -920,6 +1247,10 @@ def from_invocations( require_live_source_bindings(inputs) require_consistent_sources(invocation_source_uses(graph.invocations)) instance._source_streams = dict(graph.source_streams) + instance._capture_leaves = { + key: instance._describe_capture_leaf(stream, key) + for key, stream in graph.source_streams.items() + } capture_streams = instance._capture_key_memo() for inv in graph.invocations: key, input_keys = inv.capture_keys( diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index b192a5c96..829e62612 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -18,8 +18,9 @@ from __future__ import annotations import heapq -from collections.abc import Hashable +from collections.abc import Hashable, KeysView from graphlib import CycleError, TopologicalSorter +from inspect import getattr_static from typing import ( Any, Generic, @@ -30,7 +31,9 @@ runtime_checkable, ) -__all__ = ["Comparable", "GraphProtocol", "OrcaDAG", "CycleError"] +from orcapod.errors import UndefinedGraphMembershipError + +__all__ = ["Comparable", "CompiledDAG", "GraphProtocol", "OrcaDAG", "CycleError"] class Comparable(Hashable, Protocol): @@ -366,3 +369,128 @@ def ancestors(self, node: NodeT) -> frozenset[NodeT]: visited.add(n) queue.extend(self._predecessors[n]) return frozenset(visited) + + +def _is_graph_object(node: object) -> bool: + """Whether *node* is a node, stream or pod invocation (anything with identity chains). + + Read statically, so a stream is never asked to compute anything. + """ + return getattr_static(node, "_identity_chains", None) is not None + + +def _require_held(dag: CompiledDAG[Any], node: object) -> bool: + """Answer ``in`` for a compiled DAG: a held object, or refuse any other graph object.""" + if not _is_graph_object(node): + return node in dag._attrs # pyright: ignore[reportPrivateUsage] # the DAG's own vertices + if any(vertex is node for vertex in dag._attrs): # pyright: ignore[reportPrivateUsage] # the DAG's own vertices + return True + raise UndefinedGraphMembershipError( + "Graph object membership is not defined yet (ITL-1559): this object is not " + "one of the DAG's own nodes. Access the node by label with job.nodes[label] " + "or pipeline.nodes[label]." + ) + + +class CompiledNodeView(KeysView[NodeT]): + """The vertices of a compiled DAG, as ``OrcaDAG.nodes()`` gives them. + + Everything is the plain ``dict_keys`` view's, delegated to it (set operations, + comparisons, ``repr``, ``mapping``), except ``in`` with a node, stream or + invocation that is not one of the DAG's own objects: that raises + ``UndefinedGraphMembershipError``, as ``in`` on the DAG does. + """ + + def __init__(self, dag: CompiledDAG[NodeT]) -> None: + super().__init__(dag._attrs) # pyright: ignore[reportPrivateUsage] # the DAG's own vertices + self._dag = dag + self._keys = dag._attrs.keys() # pyright: ignore[reportPrivateUsage] # the DAG's own vertices + + def __contains__(self, node: object) -> bool: + return _require_held(self._dag, node) + + def __iter__(self) -> Iterator[NodeT]: + return iter(self._keys) + + def __reversed__(self) -> Iterator[NodeT]: + return reversed(self._keys) + + def __len__(self) -> int: + return len(self._keys) + + def __repr__(self) -> str: + return repr(self._keys) + + @property + def mapping(self) -> Any: + """The attribute mapping behind the view, as ``dict_keys.mapping`` gives it.""" + return self._keys.mapping + + @staticmethod + def _plain(other: object) -> Any: + return other._keys if isinstance(other, CompiledNodeView) else other + + def __eq__(self, other: object) -> bool: + return self._keys == self._plain(other) + + def __ne__(self, other: object) -> bool: + return self._keys != self._plain(other) + + def __le__(self, other: Any) -> bool: + return self._keys <= self._plain(other) + + def __lt__(self, other: Any) -> bool: + return self._keys < self._plain(other) + + def __ge__(self, other: Any) -> bool: + return self._keys >= self._plain(other) + + def __gt__(self, other: Any) -> bool: + return self._keys > self._plain(other) + + def __and__(self, other: Any) -> Any: + return self._keys & self._plain(other) + + def __rand__(self, other: Any) -> Any: + return self._plain(other) & self._keys + + def __or__(self, other: Any) -> Any: + return self._keys | self._plain(other) + + def __ror__(self, other: Any) -> Any: + return self._plain(other) | self._keys + + def __sub__(self, other: Any) -> Any: + return self._keys - self._plain(other) + + def __rsub__(self, other: Any) -> Any: + return self._plain(other) - self._keys + + def __xor__(self, other: Any) -> Any: + return self._keys ^ self._plain(other) + + def __rxor__(self, other: Any) -> Any: + return self._plain(other) ^ self._keys + + def isdisjoint(self, other: Iterable[Any]) -> bool: + return self._keys.isdisjoint(other) + + __hash__ = None # pyright: ignore[reportAssignmentType] # unhashable, as dict_keys + + +class CompiledDAG(OrcaDAG[NodeT]): + """The DAG a pipeline or job publishes as ``dag`` after compiling. + + The same structure and answers as ``OrcaDAG``, except membership (ITL-1559): + ``node in dag`` and ``node in dag.nodes()`` answer ``True`` for the DAG's own + node objects and raise ``UndefinedGraphMembershipError`` for any other node, + stream or pod invocation, even one that compares equal. Other operands (a + string, a number) answer as on ``OrcaDAG``. + """ + + def __contains__(self, node: object) -> bool: + return _require_held(self, node) + + def nodes(self) -> CompiledNodeView[NodeT]: + """Return the vertices in insertion order (see the class docstring).""" + return CompiledNodeView(self) diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 9c6304cbf..0f91f6b61 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -17,7 +17,8 @@ from orcapod.side_effects import SideEffectNode from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.pipeline.base import AbstractPipelineBase -from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.dag import CompiledDAG +from orcapod.pipeline.graph_keys import legacy_graph_key, loaded_node_hash from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ReservedColumnNameError @@ -153,8 +154,11 @@ def save(self, path: str | Path) -> None: # A slot's column types, from the one writer (``saved_type_texts``): its # output_schema and its source_config are both this entry (ITL-640). slot_types: dict[str, dict[str, Any]] = {} + # A file names each node by its capture key, as before ITL-1848; saved + # files record node hashes in step 4 (ITL-1864). + node_map = self._capture_keyed(self._persistent_node_map) with shared_zero_row_memo(): - for key, node in self._persistent_node_map.items(): + for key, node in node_map.items(): if isinstance(node, SourceNodeClass): try: slot_types[key] = node.saved_type_texts() @@ -173,8 +177,8 @@ 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(): + key_of = {id(node): key for key, node in node_map.items()} + for content_hash_str, node in node_map.items(): try: type_converter = node.data_context.type_converter except (AttributeError, TypeError): @@ -306,7 +310,7 @@ def save(self, path: str | Path) -> None: "orcapod_version": orcapod.__version__, "pipeline": {"name": list(self._name)}, "nodes": nodes, - "edges": [list(edge) for edge in self._graph_edges], + "edges": [list(edge) for edge in self._capture_keyed_edges()], } path = Path(path) @@ -650,7 +654,7 @@ def load(cls, path: str | Path) -> "Pipeline": nodes_by_label[node.label] = node pipeline._nodes = nodes_by_label - node_dag: OrcaDAG[GraphNode] = OrcaDAG() + node_dag: CompiledDAG[GraphNode] = CompiledDAG() for node in reconstructed.values(): node_dag.add_node(node) for up_hash, down_hash in edges: @@ -683,6 +687,17 @@ def load(cls, path: str | Path) -> "Pipeline": h: n for h, n in reconstructed.items() if n.node_type == "source" } + # A loaded node is held under ``legacy:`` and its saved key until saved + # files record node hashes (ITL-1864); a file in which two distinct nodes + # share one node hash is refused (ITL-1848). + pipeline._require_one_node_per_graph_key( + reconstructed, + {key: loaded_node_hash(node) for key, node in reconstructed.items()}, + ) + pipeline._publish_graph_keys( + {key: legacy_graph_key(key) for key in reconstructed} + ) + pipeline._compiled = True return pipeline @@ -717,6 +732,10 @@ def _clone_for_execution(self) -> "Pipeline": clone._graph_edges = self._graph_edges clone._hash_graph = self._hash_graph clone._persistent_node_map = self._persistent_node_map + clone._graph_key_of = self._graph_key_of + clone._capture_key_of = self._capture_key_of + clone._pinned_slot_names = self._pinned_slot_names + clone._capture_leaves = self._capture_leaves clone._node_graph = self._node_graph clone._auto_compile = self._auto_compile clone._compiled = self._compiled diff --git a/src/orcapod/pipeline/graph_keys.py b/src/orcapod/pipeline/graph_keys.py new file mode 100644 index 000000000..7235fe25b --- /dev/null +++ b/src/orcapod/pipeline/graph_keys.py @@ -0,0 +1,100 @@ +"""Keys of a compiled pipeline graph (ITL-1848). + +A pipeline or job records its captures under capture keys (the content hash of a +bound capture, the name-based hash of an unbound one), as before. Its compiled +graph holds each node under the node's node hash instead, or, for a node that has +none (a custom operator, and anything downstream of one), under ``legacy:`` and its +capture key. A graph loaded from a file keys every node by ``legacy:`` and its saved +key until saved files record node hashes (ITL-1864). + +The two keys are one to one: one capture key is one node, and a node hash is unique +within a pipeline. Two distinct nodes with one node hash are refused, never told +apart by a tie-break. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from typing import Any, TypeVar + +from orcapod.core.identity_chains import UndefinedIdentityError + +LEGACY_KEY_PREFIX = "legacy:" + +_V = TypeVar("_V") + + +def legacy_graph_key(capture_key: str) -> str: + """The graph key of a node that has no node hash, or of a loaded node.""" + return f"{LEGACY_KEY_PREFIX}{capture_key}" + + +def is_legacy_graph_key(graph_key: str) -> bool: + """Whether *graph_key* is a capture key under ``legacy:``, not a node hash.""" + return graph_key.startswith(LEGACY_KEY_PREFIX) + + +def compiled_graph_key(node: Any, capture_key: str) -> str: + """The key a compiled graph holds *node* under. + + Args: + node: A compiled node. + capture_key: The key its capture was recorded under. + + Returns: + The node's node hash as text, or ``legacy:`` when the node has + no node hash in this step. + """ + try: + return node.node_hash().to_string() + except UndefinedIdentityError: + return legacy_graph_key(capture_key) + + +def loaded_node_hash(node: Any) -> str | None: + """The node hash of a node loaded from a file, where it is defined. + + Returns: + The node hash as text, or ``None`` for a node whose identity cannot be read + (a read-only node without its pod, a custom operator). + """ + try: + return node.node_hash().to_string() + except (ValueError, TypeError, KeyError, AttributeError, RuntimeError): + return None + + +def shared_graph_keys( + keys: Mapping[str, str | None], +) -> list[tuple[str, str, str]]: + """Find distinct capture keys that share one graph key. + + Args: + keys: Capture key to graph key (``None`` for a node without one, never + shared). + + Returns: + ``(graph key, first capture key, second capture key)`` for each capture key + whose graph key an earlier one already holds, in the mapping's order. + """ + holder: dict[str, str] = {} + shared: list[tuple[str, str, str]] = [] + for capture_key, graph_key in keys.items(): + if graph_key is None: + continue + first = holder.setdefault(graph_key, capture_key) + if first != capture_key: + shared.append((graph_key, first, capture_key)) + return shared + + +def rekeyed(mapping: Mapping[str, _V], keys: Mapping[str, str]) -> dict[str, _V]: + """Re-key *mapping* through *keys*, keeping its order; unknown keys stay as given.""" + return {keys.get(key, key): value for key, value in mapping.items()} + + +def rekeyed_edges( + edges: Iterable[tuple[str, str]], keys: Mapping[str, str] +) -> list[tuple[str, str]]: + """Re-key an edge list through *keys*, keeping its order.""" + return [(keys.get(up, up), keys.get(down, down)) for up, down in edges] diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 7ac378968..4738ae21c 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -35,7 +35,12 @@ UnboundSourceError, ) from orcapod.pipeline.base import AbstractPipelineBase -from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.dag import CompiledDAG, OrcaDAG +from orcapod.pipeline.graph_keys import ( + compiled_graph_key, + is_legacy_graph_key, + legacy_graph_key, +) from orcapod.pipeline.node_run import ( RunPlan, check_sources, @@ -365,7 +370,7 @@ def _input_graph_key(self, upstream: cp.StreamProtocol) -> str: if isinstance(upstream, SourceJobNode): for key, slot in self._persistent_node_map.items(): if slot is upstream: - return key + return self._capture_key(key) return super()._input_graph_key(upstream) def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> None: @@ -440,8 +445,11 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse for key, stream in self._source_streams.items(): if key in self._invocation_lut: continue - slot = self._persistent_node_map.get(key) - if key in self._rebound_source_keys and isinstance(slot, SourceJobNode): + compiled_key = self._compiled_key(key) + slot = self._persistent_node_map.get(compiled_key) + if compiled_key in self._rebound_source_keys and isinstance( + slot, SourceJobNode + ): yield f"node {slot.label!r}", slot else: yield f"source {stream.label!r}", stream @@ -451,8 +459,9 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse def _source_node_from_recording(self, key: str) -> SourceJobNode: """Preserve an explicit binding when recompiling its slot.""" stream = self._source_streams[key] - if key in self._rebound_source_keys: - slot = self._persistent_node_map.get(key) + compiled_key = self._compiled_key(key) + if compiled_key in self._rebound_source_keys: + slot = self._persistent_node_map.get(compiled_key) if isinstance(slot, SourceJobNode): stream = slot source = stream.bound_source if isinstance(stream, SourceJobNode) else stream @@ -1121,8 +1130,11 @@ def as_pipeline(self) -> "Pipeline": # valid for the blueprint nodes. bp_hash_graph = _nx.DiGraph() for old_h, new_h in old_to_new.items(): + captured = self._capture_key(old_h) old_attrs = ( - dict(self._hash_graph.nodes[old_h]) if old_h in self._hash_graph else {} + dict(self._hash_graph.nodes[captured]) + if captured in self._hash_graph + else {} ) bp_hash_graph.add_node(new_h, **old_attrs) new_graph_edges = sorted( @@ -1151,13 +1163,24 @@ def as_pipeline(self) -> "Pipeline": # Build _node_graph (OrcaDAG with node objects as vertices). # node_map here contains GraphNode objects (blueprint nodes). - bp_dag: OrcaDAG = OrcaDAG() + bp_dag: OrcaDAG = CompiledDAG() for node in pipeline._persistent_node_map.values(): bp_dag.add_node(node) for up_h, down_h in new_graph_edges: bp_dag.add_edge(new_node_map[up_h], new_node_map[down_h]) pipeline._node_graph = bp_dag + # The blueprint's graph keys (ITL-1848): each node's node hash, or its + # capture key under legacy: where the job's node has none or was loaded. + blueprint_keys = { + new_h: legacy_graph_key(new_h) + if is_legacy_graph_key(old_h) + else compiled_graph_key(new_node_map[new_h], new_h) + for old_h, new_h in old_to_new.items() + } + pipeline._require_one_node_per_graph_key(new_node_map, blueprint_keys) # pyright: ignore[reportPrivateUsage] # the blueprint is built here + pipeline._publish_graph_keys(blueprint_keys) # pyright: ignore[reportPrivateUsage] # the blueprint is built here + pipeline._compiled = True return pipeline @@ -1252,11 +1275,12 @@ def is_runnable(self, node_label: str) -> bool: target_hash = node_id_to_hash.get(id(target)) if target_hash is None: return False + target_hash = self._capture_key(target_hash) import networkx as nx for h in nx.ancestors(self._hash_graph, target_hash) | {target_hash}: - node = self._persistent_node_map.get(h) + node = self._persistent_node_map.get(self._compiled_key(h)) if isinstance(node, SourceJobNode) and node.bound_source is None: return False return True @@ -1644,12 +1668,13 @@ def _prepare_run( continue # below an unbound source: not part of this run if not isinstance(node, (FunctionJobNode, OperatorJobNode)): continue - if node_hash not in self._hash_graph: + capture_key = self._capture_key(node_hash) + if capture_key not in self._hash_graph: continue missing = [ upstream - for upstream in self._hash_graph.predecessors(node_hash) - if upstream not in self._persistent_node_map + for upstream in self._hash_graph.predecessors(capture_key) + if self._compiled_key(upstream) not in self._persistent_node_map ] if missing: raise RuntimeError( @@ -2513,13 +2538,16 @@ def load( job._compiled = True # Populate _upstreams / _node_lut / _graph_edges / _hash_graph from pipeline. - job._upstreams = dict(pipeline._upstreams) - job._node_lut = dict(pipeline._node_lut) - job._graph_edges = list(pipeline._graph_edges) + # The job is built by saved (capture) keys, then holds its nodes under the + # loaded pipeline's graph keys (``legacy:`` and the saved key until ITL-1864). + bp_map = pipeline._capture_keyed(pipeline._persistent_node_map) # pyright: ignore[reportPrivateUsage] # the loader reads the loaded pipeline + job._upstreams = pipeline._capture_keyed(pipeline._upstreams) # pyright: ignore[reportPrivateUsage] # the loader reads the loaded pipeline + job._node_lut = pipeline._capture_keyed(pipeline._node_lut) # pyright: ignore[reportPrivateUsage] # the loader reads the loaded pipeline + job._graph_edges = pipeline._capture_keyed_edges() # pyright: ignore[reportPrivateUsage] # the loader reads the loaded pipeline job._hash_graph = pipeline._hash_graph.copy() # Populate _persistent_node_map with job-node instances for ALL node types, - # keyed by the same hash keys as pipeline._persistent_node_map. + # keyed by the same hash keys as bp_map. # # SourceJobNode stubs must be present so that bind() can locate source slots # and update them in-place. FunctionJobNode and OperatorJobNode stubs must @@ -2554,14 +2582,14 @@ def load( unbound_slots = set(run_block.get("unbound_sources", ())) unbound_nodes = { - pipeline._persistent_node_map[downstream].label - for key, slot in pipeline._persistent_node_map.items() + bp_map[downstream].label + for key, slot in bp_map.items() if isinstance(slot, SourceNodeBase) and slot.name in unbound_slots for downstream in descendants(pipeline._hash_graph, key) } unrecorded = sorted( bp_node.label - for bp_node in pipeline._persistent_node_map.values() + for bp_node in bp_map.values() if isinstance(bp_node, (_FunctionNode, _OperatorNode, SideEffectNode)) and ( bp_node.label not in node_job_content_hashes @@ -2587,7 +2615,7 @@ def load( # is the source of truth. expected_rows: dict[str, int] = run_block.get("expected_rows", {}) - for node_hash, bp_node in pipeline._persistent_node_map.items(): + for node_hash, bp_node in bp_map.items(): if isinstance(bp_node, _SourceNode): # Keeps the loaded slot's saved hashes and saved type texts (ITL-1138). sjn = SourceJobNode._from_loaded_slot( # pyright: ignore[reportPrivateUsage] # the loader is the one caller @@ -2655,9 +2683,7 @@ def load( # Update _nodes to point to job nodes (FunctionJobNode/OperatorJobNode stubs) # rather than blueprint nodes, so that job.nodes["label"].get_all_records() # works on a loaded job. - bp_id_to_hash: dict[int, str] = { - id(bp): h for h, bp in pipeline._persistent_node_map.items() - } + bp_id_to_hash: dict[int, str] = {id(bp): h for h, bp in bp_map.items()} job._nodes = { label: job._persistent_node_map.get( bp_id_to_hash.get(id(bp_node), ""), bp_node @@ -2671,7 +2697,8 @@ def load( # 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() + job._publish_graph_keys(pipeline._graph_key_of) # pyright: ignore[reportPrivateUsage] # the loaded pipeline's graph keys + job_dag: OrcaDAG = CompiledDAG() for node in job._persistent_node_map.values(): if isinstance(node, RunHoldingNode): node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py index 2abd451a1..7cbfd6974 100644 --- a/tests/test_core/test_tracker.py +++ b/tests/test_core/test_tracker.py @@ -590,7 +590,11 @@ def test_record_function_pod_stores_edge(self): tracker.compile() assert len(tracker._graph_edges) == 1 upstream_hash, node_hash = tracker._graph_edges[0] - assert upstream_hash == stream.content_hash().to_string() + # Compiled maps hold nodes under their node hash (ITL-1848). + assert upstream_hash == tracker._compiled_key(stream.content_hash().to_string()) + assert ( + upstream_hash == tracker._upstreams[upstream_hash].node_hash().to_string() + ) assert node_hash in tracker._node_lut def test_record_function_pod_stores_upstream_stream(self): @@ -611,8 +615,10 @@ def test_record_function_pod_stores_upstream_stream(self): tracker.compile() from orcapod.core.nodes.source_node import SourceNode - assert stream_hash in tracker._upstreams - assert isinstance(tracker._upstreams[stream_hash], SourceNode) + # Compiled maps hold nodes under their node hash (ITL-1848). + assert isinstance( + tracker._upstreams[tracker._compiled_key(stream_hash)], SourceNode + ) def test_record_operator_pod_creates_operator_node(self): stream = _make_stream() diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index 1cefe7e45..f0e320f82 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -1680,17 +1680,32 @@ def test_capture_distinguishes_joins_by_multiplicity( def test_capture_keys_follow_a_rewired_join() -> None: - """A key memo must pick up a changed repeat count through a held stream.""" + """A key memo must pick up a changed repeat count through a held stream. + + Since ITL-1848 a captured input cannot be rewired (REWIRE-87; following it is + ITL-1847): the rewire is refused and the graph keeps what it captured. A join + rewired before any capture is captured with its new repeat count. + """ from orcapod.core.nodes.operator_node import OperatorNode + from orcapod.errors import InconsistentSourceError a, b = _data_tags("a"), _data_tags("b") stream = OperatorNode(Join(), (a, b), label="external") graph = Pipeline("rewired") with graph: _ = stream.select_tag_columns(["region", "item"], label="original") - stream.upstreams = (a, b, b) - _ = stream.select_tag_columns(["region", "item"], label="rewired") - assert {"original", "rewired"} <= set(graph.nodes) + with pytest.raises(InconsistentSourceError, match="ITL-1847"): + stream.upstreams = (a, b, b) + assert len(stream.upstreams) == 2 + assert "original" in graph.nodes + + fresh = OperatorNode(Join(), (a, b), label="fresh") + fresh.upstreams = (a, b, b) + other = Pipeline("rewired before capture") + with other: + _ = fresh.select_tag_columns(["region", "item"], label="rewired") + assert len(other.nodes["rewired"].upstreams) == 1 + assert len(fresh.upstreams) == 3 @pytest.mark.parametrize("reverse", [False, True]) diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py new file mode 100644 index 000000000..533da692d --- /dev/null +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -0,0 +1,665 @@ +"""Compiled graphs keyed by node hash behave as main, but for the accepted refusals. + +ITL-1848 (step 3 of ITL-1559) keys a compiled pipeline's or job's nodes by node hash. The +governing condition is that nothing changes main's behaviour without a solid reason. Each +case below runs in this checkout and, in a separate interpreter, on the reviewed main +commit (``MAIN``, extracted with ``git archive``), and the two outcomes are compared. Every +difference is named by its code and asserted on both sides: + +- R-IN: ``object in compiled_dag`` is refused for an object that is not one of the DAG's + own nodes (``UndefinedGraphMembershipError``); main compared by equality. +- R-GRAPH: the ``graph`` attribute of a pipeline or job is gone. +- R-53/54: one source object read through an explicit slot and directly, one name. +- R-MIX: the same, under two names. +- ROWS-37-38: an explicit slot and another source object with the same name (two slots + with one node hash). +- REWIRE-87: setting a captured step's ``upstreams`` to other streams. +- LOAD-DUP: loading a pipeline file in which two distinct nodes share one node hash. + +Everything else (labels, the compiled DAG, rows, stored tables, saved bytes, bind, rebind, +unbind and the ITL-1469 refusals) must be identical. When the main commit is not available +(a shallow clone), only this checkout's outcome is checked. +""" + +from __future__ import annotations + +import asyncio +import io +import json +import os +import subprocess +import sys +from collections.abc import Callable +from datetime import datetime, timezone, tzinfo +from itertools import count +from pathlib import Path +from types import SimpleNamespace +from typing import Any, cast +from unittest.mock import patch +from uuid import UUID +from zipfile import ZipFile + +import pytest +from deltalake import DeltaTable +from typing_extensions import override + +from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.nodes.function_node import FunctionJobNode, FunctionNode +from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNode +from orcapod.core.operators import Join, SelectDataColumns +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.sources import DictSource + +ROOT = Path(__file__).resolve().parents[2] +MAIN = "2075e85e2c9418444ec5368e800f71d354fd0b5e" +MODES = ["sync", "async"] +FIXED_RUN_ID = UUID("01234567-89ab-4def-8abc-0123456789ab") + + +@function_pod(output_keys="doubled") +def double(x: int) -> int: + return 2 * x + + +@function_pod(output_keys="tripled") +def triple(x: int) -> int: + return 3 * x + + +@function_pod(output_keys="plus") +def plus_one(doubled: int) -> int: + return doubled + 1 + + +@function_pod(output_keys="total") +def total(x: int, y: int) -> int: + return x + y + + +def source(name: str, base: int, *, column: str = "x") -> DictSource: + """Two tag columns and two data columns, so every step sees several of each.""" + return DictSource( + [ + {"id": 1, "part": "p", column: base, f"{column}_note": "n"}, + {"id": 2, "part": "q", column: base + 1, f"{column}_note": "m"}, + ], + source_id=name, + tag_columns=["id", "part"], + tag_only_columns=True, + ) + + +class FrozenClock(datetime): + @classmethod + @override + def now(cls, tz: tzinfo | None = None) -> datetime: + return cls(2026, 1, 1, tzinfo=timezone.utc).astimezone(tz) + + +def caught(action: Callable[[], Any]) -> Any: + """The action's value, or its error's class name and text.""" + try: + return ["ok", action()] + except Exception as error: # noqa: BLE001 # the outcome is what is compared + return [type(error).__name__, str(error)] + + +def run(job: PipelineJob, mode: str, *, load_only: bool = False) -> None: + if mode == "async": + _ = asyncio.run(job.run_async(load_only=load_only)) + else: + _ = job.run(load_only=load_only) + + +def rows(graph: Pipeline | PipelineJob) -> dict[str, Any]: + """Every computed node's rows, sorted (row order is not guaranteed).""" + result = {} + for label, node in sorted(graph.nodes.items()): + if node.node_type == "source": + continue + table = node.as_table() + result[label] = sorted(map(repr, table.to_pylist())) + return result + + +def listing(graph: Pipeline | PipelineJob) -> dict[str, Any]: + """The public shape of a compiled graph, by label.""" + dag = graph.dag + return { + "labels": sorted(graph.nodes), + "kinds": {label: node.node_type for label, node in sorted(graph.nodes.items())}, + "dag_nodes": sorted(node.label for node in dag.nodes()), + "edges": sorted([up.label, down.label] for up, down in dag.edges()), + "topological": [node.label for node in dag.topological_sort()] + if len(graph.nodes) < 2 + else sorted(node.label for node in dag.topological_sort()), + "pipeline_hashes": { + label: node.pipeline_hash().to_string() + for label, node in sorted(graph.nodes.items()) + }, + "own_members": all(node in dag for node in graph.nodes.values()), + } + + +def saved(job: PipelineJob, path: Path) -> str: + with patch("orcapod.__version__", "0.4.0"): + job.save(path) + return path.read_text() + + +def frozen_run(job: PipelineJob, mode: str) -> None: + """Run with every generated id and time fixed, so stored tables compare.""" + results = count(1) + with ( + patch( + "orcapod.core.data_function.uuid7", + side_effect=lambda: UUID(int=next(results)), + ), + patch("orcapod.core.result_cache.datetime", FrozenClock), + patch("orcapod.core.nodes.function_node.datetime", FrozenClock), + patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: FIXED_RUN_ID)), + ): + run(job, mode) + + +def stored_tables(path: Path) -> dict[str, Any]: + tables = {} + for log in sorted(path.rglob("_delta_log")): + table = DeltaTable(str(log.parent)).to_pyarrow_table() + tables[str(log.parent.relative_to(path))] = { + "schema": str(table.schema), + "rows": sorted(map(repr, table.to_pylist())), + } + return tables + + +# --------------------------------------------------------------------------- +# Cases that must match main exactly +# --------------------------------------------------------------------------- + + +def lifecycle_case(directory: Path, mode: str) -> dict[str, Any]: + """Capture, compile, run, store, save, load and run a several-step job.""" + database = DeltaTableDatabase(directory / "db") + job = PipelineJob("compat", database=database) + with job: + a, b = source("a", 3), source("b", 10, column="y") + double.pod(SelectDataColumns(["x"])(a, label="pick_a"), label="double_a") + joined = Join()(b, a, label="joined") + total.pod(SelectDataColumns(["x", "y"])(joined), label="total") + triple.pod(SourceNode.from_stream(source("c", 5), name="c"), label="triple_c") + outcome: dict[str, Any] = { + "captured": listing(job), + "blueprint": listing(job.pipeline), + } + job.compile() + outcome["recompiled"] = listing(job) + frozen_run(job, mode) + outcome["rows"] = rows(job) + outcome["stored"] = stored_tables(directory / "db") + outcome["saved"] = saved(job, directory / "job.json") + loaded = PipelineJob.load(directory / "job.json", database=database) + outcome["loaded"] = listing(loaded) + outcome["loaded_stored"] = { + label: getattr(node.get_all_records(), "num_rows", None) + for label, node in sorted(loaded.nodes.items()) + if node.node_type != "source" + } + run(loaded, mode, load_only=True) + outcome["loaded_rows"] = rows(loaded) + with patch("orcapod.__version__", "0.4.0"): + job.pipeline.save(directory / "pipeline.json") + outcome["blueprint_saved"] = (directory / "pipeline.json").read_text() + blueprint = Pipeline.load(directory / "pipeline.json") + outcome["blueprint_loaded"] = listing(blueprint) + return outcome + + +def bind_case(directory: Path, mode: str) -> dict[str, Any]: + """Bind, rebind, unbind, the setter, a swap, and each ITL-1469 refusal.""" + database = InMemoryArrowDatabase() + first, second = source("a", 3), source("b", 20) + job = PipelineJob("binding", database=database) + with job: + double.pod(SourceNode.from_stream(first, name="left"), label="left_doubled") + double.pod(SourceNode.from_stream(second, name="right"), label="right_doubled") + job.bind(sources={"left": first, "right": second}) + steps: dict[str, Any] = {} + + def state() -> dict[str, Any]: + return { + "sources": { + name: getattr(bound, "source_id", None) + for name, bound in sorted(job.sources.items()) + }, + "unbound": sorted(job.unbound_sources), + "runnable": {label: job.is_runnable(label) for label in sorted(job.nodes)}, + } + + def run_and_read() -> dict[str, Any]: + frozen_run(job, mode) + return rows(job) + + steps["initial"] = [state(), caught(run_and_read)] + replacement = source("a_v2", 30) + steps["rebind"] = [caught(lambda: job.bind(sources={"left": replacement}))] + steps["rebind"] += [state(), caught(run_and_read)] + + def capture_after_rebind() -> None: + with job: + double.pod(source("late", 1), label="late") + + steps["capture_after_rebind"] = caught(capture_after_rebind) + unbinding: dict[str, Any] = {"right": None} # None unbinds a slot + steps["unbind"] = [caught(lambda: job.bind(sources=unbinding)), state()] + steps["run_unbound"] = caught(run_and_read) + + def setter() -> None: + job.nodes["right"].bound_source = second # pyright: ignore[reportAttributeAccessIssue] # a source slot + + steps["setter"] = [caught(setter), state(), caught(run_and_read)] + steps["swap"] = [ + caught(lambda: job.bind(sources={"left": second, "right": replacement})), + state(), + caught(run_and_read), + ] + steps["restore"] = [ + caught(lambda: job.bind(sources={"left": first, "right": second})), + state(), + ] + steps["own_node"] = caught( + lambda: job.bind(sources={"left": job.nodes["right_doubled"].as_source()}) + ) + + other = PipelineJob("other", database=InMemoryArrowDatabase()) + with other: + double.pod(SourceNode.from_stream(source("o", 7), name="slot"), label="o") + + def foreign_slot() -> None: + with job: + triple.pod(other.nodes["slot"], label="foreign") + + steps["foreign_slot"] = caught(foreign_slot) + prebuilt = triple.pod(job.nodes["left"]) + + def prebuilt_over_own_slot() -> None: + with job: + double.pod(SelectDataColumns(["tripled"])(prebuilt), label="prebuilt") + + steps["prebuilt"] = caught(prebuilt_over_own_slot) + steps["final"] = [state(), caught(run_and_read)] + steps["saved"] = caught(lambda: saved(job, directory / "bound.json")) + return steps + + +class CommutativeJoin(Join): + """A custom operator: no node hash, held under ``legacy:`` and its capture key.""" + + +class OrderedJoin(Join): + def argument_symmetry(self, streams: Any) -> Any: + return tuple(streams) + + +def custom_operator_case(directory: Path, kind: str, mode: str) -> dict[str, Any]: + operator_class = {"commutative": CommutativeJoin, "ordered": OrderedJoin}[kind] + job = PipelineJob("custom", database=InMemoryArrowDatabase()) + with job: + left, right = source("a", 3), source("b", 10, column="y") + operator = operator_class() + total.pod( + SelectDataColumns(["x", "y"])(operator(left, right, label="ab")), + label="ab_total", + ) + total.pod( + SelectDataColumns(["x", "y"])(operator(right, left, label="ba")), + label="ba_total", + ) + outcome = {"listing": listing(job)} + run(job, mode) + outcome["rows"] = rows(job) + return outcome + + +# --------------------------------------------------------------------------- +# Cases with an accepted difference +# --------------------------------------------------------------------------- + + +def membership_case(receiver: str) -> dict[str, Any]: + """R-IN and R-GRAPH.""" + + def build() -> Pipeline | PipelineJob: + graph = ( + PipelineJob("members", database=InMemoryArrowDatabase()) + if receiver == "job" + else Pipeline("members") + ) + with graph: + double.pod(source("root", 3), label="result") + return graph + + graph, other = build(), build() + own, foreign = graph.nodes["result"], other.nodes["result"] + return { + "own": caught(lambda: own in graph.dag), + "own_view": caught(lambda: own in graph.dag.nodes()), + "foreign": caught(lambda: foreign in graph.dag), + "foreign_view": caught(lambda: foreign in graph.dag.nodes()), + "foreign_stream": caught(lambda: source("root", 3) in graph.dag), + "label": caught(lambda: "result" in graph.nodes), + "graph_attribute": hasattr(graph, "graph"), + } + + +def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: + """R-53/54, R-MIX and ROWS-37-38, in either capture order.""" + graph = ( + PipelineJob("capture", database=InMemoryArrowDatabase()) + if receiver == "job" + else Pipeline("capture") + ) + shared = source("a", 3) + if case == "slot-and-direct": # R-53/54 + steps = [ + lambda: double.pod(SourceNode.from_stream(shared, name="a"), label="slot"), + lambda: triple.pod(shared, label="direct"), + ] + elif case == "slot-and-direct-renamed": # R-MIX + steps = [ + lambda: double.pod(SourceNode.from_stream(shared, name="b"), label="slot"), + lambda: triple.pod(shared, label="direct"), + ] + else: # ROWS-37-38: slot x over one object, a root named x + steps = [ + lambda: double.pod( + SourceNode.from_stream(source("other", 8), name="a"), label="slot" + ), + lambda: triple.pod(shared, label="direct"), + ] + if order == "reversed": + steps.reverse() + + def capture() -> list[str]: + with graph: + for step in steps: + step() + return sorted(graph.nodes) + + return {"capture": caught(capture)} + + +def rewire_case(kind: str, receiver: str) -> dict[str, Any]: + """REWIRE-87: a captured descriptor's inputs are fixed; the same ones are accepted.""" + first, second = source("a", 3), source("b", 9) + descriptor: Any + replacement: tuple[Any, ...] = (second,) + if kind == "operator": + descriptor_class = OperatorNode if receiver == "pipeline" else OperatorJobNode + descriptor = descriptor_class( + SelectDataColumns(["x"]), (first,), label="descriptor" + ) + else: + descriptor_class = FunctionNode if receiver == "pipeline" else FunctionJobNode + # A function reads exactly its parameters: give it the one column. + descriptor = descriptor_class( + cast("Any", double.pod), SelectDataColumns(["x"])(first), label="descriptor" + ) + replacement = (SelectDataColumns(["x"])(second),) + graph = ( + PipelineJob("rewire", database=InMemoryArrowDatabase()) + if receiver == "job" + else Pipeline("rewire") + ) + with graph: + if kind == "operator": + double.pod(descriptor, label="downstream") + else: + plus_one.pod(descriptor, label="downstream") + inputs = tuple(descriptor.upstreams) + + def same() -> list[str]: + descriptor.upstreams = inputs + graph.compile() + return sorted(graph.nodes) + + def other() -> list[str]: + descriptor.upstreams = replacement + graph.compile() + return sorted(graph.nodes) + + return {"same": caught(same), "other": caught(other)} + + +def shared_node_hash_file(path: Path) -> dict[str, Any]: + """Save, where main allows it, a pipeline holding two nodes with one node hash. + + A pipeline file names its nodes by capture key, so it keeps both. (Main's job file + keys its blueprint by node hash and keeps only one of the two.) + """ + pipeline = Pipeline("dup") + with pipeline: + double.pod(SourceNode.from_stream(source("other", 8), name="a"), label="slot") + triple.pod(source("a", 3), label="direct") + + def save() -> list[str]: + with patch("orcapod.__version__", "0.4.0"): + pipeline.save(path) + return sorted(pipeline.nodes) + + return {"saved": caught(save)} + + +def load_case(path: Path) -> dict[str, Any]: + """LOAD-DUP: load a pipeline file another revision wrote.""" + return {"pipeline": caught(lambda: sorted(Pipeline.load(path).nodes))} + + +# --------------------------------------------------------------------------- +# The two interpreters +# --------------------------------------------------------------------------- + + +@pytest.fixture(scope="module") +def main_package(tmp_path_factory: pytest.TempPathFactory) -> Path | None: + archive = subprocess.run( + ["git", "archive", "--format=zip", MAIN, "src"], + cwd=ROOT, + capture_output=True, + check=False, + ) + if archive.returncode: + return None + path = tmp_path_factory.mktemp("itl-1848-main") + with ZipFile(io.BytesIO(archive.stdout)) as contents: + contents.extractall(path) + return path / "src" + + +def probe(package: Path, *args: str, cwd: Path = ROOT) -> Any: + """Run one case in a fresh interpreter importing Orcapod from *package*. + + A case that saves a file runs in its own directory (*cwd*) on relative paths, so + the saved bytes of the two revisions compare. + """ + output = subprocess.check_output( + [sys.executable, str(Path(__file__).resolve()), *args], + cwd=cwd, + env={**os.environ, "PYTHONPATH": os.pathsep.join(map(str, (package, ROOT)))}, + text=True, + timeout=300, + ) + return json.loads(output) + + +def both(main_package: Path | None, *args: str) -> tuple[Any, Any]: + """This checkout's outcome and main's (``None`` when main is not available).""" + branch = probe(ROOT / "src", *args) + return branch, None if main_package is None else probe(main_package, *args) + + +def dispatch(args: list[str]) -> Any: + name, rest = args[0], args[1:] + if name == "lifecycle": + return lifecycle_case(Path(rest[0]), rest[1]) + if name == "bind": + return bind_case(Path(rest[0]), rest[1]) + if name == "custom": + return custom_operator_case(Path(rest[0]), rest[1], rest[2]) + if name == "membership": + return membership_case(rest[0]) + if name == "capture": + return capture_case(rest[0], rest[1], rest[2]) + if name == "rewire": + return rewire_case(rest[0], rest[1]) + if name == "save-dup": + return shared_node_hash_file(Path(rest[0])) + if name == "load": + return load_case(Path(rest[0])) + raise ValueError(name) + + +@pytest.mark.parametrize("mode", MODES) +def test_lifecycle_rows_stores_and_saved_bytes_match_main( + main_package: Path | None, tmp_path: Path, mode: str +) -> None: + (tmp_path / "branch").mkdir() + branch = probe(ROOT / "src", "lifecycle", "work", mode, cwd=tmp_path / "branch") + assert branch["rows"]["double_a"] == sorted( + map( + repr, + [ + {"id": 1, "part": "p", "doubled": 6}, + {"id": 2, "part": "q", "doubled": 8}, + ], + ) + ) + if main_package is not None: + (tmp_path / "main").mkdir() + assert branch == probe( + main_package, "lifecycle", "work", mode, cwd=tmp_path / "main" + ) + + +@pytest.mark.parametrize("mode", MODES) +def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( + main_package: Path | None, tmp_path: Path, mode: str +) -> None: + (tmp_path / "branch").mkdir() + branch = probe(ROOT / "src", "bind", "work", mode, cwd=tmp_path / "branch") + assert branch["initial"][1][0] == "ok" + assert branch["own_node"][0] == "SourceSpecMismatchError" + if main_package is not None: + (tmp_path / "main").mkdir() + assert branch == probe( + main_package, "bind", "work", mode, cwd=tmp_path / "main" + ) + + +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("kind", ["commutative", "ordered"]) +def test_custom_operators_keep_main_nodes_and_rows( + main_package: Path | None, tmp_path: Path, kind: str, mode: str +) -> None: + branch, main = both(main_package, "custom", str(tmp_path), kind, mode) + if kind == "ordered": + assert {"ab_total", "ba_total"} <= set(branch["listing"]["labels"]) + if main is not None: + assert branch == main + + +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( + main_package: Path | None, receiver: str +) -> None: + branch, main = both(main_package, "membership", receiver) + refused = [ + "UndefinedGraphMembershipError", + "Graph object membership is not defined yet (ITL-1559): this object is not " + "one of the DAG's own nodes. Access the node by label with job.nodes[label] " + "or pipeline.nodes[label].", + ] + accepted = {"foreign", "foreign_view", "foreign_stream", "graph_attribute"} + assert branch["foreign"] == branch["foreign_view"] == refused # R-IN + assert branch["foreign_stream"] == refused # R-IN + assert branch["graph_attribute"] is False # R-GRAPH + assert branch["own"] == branch["own_view"] == branch["label"] == ["ok", True] + if main is not None: + assert main["foreign"] == main["foreign_view"] == ["ok", True] + assert main["foreign_stream"][0] == "ok" + assert main["graph_attribute"] is True + same = {key: value for key, value in branch.items() if key not in accepted} + assert same == { + key: value for key, value in main.items() if key not in accepted + } + + +@pytest.mark.parametrize("order", ["forward", "reversed"]) +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +@pytest.mark.parametrize( + ("case", "code"), + [ + ("slot-and-direct", "R-53/54"), + ("slot-and-direct-renamed", "R-MIX"), + ("slot-and-root-one-name", "ROWS-37-38"), + ], +) +def test_capture_refusals_differ_from_main_as_accepted( + main_package: Path | None, case: str, code: str, receiver: str, order: str +) -> None: + branch, main = both(main_package, "capture", case, receiver, order) + error, message = branch["capture"] + assert error == "InconsistentSourceError", code + if code == "ROWS-37-38": + assert "is another object under the same name" in message + assert "(ITL-1553)" in message + else: + assert ( + "One source object on two slots is not supported yet (ITL-1559, step 6)" + in message + or "already declared under slot" in message + ) + if main is not None: + # Main accepts each of these captures. + assert main["capture"][0] == "ok", (code, main) + + +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +@pytest.mark.parametrize("kind", ["operator", "function"]) +def test_rewire_87_differs_from_main_as_accepted( + main_package: Path | None, kind: str, receiver: str +) -> None: + branch, main = both(main_package, "rewire", kind, receiver) + assert branch["same"][0] == "ok" + assert branch["other"] == [ # REWIRE-87 + "InconsistentSourceError", + "Cannot rewire 'descriptor' because a pipeline or job captured it as an input " + "(ITL-1559). Create a new descriptor for the new inputs; rewiring a captured " + "input is ITL-1847.", + ] + if main is not None: + assert main["same"] == branch["same"] + assert main["other"][0] == "ok" + + +def test_load_dup_refuses_a_file_main_writes_with_two_nodes_of_one_hash( + main_package: Path | None, tmp_path: Path +) -> None: + if main_package is None: + pytest.skip(f"The main commit {MAIN} is not available") + path = tmp_path / "dup.json" + written = probe(main_package, "save-dup", str(path)) + assert written["saved"][0] == "ok" + branch = probe(ROOT / "src", "load", str(path)) + main = probe(main_package, "load", str(path)) + assert main["pipeline"][0] == "ok" + error, message = branch["pipeline"] # LOAD-DUP + assert error == "InconsistentSourceError" + assert "are two distinct nodes with one node hash" in message + + +if __name__ == "__main__": + import warnings + + warnings.simplefilter("ignore") + print(json.dumps(dispatch(sys.argv[1:]), default=str)) diff --git a/tests/test_pipeline/test_pipeline.py b/tests/test_pipeline/test_pipeline.py index b135a1ad8..6d20a23e4 100644 --- a/tests/test_pipeline/test_pipeline.py +++ b/tests/test_pipeline/test_pipeline.py @@ -13,7 +13,6 @@ from typing import cast -import networkx as nx import pyarrow as pa import pytest @@ -489,24 +488,20 @@ def test_two_derived_sources_from_same_node_share_pipeline_hash(self, pipeline_d class TestHashGraph: def test_graph_empty_before_context(self): - """pipeline.graph is an empty DiGraph before any with block.""" - # Test the Pipeline object directly — no PipelineJob needed for this property check. + """An uncompiled pipeline exposes an empty label mapping.""" pipeline = Pipeline(name="test") - assert isinstance(pipeline.graph, nx.DiGraph) - assert len(pipeline.graph.nodes) == 0 - assert len(pipeline.graph.edges) == 0 + assert pipeline.nodes == {} + with pytest.raises(RuntimeError, match="has not been compiled"): + _ = pipeline.dag def test_graph_has_edges_after_compile(self, pipeline_db): - """After a with block + compile, graph contains the right edges.""" + """After compilation the DAG connects the labeled node to its sources.""" src_a, src_b = _make_two_sources() job = PipelineJob(database=pipeline_db) with job: Join()(src_a, src_b, label="joiner") pipeline = job.pipeline - g = pipeline.graph - assert len(g.edges) > 0 - joiner_hash = job.pipeline.nodes["joiner"].node_hash().to_string() - assert joiner_hash in g.nodes + assert len(pipeline.dag.predecessors(pipeline.nodes["joiner"])) == 2 def test_graph_multi_node_has_more_edges_than_single_node(self, pipeline_db): """A pipeline with more nodes has more edges than one with fewer.""" @@ -517,14 +512,14 @@ def test_graph_multi_node_has_more_edges_than_single_node(self, pipeline_db): job1 = PipelineJob(database=pipeline_db) with job1: Join()(src_a, src_b, label="joiner") - edges_single = set(job1.pipeline.graph.edges) + edges_single = list(job1.pipeline.dag.edges()) # Build two-node pipeline src_a2, src_b2 = _make_two_sources() job2 = PipelineJob(database=InMemoryArrowDatabase()) with job2: joined = Join()(src_a2, src_b2, label="joiner") pod(joined, label="adder") - edges_double = set(job2.pipeline.graph.edges) + edges_double = list(job2.pipeline.dag.edges()) assert len(edges_double) > len(edges_single) def test_graph_node_type_source(self, pipeline_db): @@ -534,11 +529,8 @@ def test_graph_node_type_source(self, pipeline_db): with job: Join()(src_a, src_b, label="joiner") pipeline = job.pipeline - g = pipeline.graph - joiner_hash = pipeline.joiner.node_hash().to_string() - # Predecessors of joiner are source nodes - for src_hash in g.predecessors(joiner_hash): - assert g.nodes[src_hash].get("node_type") == "source" + for node in pipeline.dag.predecessors(pipeline.joiner): + assert node.node_type == "source" def test_graph_node_type_operator(self, pipeline_db): """Operator nodes have node_type='operator' after compile.""" @@ -547,8 +539,7 @@ def test_graph_node_type_operator(self, pipeline_db): with job: Join()(src_a, src_b, label="joiner") pipeline = job.pipeline - joiner_hash = pipeline.joiner.node_hash().to_string() - assert pipeline.graph.nodes[joiner_hash].get("node_type") == "operator" + assert pipeline.nodes["joiner"].node_type == "operator" def test_graph_node_type_function(self, pipeline_db): """Function nodes have node_type='function' after compile.""" @@ -560,8 +551,7 @@ def test_graph_node_type_function(self, pipeline_db): joined = Join()(src_a, src_b) pod(joined, label="adder") pipeline = job.pipeline - adder_hash = pipeline.adder.node_hash().to_string() - assert pipeline.graph.nodes[adder_hash].get("node_type") == "function" + assert pipeline.nodes["adder"].node_type == "function" def test_graph_label_attribute(self, pipeline_db): """Labeled nodes carry their label in graph node attributes after compile.""" @@ -570,8 +560,7 @@ def test_graph_label_attribute(self, pipeline_db): with job: Join()(src_a, src_b, label="my_join") pipeline = job.pipeline - joiner_hash = pipeline.my_join.node_hash().to_string() - assert pipeline.graph.nodes[joiner_hash].get("label") == "my_join" + assert pipeline.nodes["my_join"].label == "my_join" def test_graph_pipeline_hash_attribute(self, pipeline_db): """Compiled nodes have pipeline_hash attribute set in the graph.""" @@ -581,7 +570,7 @@ def test_graph_pipeline_hash_attribute(self, pipeline_db): Join()(src_a, src_b, label="joiner") pipeline = job.pipeline joiner_hash = pipeline.joiner.node_hash().to_string() - stored_ph = pipeline.graph.nodes[joiner_hash].get("pipeline_hash") + stored_ph = pipeline._hash_graph.nodes[joiner_hash].get("pipeline_hash") assert stored_ph is not None assert stored_ph == pipeline.joiner.pipeline_hash().to_string() diff --git a/tests/test_pipeline/test_pipeline_base_recording.py b/tests/test_pipeline/test_pipeline_base_recording.py index 770e23d25..38078e228 100644 --- a/tests/test_pipeline/test_pipeline_base_recording.py +++ b/tests/test_pipeline/test_pipeline_base_recording.py @@ -110,7 +110,12 @@ def test_compile_creates_source_node_for_unregistered_upstream(self): with pipeline: pod(stream, label="out") source_hash = stream.content_hash().to_string() - assert isinstance(pipeline._persistent_node_map[source_hash], SourceNode) + # Compiled nodes are held under their node hash (ITL-1848). + source_node = pipeline._persistent_node_map[pipeline._compiled_key(source_hash)] + assert isinstance(source_node, SourceNode) + assert ( + pipeline._compiled_key(source_hash) == source_node.node_hash().to_string() + ) class TestSourceNodeNaming: diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index 755406d3b..c0d9f6931 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -32,6 +32,7 @@ from orcapod.core.nodes.operator_node import OperatorJobNode from orcapod.core.operators.column_selection import SelectDataColumns from orcapod.databases import DeltaTableDatabase +from orcapod.errors import InconsistentSourceError from orcapod.operators import Join, MergeJoin, SemiJoin from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator from orcapod.sources import ArrowTableSource, CSVSource @@ -123,6 +124,17 @@ def _capture( ] + [pytest.param("unary", reverse, id=f"unary-{reverse}") for reverse in (False, True)] +# Accepted differences from main (ITL-1848): the cases that read one source object +# through the explicit slot ``a`` and directly (as source ``a``) are refused at the +# capture that brings the second form, R-53/54 (one name) or R-MIX (``a2``), before +# their steps could shadow each other. ``unary`` keeps main's compile refusal. +_CAPTURE_REFUSAL = "One source object on two slots|already declared under slot" + + +def _refused_at_capture(case: str) -> bool: + return case != "unary" + + def _refusal_message(case: str) -> str: first, second = ("first", "second") if case == "unary" else ("direct", "slots") labels = rf"(?:'{first}' and '{second}'|'{second}' and '{first}')" @@ -140,7 +152,11 @@ def test_refuses_shadowed_steps_at_compile( database_path = tmp_path / "db" database = DeltaTableDatabase(database_path) message = _refusal_message(case) - if direct_capture: + if _refused_at_capture(case): + graph = PipelineJob("matrix", database=database) if direct_capture else None + with pytest.raises(InconsistentSourceError, match=_CAPTURE_REFUSAL): + _ = _capture(graph or Pipeline("matrix"), case, reverse=reverse) + elif direct_capture: job = PipelineJob("matrix", database=database) bindings = _capture(job, case, reverse=reverse) job.bind(sources=bindings) @@ -218,6 +234,10 @@ def test_rechecks_when_later_bindings_make_steps_equal( case: str, reverse: bool, asynchronous: bool, tmp_path: Path ) -> None: pipeline = Pipeline("matrix") + if _refused_at_capture(case): + with pytest.raises(InconsistentSourceError, match=_CAPTURE_REFUSAL): + _ = _capture(pipeline, case, reverse=reverse) + return bindings = _capture(pipeline, case, reverse=reverse) job = cast( "PipelineJob", @@ -237,24 +257,27 @@ def test_rechecks_when_later_bindings_make_steps_equal( def test_step_collision_is_independent_of_rows_and_run_state( scenario: str, reverse: bool, asynchronous: bool, tmp_path: Path ) -> None: + # The ``unary`` steps: ``mixed`` is refused at capture since ITL-1848 (R-53/54). pipeline = Pipeline("matrix") bindings = _capture( - pipeline, "mixed", reverse=reverse, null_keys=scenario == "null-keys" + pipeline, "unary", reverse=reverse, null_keys=scenario == "null-keys" ) database = DeltaTableDatabase(tmp_path / "db") if scenario == "null-keys": - with pytest.raises(ValueError, match=_refusal_message("mixed")): + with pytest.raises(ValueError, match=_refusal_message("unary")): _ = 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"): + # A function step keeps its rows whatever the keys hold; the refusal does not + # depend on them. + expected = 2 + for label in ("first", "second"): 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")): + with pytest.raises(ValueError, match=_refusal_message("unary")): _run(job, asynchronous) @@ -289,6 +312,10 @@ def test_load_keeps_existing_refusal_of_colliding_stubs( case: str, reverse: bool, tmp_path: Path ) -> None: pipeline = Pipeline("matrix") + if _refused_at_capture(case): + with pytest.raises(InconsistentSourceError, match=_CAPTURE_REFUSAL): + _ = _capture(pipeline, case, reverse=reverse) + return bindings = _capture(pipeline, case, reverse=reverse) job = PipelineJob.from_pipeline(pipeline) job.bind(sources=bindings) diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py index a745e03c9..3ca417130 100644 --- a/tests/test_pipeline/test_source_id_conflicts.py +++ b/tests/test_pipeline/test_source_id_conflicts.py @@ -632,11 +632,13 @@ def test_deferred_capture_refuses_new_source_conflict() -> None: OperatorInvocation(other, (first,), "reused") ) record_first() - before = pipeline.graph.copy() + # The capture graph: the public ``graph`` property is gone (ITL-1848, R-GRAPH). + captured = pipeline._hash_graph # pyright: ignore[reportPrivateUsage] # the test is about the capture record + before = captured.copy() with pytest.raises(InconsistentSourceError, match="distinct source objects"): record_conflicting() - assert set(pipeline.graph.nodes) == set(before.nodes) - assert set(pipeline.graph.edges) == set(before.edges) + assert set(captured.nodes) == set(before.nodes) + assert set(captured.edges) == set(before.edges) record_shared() pipeline.compile() assert set(pipeline.nodes) == {"first", "reused", "shared"} diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py index a2869934b..501f64410 100644 --- a/tests/test_pipeline/test_source_object_registration.py +++ b/tests/test_pipeline/test_source_object_registration.py @@ -1888,8 +1888,9 @@ def public_state(pipeline: Pipeline | PipelineJob) -> tuple[object, ...]: """Snapshot public topology, compiled nodes and registered sources.""" invocations = pipeline.to_invocations() return ( - tuple(pipeline.graph.nodes), - tuple(pipeline.graph.edges), + # The capture graph: the ``graph`` property is gone (ITL-1848, R-GRAPH). + tuple(pipeline._hash_graph.nodes), # pyright: ignore[reportPrivateUsage] # the capture record + tuple(pipeline._hash_graph.edges), # pyright: ignore[reportPrivateUsage] # the capture record {label: id(node) for label, node in pipeline.nodes.items()}, tuple(invocations.source_streams), tuple(invocation.label for invocation in invocations.invocations), From 8e531b8eb709a39965860d93c18a113a55862023 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:24:35 -0800 Subject: [PATCH 02/12] fix(pipeline): enforce one node per node hash on every route (ITL-1848) Address the independent review of PR 695: - CompiledDAG.add_node/add_edge refuse a node whose node hash another vertex holds (DAG-DUP). - as_pipeline() refuses two nodes with one node hash before building its node map (PROJECT-DUP). - from_invocations runs the shared capture-leaf checks and holds. - SourceNode.from_stream records its origin with or without a name; the refusal says the stream is captured directly and through a slot declared from it. - A custom operator's node_hash() raises main's ValueError and text. - The main-compatibility gate requires main, asserts refusals at the step that raises, recompiles and runs after each bind step, and covers the import, DAG-duplicate and projection routes. - Docs and changelog state CompiledDAG/CompiledNodeView (R-IN). Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1848.md | 14 +- docs/concepts/pipeline-job.md | 12 +- docs/concepts/sources.md | 3 +- docs/reference/hashing.md | 2 +- src/orcapod/core/identity_chains.py | 34 +- src/orcapod/core/nodes/source_node.py | 6 +- src/orcapod/pipeline/base.py | 56 +- src/orcapod/pipeline/dag.py | 37 ++ src/orcapod/pipeline/graph.py | 4 +- src/orcapod/pipeline/graph_keys.py | 37 +- src/orcapod/pipeline/job.py | 6 + .../test_graph_keys_main_compatibility.py | 510 ++++++++++++++---- tests/test_pipeline/test_pipeline.py | 20 +- .../test_pipeline/test_shadowed_job_steps.py | 4 +- 14 files changed, 578 insertions(+), 167 deletions(-) diff --git a/changelog.d/ITL-1848.md b/changelog.d/ITL-1848.md index c8f9d2665..9306d8242 100644 --- a/changelog.d/ITL-1848.md +++ b/changelog.d/ITL-1848.md @@ -2,6 +2,8 @@ - A pipeline or job no longer has a `graph` attribute. Use `job.dag` (or `pipeline.dag`) for the compiled graph and `job.nodes[label]` for a node. +- `job.dag` (and `pipeline.dag`) is a `CompiledDAG`, a subclass of `OrcaDAG`, and its + `nodes()` view is a `CompiledNodeView`. - `node in job.dag` (and in `pipeline.dag`) answers only for the DAG's own nodes. Any other node, stream or invocation object raises `UndefinedGraphMembershipError`, a new error in `orcapod.errors`: look the node up by label instead (ITL-1559). @@ -15,12 +17,18 @@ until saved files record node hashes (ITL-1864). - One source object read through an explicit slot (`SourceNode.from_stream(source, name=...)`) and directly in one pipeline or job is refused with `InconsistentSourceError` - at the capture that brings the second form, whether the names agree or not. + at the capture that brings the second form, whether the names agree or not, and also + when the slot takes the source's own name (`SourceNode.from_stream(source)`). Graphs + imported with `from_invocations` are checked the same way. - An explicit slot and another source object with the same name (two slots with one node hash) are refused with `InconsistentSourceError` at the capture that brings the second one; declare the second source under its own slot name. - Setting a captured step's `upstreams` to other streams raises `InconsistentSourceError`; build a new step for the new inputs (following such a change is ITL-1847). Setting the same streams again is still accepted. -- Loading a saved pipeline or job in which two distinct nodes share one node hash raises - `InconsistentSourceError`. +- Adding to a compiled DAG a node whose node hash another of its nodes holds raises + `InconsistentSourceError`, as does `job.as_pipeline()` when two of the job's nodes would + share one node hash. +- Loading a saved pipeline in which two distinct nodes share one node hash raises + `InconsistentSourceError`. Such a file could be written by an earlier + `Pipeline.save`; build the pipeline again and save it. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index c11256e6f..db5760d21 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -468,10 +468,14 @@ Within one pipeline or job, a node hash names one node: two distinct nodes with hash are refused, never told apart. A step's inputs are fixed once a pipeline or job has captured it: setting a captured step's `upstreams` to other streams raises `InconsistentSourceError` (following such a change is ITL-1847); build a new step for the new -inputs. Loading a saved file in which two distinct nodes share one node hash is refused too. - -The compiled graph is `job.dag` (or `pipeline.dag`), and `job.nodes[label]` gives a node by -its label. A pipeline or job has no `graph` attribute. `node in job.dag` answers for the +inputs. The same rule holds wherever nodes reach a compiled graph: adding to `job.dag` a node +whose node hash another of its nodes holds, `job.as_pipeline()` of a job whose steps would +give two nodes one node hash, and loading a saved file in which two distinct nodes share one +node hash all raise `InconsistentSourceError`. + +The compiled graph is `job.dag` (or `pipeline.dag`), a `CompiledDAG`, which is an `OrcaDAG`; +`job.dag.nodes()` is a `CompiledNodeView`. `job.nodes[label]` gives a node by its label. A +pipeline or job has no `graph` attribute. `node in job.dag` answers for the DAG's own nodes; for any other node, stream or invocation object it raises `UndefinedGraphMembershipError`, since membership of a node object is not defined yet (ITL-1559): look the node up by label instead. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index 8ba70e6ee..eaba8e72a 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -108,7 +108,8 @@ and run with its replacement bindings. ITL-1559 tracks capture after rebinding. A slot holds one source object. Read a source either through an explicit slot (`SourceNode.from_stream(source, name="units")`) or directly, never both in one pipeline or job: the capture that brings the second form raises `InconsistentSourceError`, under -the same name or another. Likewise, an explicit slot `units` and another source object named +the same name or another, and also when the slot takes the source's own name +(`SourceNode.from_stream(source)`). Likewise, an explicit slot `units` and another source object named `units` would be two slots with one node hash, so the capture that brings the second one is refused; declare the second source under its own slot name (`SourceNode.from_stream(other, name="units_2")`). Until source equivalence is defined diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 5ea1760ee..ee4ca557d 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -461,7 +461,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_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), `pipeline/graph_keys.py:compiled_graph_key` and `pipeline/base.py:AbstractPipelineBase._describe_capture_leaf` (a compiled node's node hash, the key the compiled graph holds it under, ITL-1848) | +| 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), `pipeline/graph_keys.py:compiled_graph_key`, `pipeline/graph_keys.py:defined_node_hash` and `pipeline/base.py:AbstractPipelineBase._describe_capture_leaf` (a compiled node's node hash, the key the compiled graph holds it under, ITL-1848) | | 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/core/identity_chains.py b/src/orcapod/core/identity_chains.py index ed2142584..a4de22b00 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -50,19 +50,39 @@ def _identity_read() -> Iterator[None]: _reading_chains.reset(token) -class UndefinedIdentityError(ValueError): - """A pipeline element cannot give its node hash in this step. +_undefined_identity_notes: ContextVar[list[str] | None] = ContextVar( + "undefined_identity_notes", default=None +) + + +@contextmanager +def noting_undefined_identity() -> Iterator[list[str]]: + """Note each undefined-identity refusal raised inside the block. - Raised for a custom operator, and for an element whose identity would need rows - or a source callback. A compiled graph then keys the node by its capture key - (ITL-1848). + The refusal stays main's ``ValueError``; a compiled graph reads the notes to tell + a node without a node hash (a custom operator, and below it) from another + ``ValueError`` (ITL-1848). """ + notes: list[str] = [] + token = _undefined_identity_notes.set(notes) + try: + yield notes + finally: + _undefined_identity_notes.reset(token) + + +def _undefined_identity(message: str) -> ValueError: + """Main's refusal of an undefined identity, noted for a compiled graph.""" + notes = _undefined_identity_notes.get() + if notes is not None: + notes.append(message) + return ValueError(message) def refuse_identity_io(reason: str = "this source requires a schema") -> None: """Report why an identity read would need rows or a source callback.""" if reading_identity_chains(): - raise UndefinedIdentityError(f"Pipeline identity is undefined: {reason}.") + raise _undefined_identity(f"Pipeline identity is undefined: {reason}.") def reading_identity_chains() -> bool: @@ -76,7 +96,7 @@ def require_builtin_operator_identity(operator: object) -> None: from orcapod.core.operators import BUILTIN_OPERATOR_TYPES if type(operator) not in BUILTIN_OPERATOR_TYPES: - raise UndefinedIdentityError( + raise _undefined_identity( "Pipeline identity is undefined for a custom operator in this step." ) diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 8906dbe98..825ba1612 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1743,9 +1743,9 @@ def from_stream( # A loaded job's slot keeps all its saved state (ITL-1138, ITL-640), # through the one method every copy of a slot uses. node._take_saved_state_of(stream) - elif name is not None: - # The stream an explicit slot was declared from: a pipeline refuses to - # capture it directly as well (ITL-1848). Only weakly held. + else: + # The stream a slot was declared from, named or not: a pipeline refuses + # to capture it directly as well (ITL-1848). Only weakly held. try: node._declared_from = weakref.ref(stream) except TypeError: diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 2c8ea7727..35d105230 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -24,6 +24,7 @@ rekeyed, rekeyed_edges, shared_graph_keys, + shared_node_hash_error, ) from orcapod.pipeline.pod_invocation import ( FunctionInvocation, @@ -470,13 +471,29 @@ def _validate_invocation( if remember_streams: self._remember_capture_stream_keys(capture_streams.maps[0]) - self._capture_leaves.update((leaf.capture_key, leaf) for leaf in leaves) - new_keys = {leaf.capture_key for leaf in leaves} - for stream, input_key in zip(inputs, input_keys, strict=True): - if input_key in new_keys: - self._hold_captured(stream) + self._commit_capture_leaves(leaves, zip(input_keys, inputs, strict=True)) return key, input_keys + def _commit_capture_leaves( + self, + leaves: Iterable[CaptureLeaf], + streams: Iterable[tuple[str, StreamProtocol]], + ) -> None: + """Record admitted leaves and hold what lies beneath them (ITL-1848). + + Args: + leaves: Leaves ``_new_capture_leaves`` admitted. + streams: Capture key and stream of each input, leaves among them. + """ + admitted = {leaf.capture_key: leaf for leaf in leaves} + self._capture_leaves.update(admitted) + new_keys = admitted.keys() + held: set[str] = set() + for input_key, stream in streams: + if input_key in new_keys and input_key not in held: + held.add(input_key) + self._hold_captured(stream) + # ------------------------------------------------------------------ # Capture leaves (ITL-1848) # ------------------------------------------------------------------ @@ -583,8 +600,9 @@ def _refuse_one_object_twice(leaf: CaptureLeaf, known: list[CaptureLeaf]) -> Non _one_object_on_two_slots(obj, other.name, leaf.name) ) raise InconsistentSourceError( - f"The same source object is already declared under slot {leaf.name!r}. " - "Use the slot declaration or capture the source directly (ITL-1559)." + "The same stream is captured directly and through a slot declared from " + f"it (slot {leaf.name!r}). Use the slot declaration or capture the " + "stream directly, not both (ITL-1559)." ) @staticmethod @@ -697,7 +715,11 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse def _source_node_from_recording(self, key: str) -> Any: """Create the source node for a recorded leaf.""" - return self.source_node_class.from_stream(self._source_streams[key]) + node = self.source_node_class.from_stream(self._source_streams[key]) + # A slot a compile builds is not a declaration: another pipeline may capture + # it beside its source, as on main (ITL-1848). + node._declared_from = None + return node # ------------------------------------------------------------------ # Diagram (ITL-1197) @@ -1064,12 +1086,7 @@ def _require_one_node_per_graph_key( InconsistentSourceError: Naming both nodes. """ for _, first, second in shared_graph_keys(keys): - raise InconsistentSourceError( - f"Nodes {nodes[first].label!r} and {nodes[second].label!r} are two " - "distinct nodes with one node hash. A node hash is unique within a " - "pipeline (ITL-1559): give the slots different names, or build the " - "pipeline again with this version of Orcapod." - ) + raise shared_node_hash_error(nodes[first], nodes[second]) def _publish_graph_keys(self, keys: Mapping[str, str]) -> None: """Re-key the compiled maps, given by capture key, to their graph keys.""" @@ -1246,11 +1263,14 @@ def from_invocations( instance._validate_capture_sources(inputs) require_live_source_bindings(inputs) require_consistent_sources(invocation_source_uses(graph.invocations)) + # The leaves pass the checks a direct capture applies, and are held as a + # direct capture holds them (ITL-1848). + imported = tuple(graph.source_streams.items()) + leaves = instance._new_capture_leaves( + tuple(stream for _, stream in imported), tuple(key for key, _ in imported) + ) + instance._commit_capture_leaves(leaves, imported) instance._source_streams = dict(graph.source_streams) - instance._capture_leaves = { - key: instance._describe_capture_leaf(stream, key) - for key, stream in graph.source_streams.items() - } capture_streams = instance._capture_key_memo() for inv in graph.invocations: key, input_keys = inv.capture_keys( diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index 829e62612..70c206a70 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -32,6 +32,7 @@ ) from orcapod.errors import UndefinedGraphMembershipError +from orcapod.pipeline.graph_keys import defined_node_hash, shared_node_hash_error __all__ = ["Comparable", "CompiledDAG", "GraphProtocol", "OrcaDAG", "CycleError"] @@ -488,6 +489,42 @@ class CompiledDAG(OrcaDAG[NodeT]): string, a number) answer as on ``OrcaDAG``. """ + def __init__(self) -> None: + super().__init__() + # node hash -> the one vertex holding it (rule iii, ITL-1848) + self._by_node_hash: dict[str, NodeT] = {} + + def add_node(self, node: NodeT, **attrs: Any) -> None: + """Add *node* as ``OrcaDAG.add_node`` does, keeping node hashes unique. + + Raises: + InconsistentSourceError: If another vertex already holds the node's node + hash: a node hash names one node within a pipeline (ITL-1848). + """ + self._require_unique_node_hash(node) + super().add_node(node, **attrs) + + def add_edge(self, u: NodeT, v: NodeT) -> None: + """Add an edge as ``OrcaDAG.add_edge`` does, keeping node hashes unique. + + Raises: + InconsistentSourceError: If either end is a new vertex whose node hash + another vertex already holds (ITL-1848). + """ + self._require_unique_node_hash(u) + self._require_unique_node_hash(v) + super().add_edge(u, v) + + def _require_unique_node_hash(self, node: NodeT) -> None: + if node in self._attrs: + return + node_hash = defined_node_hash(node) + if node_hash is None: + return + held = self._by_node_hash.setdefault(node_hash, node) + if held is not node: + raise shared_node_hash_error(held, node) + def __contains__(self, node: object) -> bool: return _require_held(self, node) diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 0f91f6b61..c8d459f89 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -18,7 +18,7 @@ from orcapod.core.tracker import AutoRegisteringContextBasedTracker from orcapod.pipeline.base import AbstractPipelineBase from orcapod.pipeline.dag import CompiledDAG -from orcapod.pipeline.graph_keys import legacy_graph_key, loaded_node_hash +from orcapod.pipeline.graph_keys import legacy_graph_key, defined_node_hash from orcapod.protocols import core_protocols as cp from orcapod.utils.lazy_module import LazyModule from orcapod.utils.schema_utils import ReservedColumnNameError @@ -692,7 +692,7 @@ def load(cls, path: str | Path) -> "Pipeline": # share one node hash is refused (ITL-1848). pipeline._require_one_node_per_graph_key( reconstructed, - {key: loaded_node_hash(node) for key, node in reconstructed.items()}, + {key: defined_node_hash(node) for key, node in reconstructed.items()}, ) pipeline._publish_graph_keys( {key: legacy_graph_key(key) for key in reconstructed} diff --git a/src/orcapod/pipeline/graph_keys.py b/src/orcapod/pipeline/graph_keys.py index 7235fe25b..958f0098b 100644 --- a/src/orcapod/pipeline/graph_keys.py +++ b/src/orcapod/pipeline/graph_keys.py @@ -17,7 +17,8 @@ from collections.abc import Iterable, Mapping from typing import Any, TypeVar -from orcapod.core.identity_chains import UndefinedIdentityError +from orcapod.core.identity_chains import noting_undefined_identity +from orcapod.errors import InconsistentSourceError LEGACY_KEY_PREFIX = "legacy:" @@ -45,18 +46,23 @@ def compiled_graph_key(node: Any, capture_key: str) -> str: The node's node hash as text, or ``legacy:`` when the node has no node hash in this step. """ - try: - return node.node_hash().to_string() - except UndefinedIdentityError: - return legacy_graph_key(capture_key) + with noting_undefined_identity() as undefined: + try: + return node.node_hash().to_string() + except ValueError: + if not undefined: + raise + return legacy_graph_key(capture_key) -def loaded_node_hash(node: Any) -> str | None: - """The node hash of a node loaded from a file, where it is defined. +def defined_node_hash(node: Any) -> str | None: + """A node's node hash, where it is defined. + + Used where nodes are compared by node hash (a loaded file, a compiled DAG). Returns: The node hash as text, or ``None`` for a node whose identity cannot be read - (a read-only node without its pod, a custom operator). + (a read-only loaded node without its pod, a custom operator). """ try: return node.node_hash().to_string() @@ -98,3 +104,18 @@ def rekeyed_edges( ) -> list[tuple[str, str]]: """Re-key an edge list through *keys*, keeping its order.""" return [(keys.get(up, up), keys.get(down, down)) for up, down in edges] + + +def shared_node_hash_error(first: Any, second: Any) -> InconsistentSourceError: + """The refusal of two distinct nodes with one node hash (rule iii). + + Args: + first: The node already held. + second: The other node. + """ + return InconsistentSourceError( + f"Nodes {getattr(first, 'label', first)!r} and " + f"{getattr(second, 'label', second)!r} are two distinct nodes with one node " + "hash. A node hash is unique within a pipeline (ITL-1559): give the slots " + "different names, or build the pipeline again with this version of Orcapod." + ) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4738ae21c..e976a25c3 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -40,6 +40,8 @@ compiled_graph_key, is_legacy_graph_key, legacy_graph_key, + shared_graph_keys, + shared_node_hash_error, ) from orcapod.pipeline.node_run import ( RunPlan, @@ -1119,6 +1121,10 @@ def as_pipeline(self) -> "Pipeline": old_to_new: dict[str, str] = { h: graph_hash(bp_node).to_string() for h, bp_node in node_map.items() } + # Two distinct nodes under one key would collapse into one below: refuse + # them first, never keep one silently (rule iii, ITL-1848). + for _, first, second in shared_graph_keys(old_to_new): + raise shared_node_hash_error(node_map[first], node_map[second]) # Re-key node_map with declaration hashes. new_node_map: dict[str, object] = { new_h: node_map[h] for h, new_h in old_to_new.items() diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 533da692d..6a6e7a5fa 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -7,18 +7,23 @@ difference is named by its code and asserted on both sides: - R-IN: ``object in compiled_dag`` is refused for an object that is not one of the DAG's - own nodes (``UndefinedGraphMembershipError``); main compared by equality. + own nodes (``UndefinedGraphMembershipError``); main compared by equality. The compiled + DAG is a ``CompiledDAG`` (still an ``OrcaDAG``) and its node view a ``CompiledNodeView``. - R-GRAPH: the ``graph`` attribute of a pipeline or job is gone. - R-53/54: one source object read through an explicit slot and directly, one name. - R-MIX: the same, under two names. - ROWS-37-38: an explicit slot and another source object with the same name (two slots with one node hash). -- REWIRE-87: setting a captured step's ``upstreams`` to other streams. +- REWIRE-87: setting a captured step's ``upstreams`` to other streams, whether the step + was captured directly or imported with ``from_invocations``. - LOAD-DUP: loading a pipeline file in which two distinct nodes share one node hash. +- DAG-DUP: adding to a compiled DAG a node whose node hash another of its nodes holds. +- PROJECT-DUP: ``as_pipeline()`` of a job whose distinct nodes would share one key (after + a compiled step's ``upstreams`` setter, which stays as main). Everything else (labels, the compiled DAG, rows, stored tables, saved bytes, bind, rebind, -unbind and the ITL-1469 refusals) must be identical. When the main commit is not available -(a shallow clone), only this checkout's outcome is checked. +unbind and the ITL-1469 refusals) must be identical. The main commit is required: without +it the gate fails, it never checks this checkout alone. """ from __future__ import annotations @@ -26,6 +31,7 @@ import asyncio import io import json +import logging import os import subprocess import sys @@ -48,12 +54,19 @@ from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNode from orcapod.core.operators import Join, SelectDataColumns from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase +from orcapod.pipeline.base import InvocationGraph +from orcapod.pipeline.dag import OrcaDAG +from orcapod.pipeline.pod_invocation import FunctionInvocation from orcapod.sources import DictSource ROOT = Path(__file__).resolve().parents[2] MAIN = "2075e85e2c9418444ec5368e800f71d354fd0b5e" MODES = ["sync", "async"] -FIXED_RUN_ID = UUID("01234567-89ab-4def-8abc-0123456789ab") +# One sequence per interpreter, never restarted, so every run's ids are unique. +RESULT_IDS = count(1) +RUN_IDS = count(1) +# Warnings and errors Orcapod logs while a case runs (a write failure among them). +LOGGED: list[str] = [] @function_pod(output_keys="doubled") @@ -104,11 +117,16 @@ def caught(action: Callable[[], Any]) -> Any: return [type(error).__name__, str(error)] -def run(job: PipelineJob, mode: str, *, load_only: bool = False) -> None: +def run(job: PipelineJob, mode: str, *, load_only: bool = False) -> dict[str, Any]: + """Run the job; the summary's counts per node.""" if mode == "async": - _ = asyncio.run(job.run_async(load_only=load_only)) + summary = asyncio.run(job.run_async(load_only=load_only)) else: - _ = job.run(load_only=load_only) + summary = job.run(load_only=load_only) + return { + label: [node.computed, node.reused, node.failed, node.held] + for label, node in sorted(summary.nodes.items()) + } def rows(graph: Pipeline | PipelineJob) -> dict[str, Any]: @@ -138,6 +156,7 @@ def listing(graph: Pipeline | PipelineJob) -> dict[str, Any]: for label, node in sorted(graph.nodes.items()) }, "own_members": all(node in dag for node in graph.nodes.values()), + "dag_is_orca_dag": isinstance(dag, OrcaDAG), } @@ -147,19 +166,24 @@ def saved(job: PipelineJob, path: Path) -> str: return path.read_text() -def frozen_run(job: PipelineJob, mode: str) -> None: - """Run with every generated id and time fixed, so stored tables compare.""" - results = count(1) +def frozen_run(job: PipelineJob, mode: str) -> dict[str, Any]: + """Run with generated ids and times fixed, so stored tables compare. + + The ids come from one sequence per interpreter, so no two runs share one. + """ with ( patch( "orcapod.core.data_function.uuid7", - side_effect=lambda: UUID(int=next(results)), + side_effect=lambda: UUID(int=next(RESULT_IDS)), ), patch("orcapod.core.result_cache.datetime", FrozenClock), patch("orcapod.core.nodes.function_node.datetime", FrozenClock), - patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: FIXED_RUN_ID)), + patch( + "orcapod.pipeline.job.uuid", + SimpleNamespace(uuid4=lambda: UUID(int=next(RUN_IDS) << 64)), + ), ): - run(job, mode) + return run(job, mode) def stored_tables(path: Path) -> dict[str, Any]: @@ -194,7 +218,7 @@ def lifecycle_case(directory: Path, mode: str) -> dict[str, Any]: } job.compile() outcome["recompiled"] = listing(job) - frozen_run(job, mode) + outcome["summary"] = frozen_run(job, mode) outcome["rows"] = rows(job) outcome["stored"] = stored_tables(directory / "db") outcome["saved"] = saved(job, directory / "job.json") @@ -237,13 +261,16 @@ def state() -> dict[str, Any]: } def run_and_read() -> dict[str, Any]: - frozen_run(job, mode) - return rows(job) + return {"summary": frozen_run(job, mode), "rows": rows(job)} + + def recompile() -> list[str]: + job.compile() + return sorted(node.label for node in job.dag.nodes()) - steps["initial"] = [state(), caught(run_and_read)] + steps["initial"] = [state(), caught(recompile), caught(run_and_read)] replacement = source("a_v2", 30) steps["rebind"] = [caught(lambda: job.bind(sources={"left": replacement}))] - steps["rebind"] += [state(), caught(run_and_read)] + steps["rebind"] += [state(), caught(recompile), caught(run_and_read)] def capture_after_rebind() -> None: with job: @@ -251,21 +278,28 @@ def capture_after_rebind() -> None: steps["capture_after_rebind"] = caught(capture_after_rebind) unbinding: dict[str, Any] = {"right": None} # None unbinds a slot - steps["unbind"] = [caught(lambda: job.bind(sources=unbinding)), state()] + steps["unbind"] = [ + caught(lambda: job.bind(sources=unbinding)), + state(), + caught(recompile), + ] steps["run_unbound"] = caught(run_and_read) def setter() -> None: job.nodes["right"].bound_source = second # pyright: ignore[reportAttributeAccessIssue] # a source slot - steps["setter"] = [caught(setter), state(), caught(run_and_read)] + steps["setter"] = [caught(setter), state(), caught(recompile), caught(run_and_read)] steps["swap"] = [ caught(lambda: job.bind(sources={"left": second, "right": replacement})), state(), + caught(recompile), caught(run_and_read), ] steps["restore"] = [ caught(lambda: job.bind(sources={"left": first, "right": second})), state(), + caught(recompile), + caught(run_and_read), ] steps["own_node"] = caught( lambda: job.bind(sources={"left": job.nodes["right_doubled"].as_source()}) @@ -287,7 +321,7 @@ def prebuilt_over_own_slot() -> None: double.pod(SelectDataColumns(["tripled"])(prebuilt), label="prebuilt") steps["prebuilt"] = caught(prebuilt_over_own_slot) - steps["final"] = [state(), caught(run_and_read)] + steps["final"] = [state(), caught(recompile), caught(run_and_read)] steps["saved"] = caught(lambda: saved(job, directory / "bound.json")) return steps @@ -315,7 +349,12 @@ def custom_operator_case(directory: Path, kind: str, mode: str) -> dict[str, Any SelectDataColumns(["x", "y"])(operator(right, left, label="ba")), label="ba_total", ) - outcome = {"listing": listing(job)} + outcome: dict[str, Any] = {"listing": listing(job)} + # S1: a node without a defined identity raises main's ValueError, type and text. + outcome["node_hash"] = { + label: caught(lambda label=label: job.nodes[label].node_hash()) + for label in ("ab", "ab_total") + } run(job, mode) outcome["rows"] = rows(job) return outcome @@ -349,6 +388,9 @@ def build() -> Pipeline | PipelineJob: "foreign_stream": caught(lambda: source("root", 3) in graph.dag), "label": caught(lambda: "result" in graph.nodes), "graph_attribute": hasattr(graph, "graph"), + "dag_type": type(graph.dag).__name__, + "view_type": type(graph.dag.nodes()).__name__, + "dag_is_orca_dag": isinstance(graph.dag, OrcaDAG), } @@ -365,6 +407,11 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: lambda: double.pod(SourceNode.from_stream(shared, name="a"), label="slot"), lambda: triple.pod(shared, label="direct"), ] + elif case == "unnamed-slot-and-direct": # R-53/54, the slot named by default + steps = [ + lambda: double.pod(SourceNode.from_stream(shared), label="slot"), + lambda: triple.pod(shared, label="direct"), + ] elif case == "slot-and-direct-renamed": # R-MIX steps = [ lambda: double.pod(SourceNode.from_stream(shared, name="b"), label="slot"), @@ -380,17 +427,19 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: if order == "reversed": steps.reverse() - def capture() -> list[str]: - with graph: - for step in steps: - step() - return sorted(graph.nodes) + outcome: dict[str, Any] = {} + with graph: + for number, step in enumerate(steps, start=1): + outcome[f"step_{number}"] = caught(lambda: step() and None) + outcome["nodes"] = caught(lambda: sorted(graph.nodes)) + return outcome - return {"capture": caught(capture)} +def rewire_case(kind: str, receiver: str, route: str) -> dict[str, Any]: + """REWIRE-87: a captured descriptor's inputs are fixed; the same ones are accepted. -def rewire_case(kind: str, receiver: str) -> dict[str, Any]: - """REWIRE-87: a captured descriptor's inputs are fixed; the same ones are accepted.""" + *route* is ``capture`` (a ``with`` block) or ``import`` (``from_invocations``). + """ first, second = source("a", 3), source("b", 9) descriptor: Any replacement: tuple[Any, ...] = (second,) @@ -406,29 +455,126 @@ def rewire_case(kind: str, receiver: str) -> dict[str, Any]: cast("Any", double.pod), SelectDataColumns(["x"])(first), label="descriptor" ) replacement = (SelectDataColumns(["x"])(second),) - graph = ( - PipelineJob("rewire", database=InMemoryArrowDatabase()) - if receiver == "job" - else Pipeline("rewire") - ) - with graph: - if kind == "operator": - double.pod(descriptor, label="downstream") - else: - plus_one.pod(descriptor, label="downstream") + pod = double.pod if kind == "operator" else plus_one.pod + graph: Pipeline | PipelineJob + if route == "import": + from orcapod.core.identity_chains import graph_hash + + imported = InvocationGraph( + ( + FunctionInvocation( + pod=cast("Any", pod), + input_streams=(descriptor,), + label="downstream", + ), + ), + {graph_hash(descriptor).to_string(): descriptor}, + ) + receiver_class = PipelineJob if receiver == "job" else Pipeline + graph = cast( + "Pipeline | PipelineJob", + receiver_class.from_invocations(imported, name="rewire"), + ) + else: + graph = ( + PipelineJob("rewire", database=InMemoryArrowDatabase()) + if receiver == "job" + else Pipeline("rewire") + ) + with graph: + pod(descriptor, label="downstream") inputs = tuple(descriptor.upstreams) - def same() -> list[str]: - descriptor.upstreams = inputs - graph.compile() - return sorted(graph.nodes) + def set_upstreams(value: tuple[Any, ...]) -> None: + descriptor.upstreams = value - def other() -> list[str]: - descriptor.upstreams = replacement + def recompile() -> list[str]: graph.compile() return sorted(graph.nodes) - return {"same": caught(same), "other": caught(other)} + return { + "same": caught(lambda: set_upstreams(inputs)), + "same_compile": caught(recompile), + "other": caught(lambda: set_upstreams(replacement)), + "other_compile": caught(recompile), + } + + +def imported_mixed_case(receiver: str) -> dict[str, Any]: + """R-MIX through ``from_invocations``: one object directly and through a slot.""" + from orcapod.core.identity_chains import graph_hash + + # One data column: an invocation reads exactly its function's parameters. + shared = DictSource( + [{"id": 1, "x": 3}, {"id": 2, "x": 4}], + source_id="a", + tag_columns=["id"], + tag_only_columns=True, + ) + slot = SourceNode.from_stream(shared, name="different") + imported = InvocationGraph( + tuple( + FunctionInvocation( + pod=cast("Any", double.pod), input_streams=(leaf,), label=label + ) + for leaf, label in ((shared, "direct"), (slot, "declared")) + ), + {graph_hash(leaf).to_string(): leaf for leaf in (shared, slot)}, + ) + receiver_class = PipelineJob if receiver == "job" else Pipeline + return { + "import": caught( + lambda: sorted( + receiver_class.from_invocations(imported, name="mixed").nodes + ) + ) + } + + +def dag_duplicate_case() -> dict[str, Any]: + """DAG-DUP: a compiled DAG refuses a second node with a node hash it holds.""" + jobs = [] + for name in ("left", "right"): + blueprint = Pipeline(name) + with blueprint: + double.pod(SourceNode.from_stream(source(name, 1), name="slot"), label="d") + jobs.append( + PipelineJob.from_pipeline(blueprint, sources={"slot": source(name, 1)}) + ) + left, right = jobs + held, other = left.nodes["d"], right.nodes["d"] + return { + "distinct": held is not other and held != other, + "one_node_hash": held.node_hash() == other.node_hash(), + "add_node": caught(lambda: left.dag.add_node(other)), + "add_edge": caught(lambda: left.dag.add_edge(left.nodes["slot"], other)), + "dag_nodes": sorted(node.label for node in left.dag.nodes()), + } + + +def projection_duplicate_case() -> dict[str, Any]: + """PROJECT-DUP: ``as_pipeline()`` never collapses two distinct nodes into one.""" + job = PipelineJob("editable") + with job: + double.pod(source("a", 1), label="first") + double.pod(source("b", 5), label="second") + first, second = job.nodes["first"], job.nodes["second"] + setter = caught( + lambda: setattr(first, "upstreams", second.upstreams) # noqa: B010 # the setter as main has it + ) + + def project() -> dict[str, Any]: + blueprint = job.as_pipeline() + return { + "nodes": sorted(blueprint.nodes), + "dag": sorted(node.label for node in blueprint.dag.nodes()), + } + + return { + "setter": setter, + "one_node_hash": first.node_hash() == second.node_hash(), + "project": caught(project), + } def shared_node_hash_file(path: Path) -> dict[str, Any]: @@ -461,7 +607,8 @@ def load_case(path: Path) -> dict[str, Any]: @pytest.fixture(scope="module") -def main_package(tmp_path_factory: pytest.TempPathFactory) -> Path | None: +def main_package(tmp_path_factory: pytest.TempPathFactory) -> Path: + """Main's ``src`` at ``MAIN``; the gate fails without it.""" archive = subprocess.run( ["git", "archive", "--format=zip", MAIN, "src"], cwd=ROOT, @@ -469,7 +616,10 @@ def main_package(tmp_path_factory: pytest.TempPathFactory) -> Path | None: check=False, ) if archive.returncode: - return None + pytest.fail( + f"The main commit {MAIN} is required by the compatibility gate " + f"(git archive: {archive.stderr.decode().strip()})." + ) path = tmp_path_factory.mktemp("itl-1848-main") with ZipFile(io.BytesIO(archive.stdout)) as contents: contents.extractall(path) @@ -492,10 +642,14 @@ def probe(package: Path, *args: str, cwd: Path = ROOT) -> Any: return json.loads(output) -def both(main_package: Path | None, *args: str) -> tuple[Any, Any]: - """This checkout's outcome and main's (``None`` when main is not available).""" - branch = probe(ROOT / "src", *args) - return branch, None if main_package is None else probe(main_package, *args) +def both(main_package: Path, *args: str) -> tuple[Any, Any]: + """This checkout's outcome and main's.""" + return probe(ROOT / "src", *args), probe(main_package, *args) + + +def require_no_write_failure(outcome: dict[str, Any]) -> None: + """A passing gate holds no logged write failure or failed row (S2).""" + assert not [line for line in outcome["logged"] if "write" in line.lower()] def dispatch(args: list[str]) -> Any: @@ -511,7 +665,13 @@ def dispatch(args: list[str]) -> Any: if name == "capture": return capture_case(rest[0], rest[1], rest[2]) if name == "rewire": - return rewire_case(rest[0], rest[1]) + return rewire_case(rest[0], rest[1], rest[2]) + if name == "imported-mixed": + return imported_mixed_case(rest[0]) + if name == "dag-dup": + return dag_duplicate_case() + if name == "project-dup": + return projection_duplicate_case() if name == "save-dup": return shared_node_hash_file(Path(rest[0])) if name == "load": @@ -519,11 +679,16 @@ def dispatch(args: list[str]) -> Any: raise ValueError(name) +def no_failed_rows(summary: dict[str, list[int]]) -> bool: + return all(counts[2] == 0 for counts in summary.values()) + + @pytest.mark.parametrize("mode", MODES) def test_lifecycle_rows_stores_and_saved_bytes_match_main( - main_package: Path | None, tmp_path: Path, mode: str + main_package: Path, tmp_path: Path, mode: str ) -> None: (tmp_path / "branch").mkdir() + (tmp_path / "main").mkdir() branch = probe(ROOT / "src", "lifecycle", "work", mode, cwd=tmp_path / "branch") assert branch["rows"]["double_a"] == sorted( map( @@ -534,43 +699,59 @@ def test_lifecycle_rows_stores_and_saved_bytes_match_main( ], ) ) - if main_package is not None: - (tmp_path / "main").mkdir() - assert branch == probe( - main_package, "lifecycle", "work", mode, cwd=tmp_path / "main" - ) + assert no_failed_rows(branch["summary"]) + assert branch["recompiled"]["dag_is_orca_dag"] is True + require_no_write_failure(branch) + assert branch == probe( + main_package, "lifecycle", "work", mode, cwd=tmp_path / "main" + ) @pytest.mark.parametrize("mode", MODES) def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( - main_package: Path | None, tmp_path: Path, mode: str + main_package: Path, tmp_path: Path, mode: str ) -> None: (tmp_path / "branch").mkdir() + (tmp_path / "main").mkdir() branch = probe(ROOT / "src", "bind", "work", mode, cwd=tmp_path / "branch") - assert branch["initial"][1][0] == "ok" - assert branch["own_node"][0] == "SourceSpecMismatchError" - if main_package is not None: - (tmp_path / "main").mkdir() - assert branch == probe( - main_package, "bind", "work", mode, cwd=tmp_path / "main" + # Every bind, rebind and restore recompiles and runs without a failed row. + for step in ("initial", "rebind", "setter", "swap", "restore", "final"): + recompiled, ran = branch[step][-2], branch[step][-1] + assert recompiled[0] == "ok", (step, recompiled) + assert ran[0] == "ok", (step, ran) + assert no_failed_rows(ran[1]["summary"]), (step, ran) + assert branch["unbind"][2][0] == "ok" + assert branch["rebind"][-1][1]["rows"]["left_doubled"] == sorted( + map( + repr, + [ + {"id": 1, "part": "p", "doubled": 60}, + {"id": 2, "part": "q", "doubled": 62}, + ], ) + ) + assert branch["own_node"][0] == "SourceSpecMismatchError" + require_no_write_failure(branch) + assert branch == probe(main_package, "bind", "work", mode, cwd=tmp_path / "main") @pytest.mark.parametrize("mode", MODES) @pytest.mark.parametrize("kind", ["commutative", "ordered"]) def test_custom_operators_keep_main_nodes_and_rows( - main_package: Path | None, tmp_path: Path, kind: str, mode: str + main_package: Path, tmp_path: Path, kind: str, mode: str ) -> None: branch, main = both(main_package, "custom", str(tmp_path), kind, mode) if kind == "ordered": assert {"ab_total", "ba_total"} <= set(branch["listing"]["labels"]) - if main is not None: - assert branch == main + # S1: main's exact ValueError, never another error type. + assert {error[0] for error in branch["node_hash"].values()} == {"ValueError"} + require_no_write_failure(branch) + assert branch == main @pytest.mark.parametrize("receiver", ["pipeline", "job"]) def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( - main_package: Path | None, receiver: str + main_package: Path, receiver: str ) -> None: branch, main = both(main_package, "membership", receiver) refused = [ @@ -579,19 +760,60 @@ def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( "one of the DAG's own nodes. Access the node by label with job.nodes[label] " "or pipeline.nodes[label].", ] - accepted = {"foreign", "foreign_view", "foreign_stream", "graph_attribute"} - assert branch["foreign"] == branch["foreign_view"] == refused # R-IN - assert branch["foreign_stream"] == refused # R-IN - assert branch["graph_attribute"] is False # R-GRAPH + accepted = { + "foreign", + "foreign_view", + "foreign_stream", + "graph_attribute", + "dag_type", + "view_type", + } + # R-IN + assert branch["foreign"] == branch["foreign_view"] == refused + assert branch["foreign_stream"] == refused + assert (branch["dag_type"], branch["view_type"]) == ( + "CompiledDAG", + "CompiledNodeView", + ) + assert main["foreign"] == main["foreign_view"] == ["ok", True] + assert main["foreign_stream"][0] == "ok" + assert (main["dag_type"], main["view_type"]) == ("OrcaDAG", "dict_keys") + # R-GRAPH + assert branch["graph_attribute"] is False + assert main["graph_attribute"] is True + # The rest as main: own nodes, labels, and the DAG is still an OrcaDAG. assert branch["own"] == branch["own_view"] == branch["label"] == ["ok", True] - if main is not None: - assert main["foreign"] == main["foreign_view"] == ["ok", True] - assert main["foreign_stream"][0] == "ok" - assert main["graph_attribute"] is True - same = {key: value for key, value in branch.items() if key not in accepted} - assert same == { - key: value for key, value in main.items() if key not in accepted - } + assert branch["dag_is_orca_dag"] is True + same = {key: value for key, value in branch.items() if key not in accepted} + assert same == {key: value for key, value in main.items() if key not in accepted} + + +# The one refusal per code, raised by the capture of the second form. +CAPTURE_REFUSALS = { + "R-53/54": "The same stream is captured directly and through a slot declared " + "from it (slot 'a'). Use the slot declaration or capture the stream directly, " + "not both (ITL-1559).", + "R-MIX": "Source 'dict_v1:a' would be read by slots {first!r} and {second!r}. One " + "source object on two slots is not supported yet (ITL-1559, step 6). Read it " + "through one slot and branch from that slot.", + "ROWS-37-38": "Slot 'a' already holds {held}; {other} is another object under " + "the same name. A slot holds exactly one source object until source equivalence " + "is defined (ITL-1553). Pass the same object again, or declare the second one " + "under its own slot name with SourceNode.from_stream(stream, name=...).", +} + + +def capture_refusal(code: str, order: str) -> str: + """The exact refusal of the second capture, by code and capture order.""" + if code == "R-MIX": + first, second = ("b", "a") if order == "forward" else ("a", "b") + return CAPTURE_REFUSALS[code].format(first=first, second=second) + if code == "ROWS-37-38": + held, other = "declared slot 'a'", "source 'dict_v1:a'" + if order == "reversed": + held, other = other, held + return CAPTURE_REFUSALS[code].format(held=held, other=other) + return CAPTURE_REFUSALS[code] @pytest.mark.parametrize("order", ["forward", "reversed"]) @@ -600,66 +822,128 @@ def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( ("case", "code"), [ ("slot-and-direct", "R-53/54"), + ("unnamed-slot-and-direct", "R-53/54"), ("slot-and-direct-renamed", "R-MIX"), ("slot-and-root-one-name", "ROWS-37-38"), ], ) def test_capture_refusals_differ_from_main_as_accepted( - main_package: Path | None, case: str, code: str, receiver: str, order: str + main_package: Path, case: str, code: str, receiver: str, order: str ) -> None: branch, main = both(main_package, "capture", case, receiver, order) - error, message = branch["capture"] - assert error == "InconsistentSourceError", code - if code == "ROWS-37-38": - assert "is another object under the same name" in message - assert "(ITL-1553)" in message - else: - assert ( - "One source object on two slots is not supported yet (ITL-1559, step 6)" - in message - or "already declared under slot" in message - ) - if main is not None: - # Main accepts each of these captures. - assert main["capture"][0] == "ok", (code, main) + second = "direct" if order == "forward" else "slot" + assert branch["step_1"] == ["ok", None] + assert branch["step_2"] == [ + "InconsistentSourceError", + f"While capturing step {second!r}: {capture_refusal(code, order)}", + ], code + # Main accepts both captures. + assert main["step_1"] == main["step_2"] == ["ok", None], (code, main) + # The graph keeps what the first capture recorded, as main does before it. + assert branch["nodes"][0] == "ok" +@pytest.mark.parametrize("route", ["capture", "import"]) @pytest.mark.parametrize("receiver", ["pipeline", "job"]) @pytest.mark.parametrize("kind", ["operator", "function"]) def test_rewire_87_differs_from_main_as_accepted( - main_package: Path | None, kind: str, receiver: str + main_package: Path, kind: str, receiver: str, route: str ) -> None: - branch, main = both(main_package, "rewire", kind, receiver) - assert branch["same"][0] == "ok" - assert branch["other"] == [ # REWIRE-87 + branch, main = both(main_package, "rewire", kind, receiver, route) + # The same inputs again: accepted, as main, and the graph compiles. + assert branch["same"] == main["same"] == ["ok", None] + assert branch["same_compile"] == main["same_compile"] + assert branch["same_compile"][0] == "ok" + # REWIRE-87: refused at the setter itself; main accepts it. + assert branch["other"] == [ "InconsistentSourceError", "Cannot rewire 'descriptor' because a pipeline or job captured it as an input " "(ITL-1559). Create a new descriptor for the new inputs; rewiring a captured " "input is ITL-1847.", ] - if main is not None: - assert main["same"] == branch["same"] - assert main["other"][0] == "ok" + assert main["other"] == ["ok", None] + # Refused, the step keeps its inputs: the graph compiles as before. + assert branch["other_compile"] == branch["same_compile"] + + +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +def test_r_mix_through_from_invocations_differs_from_main_as_accepted( + main_package: Path, receiver: str +) -> None: + branch, main = both(main_package, "imported-mixed", receiver) + assert branch["import"] == [ # R-MIX, as a direct capture refuses it + "InconsistentSourceError", + "Source 'dict_v1:a' would be read by slots 'a' and 'different'. One source " + "object on two slots is not supported yet (ITL-1559, step 6). Read it through " + "one slot and branch from that slot.", + ] + assert main["import"][0] == "ok" + + +def test_dag_dup_differs_from_main_as_accepted(main_package: Path) -> None: + branch, main = both(main_package, "dag-dup") + refused = [ + "InconsistentSourceError", + "Nodes 'd' and 'd' are two distinct nodes with one node hash. A node hash is " + "unique within a pipeline (ITL-1559): give the slots different names, or " + "build the pipeline again with this version of Orcapod.", + ] + for side in (branch, main): + assert side["distinct"] is True and side["one_node_hash"] is True + # DAG-DUP + assert branch["add_node"] == branch["add_edge"] == refused + assert branch["dag_nodes"].count("d") == 1 + assert main["add_node"] == main["add_edge"] == ["ok", None] + assert main["dag_nodes"].count("d") == 2 + assert sorted(set(main["dag_nodes"])) == sorted(branch["dag_nodes"]) + + +def test_project_dup_differs_from_main_as_accepted(main_package: Path) -> None: + branch, main = both(main_package, "project-dup") + # The compiled step's setter stays as main (Q-B). + assert branch["setter"] == main["setter"] == ["ok", None] + assert branch["one_node_hash"] is main["one_node_hash"] is True + # PROJECT-DUP: main keeps both labels but one DAG node; refused here. + assert main["project"][0] == "ok" + assert {"first", "second"} <= set(main["project"][1]["nodes"]) + assert "first" not in main["project"][1]["dag"] + assert branch["project"] == [ + "InconsistentSourceError", + "Nodes 'first' and 'second' are two distinct nodes with one node hash. A node " + "hash is unique within a pipeline (ITL-1559): give the slots different names, " + "or build the pipeline again with this version of Orcapod.", + ] def test_load_dup_refuses_a_file_main_writes_with_two_nodes_of_one_hash( - main_package: Path | None, tmp_path: Path + main_package: Path, tmp_path: Path ) -> None: - if main_package is None: - pytest.skip(f"The main commit {MAIN} is not available") path = tmp_path / "dup.json" written = probe(main_package, "save-dup", str(path)) assert written["saved"][0] == "ok" branch = probe(ROOT / "src", "load", str(path)) main = probe(main_package, "load", str(path)) assert main["pipeline"][0] == "ok" - error, message = branch["pipeline"] # LOAD-DUP - assert error == "InconsistentSourceError" - assert "are two distinct nodes with one node hash" in message + assert branch["pipeline"] == [ # LOAD-DUP + "InconsistentSourceError", + "Nodes 'a_1' and 'a_2' are two distinct nodes with one node hash. A node " + "hash is unique within a pipeline (ITL-1559): give the slots different names, " + "or build the pipeline again with this version of Orcapod.", + ] + + +class _Logged(logging.Handler): + def emit(self, record: logging.LogRecord) -> None: + LOGGED.append(f"{record.levelname}: {record.getMessage()}") if __name__ == "__main__": import warnings warnings.simplefilter("ignore") - print(json.dumps(dispatch(sys.argv[1:]), default=str)) + orcapod_logger = logging.getLogger("orcapod") + orcapod_logger.addHandler(_Logged(level=logging.WARNING)) + outcome = dispatch(sys.argv[1:]) + if isinstance(outcome, dict): + outcome["logged"] = LOGGED + print(json.dumps(outcome, default=str)) diff --git a/tests/test_pipeline/test_pipeline.py b/tests/test_pipeline/test_pipeline.py index 6d20a23e4..c2dccc0fb 100644 --- a/tests/test_pipeline/test_pipeline.py +++ b/tests/test_pipeline/test_pipeline.py @@ -11,6 +11,7 @@ from __future__ import annotations +import json from typing import cast import pyarrow as pa @@ -562,17 +563,24 @@ def test_graph_label_attribute(self, pipeline_db): pipeline = job.pipeline assert pipeline.nodes["my_join"].label == "my_join" - def test_graph_pipeline_hash_attribute(self, pipeline_db): - """Compiled nodes have pipeline_hash attribute set in the graph.""" + def test_graph_pipeline_hash_attribute(self, pipeline_db, tmp_path): + """A compiled node's pipeline hash is recorded in the saved pipeline.""" src_a, src_b = _make_two_sources() job = PipelineJob(database=pipeline_db) with job: Join()(src_a, src_b, label="joiner") pipeline = job.pipeline - joiner_hash = pipeline.joiner.node_hash().to_string() - stored_ph = pipeline._hash_graph.nodes[joiner_hash].get("pipeline_hash") - assert stored_ph is not None - assert stored_ph == pipeline.joiner.pipeline_hash().to_string() + path = tmp_path / "pipeline.json" + pipeline.save(path) + saved = json.loads(path.read_text()) + (descriptor,) = [ + node for node in saved["nodes"].values() if node["label"] == "joiner" + ] + assert ( + descriptor["pipeline_hash"] == pipeline.joiner.pipeline_hash().to_string() + ) + loaded = Pipeline.load(path) + assert loaded.joiner.pipeline_hash() == pipeline.joiner.pipeline_hash() # --------------------------------------------------------------------------- diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index c0d9f6931..5a07eac78 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -128,7 +128,9 @@ def _capture( # through the explicit slot ``a`` and directly (as source ``a``) are refused at the # capture that brings the second form, R-53/54 (one name) or R-MIX (``a2``), before # their steps could shadow each other. ``unary`` keeps main's compile refusal. -_CAPTURE_REFUSAL = "One source object on two slots|already declared under slot" +_CAPTURE_REFUSAL = ( + "One source object on two slots|captured directly and through a slot declared from it" +) def _refused_at_capture(case: str) -> bool: From adc54a1d8b621a1bcdfde287acc4c16655feee44 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:24:47 -0800 Subject: [PATCH 03/12] style(tests): format the capture refusal pattern (ITL-1848) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_shadowed_job_steps.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py index 5a07eac78..d66cd87d0 100644 --- a/tests/test_pipeline/test_shadowed_job_steps.py +++ b/tests/test_pipeline/test_shadowed_job_steps.py @@ -128,9 +128,7 @@ def _capture( # through the explicit slot ``a`` and directly (as source ``a``) are refused at the # capture that brings the second form, R-53/54 (one name) or R-MIX (``a2``), before # their steps could shadow each other. ``unary`` keeps main's compile refusal. -_CAPTURE_REFUSAL = ( - "One source object on two slots|captured directly and through a slot declared from it" -) +_CAPTURE_REFUSAL = "One source object on two slots|captured directly and through a slot declared from it" def _refused_at_capture(case: str) -> bool: From 4d36ad2c359c857300e32793c63f8e370ce4b22e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:31:17 -0800 Subject: [PATCH 04/12] test(pipeline): fix result ids by what a result is; spec test reads dag (ITL-1848) The async lifecycle case failed in CI: ids taken from a counter at computation land on other rows when an async run computes in another order. The gate now derives each result id from the run, the function's uri, its outputs and their occurrence. The specification test of the tracker reads the compiled graph through dag (R-GRAPH). Co-Authored-By: Claude Opus 5.5 --- test-specification/unit/test_tracker.py | 7 +-- .../test_graph_keys_main_compatibility.py | 51 ++++++++++++++++--- 2 files changed, 48 insertions(+), 10 deletions(-) diff --git a/test-specification/unit/test_tracker.py b/test-specification/unit/test_tracker.py index 7e1a7b197..06fe85e0b 100644 --- a/test-specification/unit/test_tracker.py +++ b/test-specification/unit/test_tracker.py @@ -127,6 +127,7 @@ def test_compile_builds_graph(self): tracker.record_function_pod_invocation(pod, spec) tracker.compile() - graph = tracker.graph - assert graph is not None - assert graph.number_of_nodes() >= 1 + # The compiled graph is ``dag`` (ITL-1848: no ``graph`` attribute). + dag = tracker.dag + assert dag is not None + assert len(dag) >= 1 diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 6a6e7a5fa..7e695d6d1 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -37,6 +37,9 @@ import sys from collections.abc import Callable from datetime import datetime, timezone, tzinfo +import hashlib +import threading +from collections import Counter from itertools import count from pathlib import Path from types import SimpleNamespace @@ -50,6 +53,7 @@ from typing_extensions import override from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.data_function import PythonDataFunction from orcapod.core.nodes.function_node import FunctionJobNode, FunctionNode from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNode from orcapod.core.operators import Join, SelectDataColumns @@ -63,7 +67,7 @@ MAIN = "2075e85e2c9418444ec5368e800f71d354fd0b5e" MODES = ["sync", "async"] # One sequence per interpreter, never restarted, so every run's ids are unique. -RESULT_IDS = count(1) +FROZEN_RUNS = count(1) RUN_IDS = count(1) # Warnings and errors Orcapod logs while a case runs (a write failure among them). LOGGED: list[str] = [] @@ -166,16 +170,49 @@ def saved(job: PipelineJob, path: Path) -> str: return path.read_text() -def frozen_run(job: PipelineJob, mode: str) -> dict[str, Any]: - """Run with generated ids and times fixed, so stored tables compare. +class _ResultIds: + """Result ids fixed by what a result is, never by when it is computed. - The ids come from one sequence per interpreter, so no two runs share one. + An async run computes rows in no fixed order, so an id taken from a counter at + computation would land on another row in each interpreter. Here a result's id is + a digest of the frozen run's number, the function's uri, its output values and + their occurrence: the same in this checkout and on main, unique across runs. """ + + def __init__(self) -> None: + self.run = next(FROZEN_RUNS) + self.seen: Counter[str] = Counter() + self.lock = threading.Lock() + self.current = threading.local() + self.build = PythonDataFunction._build_output_data # pyright: ignore[reportPrivateUsage] # wrapped to know the output + + def build_output_data(self, function: Any, values: Any) -> Any: + self.current.key = f"{function.uri}|{values!r}" + try: + return self.build(function, values) + finally: + self.current.key = None + + def uuid7(self) -> UUID: + key = getattr(self.current, "key", None) + assert key is not None, "a result id outside a function's output" + with self.lock: + self.seen[key] += 1 + occurrence = self.seen[key] + digest = hashlib.sha256(f"{self.run}|{occurrence}|{key}".encode()).digest() + return UUID(bytes=digest[:16]) + + +def frozen_run(job: PipelineJob, mode: str) -> dict[str, Any]: + """Run with generated ids and times fixed, so stored tables compare.""" + ids = _ResultIds() with ( - patch( - "orcapod.core.data_function.uuid7", - side_effect=lambda: UUID(int=next(RESULT_IDS)), + patch.object( + PythonDataFunction, + "_build_output_data", + lambda function, values: ids.build_output_data(function, values), ), + patch("orcapod.core.data_function.uuid7", side_effect=ids.uuid7), patch("orcapod.core.result_cache.datetime", FrozenClock), patch("orcapod.core.nodes.function_node.datetime", FrozenClock), patch( From 2aaf358cf98254372b7370f5d6693e287cfa2e7b Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:53:10 -0800 Subject: [PATCH 05/12] fix(pipeline): check DAG node hashes at the call; keep a declared slot's origin (ITL-1848) Address the delta review of PR 695: - CompiledDAG reads its vertices' node hashes when a node or edge is added, never from an index: a refused edge reserves nothing, and a vertex moved by the compiled step's setter is checked by its current node hash. Both ends of an edge are checked before either is inserted. A compile or load, which checks node hashes itself, builds its DAG through CompiledDAG.of_checked without the check. - Compile clears the origin only on a slot it built, so an explicit slot compiled in one pipeline is still refused beside its source in another. - A node-hash refusal names two slots when slots share a node hash. - The gate requires the run after unbind to succeed, covers the refused edge, the setter, the compiled slot and the import routes of R-53/54 and ROWS-37-38, and runs its lifecycle and bind cases with a second source arrangement (another tag order, a data-tag). Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/base.py | 44 ++-- src/orcapod/pipeline/dag.py | 88 +++++-- src/orcapod/pipeline/graph.py | 17 +- .../test_graph_keys_main_compatibility.py | 233 +++++++++++++----- 4 files changed, 288 insertions(+), 94 deletions(-) diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 35d105230..4b81c76cf 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -715,10 +715,13 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse def _source_node_from_recording(self, key: str) -> Any: """Create the source node for a recorded leaf.""" - node = self.source_node_class.from_stream(self._source_streams[key]) - # A slot a compile builds is not a declaration: another pipeline may capture - # it beside its source, as on main (ITL-1848). - node._declared_from = None + stream = self._source_streams[key] + node = self.source_node_class.from_stream(stream) + if node is not stream: + # A slot a compile builds is not a declaration: another pipeline may + # capture it beside its source, as on main (ITL-1848). A slot the user + # declared (returned as it is) keeps its origin. + node._declared_from = None return node # ------------------------------------------------------------------ @@ -982,14 +985,15 @@ def _compile_nodes( # 5. Build node_graph (OrcaDAG with node objects as vertices). graph_edges = sorted(self._hash_graph.edges()) - node_dag: OrcaDAG[NodeT] = CompiledDAG() - for node in node_map.values(): - node_dag.add_node(node) - for up_hash, down_hash in graph_edges: - up_node = node_map.get(up_hash) - down_node = node_map.get(down_hash) - if up_node is not None and down_node is not None: - node_dag.add_edge(up_node, down_node) + # The node hashes were checked above (_require_one_node_per_graph_key). + node_dag: OrcaDAG[NodeT] = CompiledDAG.of_checked( + node_map.values(), + ( + (node_map[up_hash], node_map[down_hash]) + for up_hash, down_hash in graph_edges + if up_hash in node_map and down_hash in node_map + ), + ) self._node_graph = node_dag # 6. Enrich hash_graph node attributes (used by serialization). @@ -1083,10 +1087,20 @@ def _require_one_node_per_graph_key( keys: Each capture key's graph key (``None``: a node without one). Raises: - InconsistentSourceError: Naming both nodes. + InconsistentSourceError: Naming both nodes: two slots when slots share a + node hash (the steps below them then share one too), so the error + names what its remedy renames. """ - for _, first, second in shared_graph_keys(keys): - raise shared_node_hash_error(nodes[first], nodes[second]) + pairs = shared_graph_keys(keys) + if not pairs: + return + slots = [ + pair + for pair in pairs + if getattr(nodes[pair[1]], "node_type", None) == "source" + ] + _, first, second = (slots or pairs)[0] + raise shared_node_hash_error(nodes[first], nodes[second]) def _publish_graph_keys(self, keys: Mapping[str, str]) -> None: """Re-key the compiled maps, given by capture key, to their graph keys.""" diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index 70c206a70..1a52d4ee4 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -18,6 +18,7 @@ from __future__ import annotations import heapq +from contextlib import contextmanager from collections.abc import Hashable, KeysView from graphlib import CycleError, TopologicalSorter from inspect import getattr_static @@ -489,10 +490,40 @@ class CompiledDAG(OrcaDAG[NodeT]): string, a number) answer as on ``OrcaDAG``. """ + @classmethod + def of_checked( + cls, nodes: Iterable[NodeT], edges: Iterable[tuple[NodeT, NodeT]] + ) -> CompiledDAG[NodeT]: + """Build a compiled DAG from nodes whose node hashes the caller checked. + + A compile (``_require_one_node_per_graph_key``) and a load (LOAD-DUP) refuse + two nodes with one node hash before they build the DAG, so this inserts + without checking again. + + Args: + nodes: The vertices, in insertion order. + edges: The edges, as pairs of vertices. + """ + dag = cls() + with dag._unchecked(): + for node in nodes: + dag.add_node(node) + for up, down in edges: + dag.add_edge(up, down) + return dag + def __init__(self) -> None: super().__init__() - # node hash -> the one vertex holding it (rule iii, ITL-1848) - self._by_node_hash: dict[str, NodeT] = {} + self._checking = True + + @contextmanager + def _unchecked(self) -> Iterator[None]: + """Insert without the node-hash check (the caller has checked).""" + previous, self._checking = self._checking, False + try: + yield + finally: + self._checking = previous def add_node(self, node: NodeT, **attrs: Any) -> None: """Add *node* as ``OrcaDAG.add_node`` does, keeping node hashes unique. @@ -501,29 +532,54 @@ def add_node(self, node: NodeT, **attrs: Any) -> None: InconsistentSourceError: If another vertex already holds the node's node hash: a node hash names one node within a pipeline (ITL-1848). """ - self._require_unique_node_hash(node) + if self._checking: + self._require_unique_node_hashes(node) super().add_node(node, **attrs) def add_edge(self, u: NodeT, v: NodeT) -> None: """Add an edge as ``OrcaDAG.add_edge`` does, keeping node hashes unique. + Both ends are checked before either is inserted, so a refused edge leaves + the DAG as it was. + Raises: InconsistentSourceError: If either end is a new vertex whose node hash - another vertex already holds (ITL-1848). + another vertex already holds, or the two ends are distinct new + vertices with one node hash (ITL-1848). """ - self._require_unique_node_hash(u) - self._require_unique_node_hash(v) - super().add_edge(u, v) - - def _require_unique_node_hash(self, node: NodeT) -> None: - if node in self._attrs: - return - node_hash = defined_node_hash(node) - if node_hash is None: + if self._checking: + self._require_unique_node_hashes(u, v) + # Both ends are checked: insert them without checking each again. + with self._unchecked(): + super().add_edge(u, v) + + def _require_unique_node_hashes(self, *candidates: NodeT) -> None: + """Refuse a candidate whose node hash another vertex holds now. + + The node hashes are read at the call, never remembered: a compiled step's + setter can move a vertex's node hash after it was inserted (Q-B). A manual + add is rare, so reading every vertex's node hash (O(n)) is accepted. + """ + vertices = tuple(self._attrs) + new: list[NodeT] = [] + for candidate in candidates: + # By identity: a vertex's Python hash can move after insertion (ITL-1873). + if not any(node is candidate for node in (*vertices, *new)): + new.append(candidate) + if not new: return - held = self._by_node_hash.setdefault(node_hash, node) - if held is not node: - raise shared_node_hash_error(held, node) + holders: dict[str, NodeT] = {} + for vertex in vertices: + node_hash = defined_node_hash(vertex) + if node_hash is not None: + holders.setdefault(node_hash, vertex) + for candidate in new: + node_hash = defined_node_hash(candidate) + if node_hash is None: + continue + held = holders.setdefault(node_hash, candidate) + if held is not candidate: + raise shared_node_hash_error(held, candidate) def __contains__(self, node: object) -> bool: return _require_held(self, node) diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index c8d459f89..d5c6894ee 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -654,14 +654,15 @@ def load(cls, path: str | Path) -> "Pipeline": nodes_by_label[node.label] = node pipeline._nodes = nodes_by_label - node_dag: CompiledDAG[GraphNode] = CompiledDAG() - for node in reconstructed.values(): - node_dag.add_node(node) - for up_hash, down_hash in edges: - up_node = reconstructed.get(up_hash) - down_node = reconstructed.get(down_hash) - if up_node is not None and down_node is not None: - node_dag.add_edge(up_node, down_node) + # Two nodes with one node hash are refused below, before return (LOAD-DUP). + node_dag: CompiledDAG[GraphNode] = CompiledDAG.of_checked( + reconstructed.values(), + ( + (reconstructed[up_hash], reconstructed[down_hash]) + for up_hash, down_hash in edges + if up_hash in reconstructed and down_hash in reconstructed + ), + ) pipeline._node_graph = node_dag pipeline._graph_edges = edges diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 7e695d6d1..900d60c84 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -93,12 +93,31 @@ def total(x: int, y: int) -> int: return x + y +# How the lifecycle and bind cases lay out their sources: ``plain`` (tags ``id``, +# ``part``, both tag only) or ``alternate`` (tags in the order ``part``, ``id``, with +# ``part`` a data-tag, and the data columns in the other order). +ARRANGEMENTS = ["plain", "alternate"] +# The arrangement of the case running in this interpreter (set by ``dispatch``). +CASE_SETTINGS = {"arrangement": "plain"} + + def source(name: str, base: int, *, column: str = "x") -> DictSource: """Two tag columns and two data columns, so every step sees several of each.""" + note = f"{column}_note" + if CASE_SETTINGS["arrangement"] == "alternate": + return DictSource( + [ + {"part": "p", note: "n", column: base, "id": 1}, + {"part": "q", note: "m", column: base + 1, "id": 2}, + ], + source_id=name, + tag_columns=["part", "id"], + tag_only_columns=["id"], + ) return DictSource( [ - {"id": 1, "part": "p", column: base, f"{column}_note": "n"}, - {"id": 2, "part": "q", column: base + 1, f"{column}_note": "m"}, + {"id": 1, "part": "p", column: base, note: "n"}, + {"id": 2, "part": "q", column: base + 1, note: "m"}, ], source_id=name, tag_columns=["id", "part"], @@ -449,6 +468,14 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: lambda: double.pod(SourceNode.from_stream(shared), label="slot"), lambda: triple.pod(shared, label="direct"), ] + elif case == "compiled-slot-and-direct": # R-MIX after the slot was compiled (D3) + declared = SourceNode.from_stream(shared, name="b") + with Pipeline("first"): + double.pod(declared, label="slot_use") + steps = [ + lambda: double.pod(declared, label="slot"), + lambda: triple.pod(shared, label="direct"), + ] elif case == "slot-and-direct-renamed": # R-MIX steps = [ lambda: double.pod(SourceNode.from_stream(shared, name="b"), label="slot"), @@ -537,26 +564,39 @@ def recompile() -> list[str]: } -def imported_mixed_case(receiver: str) -> dict[str, Any]: - """R-MIX through ``from_invocations``: one object directly and through a slot.""" +def imported_mixed_case(receiver: str, case: str = "renamed") -> dict[str, Any]: + """The capture refusals through ``from_invocations``. + + *case* is ``renamed`` (R-MIX: one object directly and through a slot of another + name), ``same`` (R-53/54: through a slot named by default) or ``other-object`` + (ROWS-37-38: a slot ``a`` and another source object named ``a``). + """ from orcapod.core.identity_chains import graph_hash - # One data column: an invocation reads exactly its function's parameters. - shared = DictSource( - [{"id": 1, "x": 3}, {"id": 2, "x": 4}], - source_id="a", - tag_columns=["id"], - tag_only_columns=True, - ) - slot = SourceNode.from_stream(shared, name="different") + def narrow(base: int) -> DictSource: + # One data column: an invocation reads exactly its function's parameters. + return DictSource( + [{"id": 1, "x": base}, {"id": 2, "x": base + 1}], + source_id="a", + tag_columns=["id"], + tag_only_columns=True, + ) + + shared = narrow(3) + if case == "renamed": + slot, direct = SourceNode.from_stream(shared, name="different"), shared + elif case == "same": + slot, direct = SourceNode.from_stream(shared), shared + else: + slot, direct = SourceNode.from_stream(shared, name="a"), narrow(9) imported = InvocationGraph( tuple( FunctionInvocation( pod=cast("Any", double.pod), input_streams=(leaf,), label=label ) - for leaf, label in ((shared, "direct"), (slot, "declared")) + for leaf, label in ((direct, "direct"), (slot, "declared")) ), - {graph_hash(leaf).to_string(): leaf for leaf in (shared, slot)}, + {graph_hash(leaf).to_string(): leaf for leaf in (direct, slot)}, ) receiver_class = PipelineJob if receiver == "job" else Pipeline return { @@ -586,6 +626,52 @@ def dag_duplicate_case() -> dict[str, Any]: "add_node": caught(lambda: left.dag.add_node(other)), "add_edge": caught(lambda: left.dag.add_edge(left.nodes["slot"], other)), "dag_nodes": sorted(node.label for node in left.dag.nodes()), + "refused_edge": refused_edge_route(), + "after_setter": after_setter_route(), + } + + +def one_step_job(label: str, slot: str, source_name: str) -> PipelineJob: + """A job of one function step over the slot *slot*, bound to a fresh source.""" + data = source(source_name, 1) + blueprint = Pipeline(label) + with blueprint: + double.pod(SourceNode.from_stream(data, name=slot), label=label) + return PipelineJob.from_pipeline(blueprint, sources={slot: data}) + + +def refused_edge_route() -> dict[str, Any]: + """D1: a refused edge inserts nothing and reserves nothing.""" + dag = one_step_job("held", "slot_a", "origin").dag + target = one_step_job("target", "slot_a", "other").nodes["target"] + candidate = one_step_job("candidate", "slot_b", "first").nodes["candidate"] + retry = one_step_job("retry", "slot_b", "second").nodes["retry"] + edge = caught(lambda: dag.add_edge(candidate, target)) + after_edge = [node.label for node in dag.nodes()] + return { + "retry_shares_candidate_hash": retry.node_hash() == candidate.node_hash(), + "edge": edge, + "after_edge": after_edge, + "retry": caught(lambda: dag.add_node(retry)), + "final": [node.label for node in dag.nodes()], + } + + +def after_setter_route() -> dict[str, Any]: + """D2: a vertex moved by the compiled-step setter is checked by its node hash now.""" + job = one_step_job("held", "slot_a", "origin") + held = job.nodes["held"] + old_hash = held.node_hash() + moved = one_step_job("moved", "slot_b", "other").nodes["moved"] + held.upstreams = moved.upstreams + slot_a = one_step_job("slot_a_node", "slot_a", "first").nodes["slot_a_node"] + slot_b = one_step_job("slot_b_node", "slot_b", "second").nodes["slot_b_node"] + return { + "slot_a_has_old_hash": slot_a.node_hash() == old_hash, + "slot_b_has_new_hash": slot_b.node_hash() == held.node_hash(), + "slot_a_add": caught(lambda: job.dag.add_node(slot_a)), + "slot_b_add": caught(lambda: job.dag.add_node(slot_b)), + "final": [node.label for node in job.dag.nodes()], } @@ -691,10 +777,10 @@ def require_no_write_failure(outcome: dict[str, Any]) -> None: def dispatch(args: list[str]) -> Any: name, rest = args[0], args[1:] - if name == "lifecycle": - return lifecycle_case(Path(rest[0]), rest[1]) - if name == "bind": - return bind_case(Path(rest[0]), rest[1]) + if name in ("lifecycle", "bind"): + CASE_SETTINGS["arrangement"] = rest[2] + case = lifecycle_case if name == "lifecycle" else bind_case + return case(Path(rest[0]), rest[1]) if name == "custom": return custom_operator_case(Path(rest[0]), rest[1], rest[2]) if name == "membership": @@ -704,7 +790,7 @@ def dispatch(args: list[str]) -> Any: if name == "rewire": return rewire_case(rest[0], rest[1], rest[2]) if name == "imported-mixed": - return imported_mixed_case(rest[0]) + return imported_mixed_case(*rest) if name == "dag-dup": return dag_duplicate_case() if name == "project-dup": @@ -721,36 +807,33 @@ def no_failed_rows(summary: dict[str, list[int]]) -> bool: @pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) def test_lifecycle_rows_stores_and_saved_bytes_match_main( - main_package: Path, tmp_path: Path, mode: str + main_package: Path, tmp_path: Path, mode: str, arrangement: str ) -> None: (tmp_path / "branch").mkdir() (tmp_path / "main").mkdir() - branch = probe(ROOT / "src", "lifecycle", "work", mode, cwd=tmp_path / "branch") - assert branch["rows"]["double_a"] == sorted( - map( - repr, - [ - {"id": 1, "part": "p", "doubled": 6}, - {"id": 2, "part": "q", "doubled": 8}, - ], - ) - ) + args = ("lifecycle", "work", mode, arrangement) + branch = probe(ROOT / "src", *args, cwd=tmp_path / "branch") + assert sorted( + (row["id"], row["part"], row["doubled"]) + for row in map(eval, branch["rows"]["double_a"]) + ) == [(1, "p", 6), (2, "q", 8)] assert no_failed_rows(branch["summary"]) assert branch["recompiled"]["dag_is_orca_dag"] is True require_no_write_failure(branch) - assert branch == probe( - main_package, "lifecycle", "work", mode, cwd=tmp_path / "main" - ) + assert branch == probe(main_package, *args, cwd=tmp_path / "main") @pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("arrangement", ARRANGEMENTS) def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( - main_package: Path, tmp_path: Path, mode: str + main_package: Path, tmp_path: Path, mode: str, arrangement: str ) -> None: (tmp_path / "branch").mkdir() (tmp_path / "main").mkdir() - branch = probe(ROOT / "src", "bind", "work", mode, cwd=tmp_path / "branch") + args = ("bind", "work", mode, arrangement) + branch = probe(ROOT / "src", *args, cwd=tmp_path / "branch") # Every bind, rebind and restore recompiles and runs without a failed row. for step in ("initial", "rebind", "setter", "swap", "restore", "final"): recompiled, ran = branch[step][-2], branch[step][-1] @@ -758,18 +841,16 @@ def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( assert ran[0] == "ok", (step, ran) assert no_failed_rows(ran[1]["summary"]), (step, ran) assert branch["unbind"][2][0] == "ok" - assert branch["rebind"][-1][1]["rows"]["left_doubled"] == sorted( - map( - repr, - [ - {"id": 1, "part": "p", "doubled": 60}, - {"id": 2, "part": "q", "doubled": 62}, - ], - ) - ) + # The run after unbind is itself required to succeed with no failed row. + assert branch["run_unbound"][0] == "ok", branch["run_unbound"] + assert no_failed_rows(branch["run_unbound"][1]["summary"]), branch["run_unbound"] + assert sorted( + (row["id"], row["part"], row["doubled"]) + for row in map(eval, branch["rebind"][-1][1]["rows"]["left_doubled"]) + ) == [(1, "p", 60), (2, "q", 62)] assert branch["own_node"][0] == "SourceSpecMismatchError" require_no_write_failure(branch) - assert branch == probe(main_package, "bind", "work", mode, cwd=tmp_path / "main") + assert branch == probe(main_package, *args, cwd=tmp_path / "main") @pytest.mark.parametrize("mode", MODES) @@ -861,6 +942,7 @@ def capture_refusal(code: str, order: str) -> str: ("slot-and-direct", "R-53/54"), ("unnamed-slot-and-direct", "R-53/54"), ("slot-and-direct-renamed", "R-MIX"), + ("compiled-slot-and-direct", "R-MIX"), ("slot-and-root-one-name", "ROWS-37-38"), ], ) @@ -903,18 +985,32 @@ def test_rewire_87_differs_from_main_as_accepted( assert branch["other_compile"] == branch["same_compile"] +IMPORT_REFUSALS = { + "renamed": CAPTURE_REFUSALS["R-MIX"].format(first="a", second="different"), + "same": CAPTURE_REFUSALS["R-53/54"], + "other-object": CAPTURE_REFUSALS["ROWS-37-38"].format( + held="source 'dict_v1:a'", other="declared slot 'a'" + ), +} + + @pytest.mark.parametrize("receiver", ["pipeline", "job"]) -def test_r_mix_through_from_invocations_differs_from_main_as_accepted( - main_package: Path, receiver: str +@pytest.mark.parametrize( + ("case", "code"), + [("renamed", "R-MIX"), ("same", "R-53/54"), ("other-object", "ROWS-37-38")], +) +def test_capture_refusals_through_from_invocations_differ_from_main_as_accepted( + main_package: Path, receiver: str, case: str, code: str ) -> None: - branch, main = both(main_package, "imported-mixed", receiver) - assert branch["import"] == [ # R-MIX, as a direct capture refuses it - "InconsistentSourceError", - "Source 'dict_v1:a' would be read by slots 'a' and 'different'. One source " - "object on two slots is not supported yet (ITL-1559, step 6). Read it through " - "one slot and branch from that slot.", - ] - assert main["import"][0] == "ok" + branch, main = both(main_package, "imported-mixed", receiver, case) + # An imported graph is checked as a direct capture is (B3). + assert branch["import"] == ["InconsistentSourceError", IMPORT_REFUSALS[case]], code + main_nodes = { + "renamed": ["a", "declared", "different", "direct"], + "same": ["a_1", "a_2", "declared", "direct"], + "other-object": ["a_1", "a_2", "declared", "direct"], + } + assert main["import"] == ["ok", main_nodes[case]], code def test_dag_dup_differs_from_main_as_accepted(main_package: Path) -> None: @@ -934,6 +1030,33 @@ def test_dag_dup_differs_from_main_as_accepted(main_package: Path) -> None: assert main["dag_nodes"].count("d") == 2 assert sorted(set(main["dag_nodes"])) == sorted(branch["dag_nodes"]) + def refusal(held: str, other: str) -> list[str]: + return [ + refused[0], + refused[1].replace("'d' and 'd'", f"{held!r} and {other!r}"), + ] + + # D1: a refused edge inserts nothing and reserves nothing; the retry is added. + edge, main_edge = branch["refused_edge"], main["refused_edge"] + assert ( + edge["retry_shares_candidate_hash"] + is main_edge["retry_shares_candidate_hash"] + is True + ) + assert edge["edge"] == refusal("held", "target") + assert edge["after_edge"] == ["slot_a", "SelectDataColumns", "held"] + assert edge["retry"] == main_edge["retry"] == ["ok", None] + assert edge["final"] == [*edge["after_edge"], "retry"] + assert main_edge["edge"] == ["ok", None] + # D2: after the setter moves a vertex, its current node hash is the one held. + moved, main_moved = branch["after_setter"], main["after_setter"] + for side in (moved, main_moved): + assert side["slot_a_has_old_hash"] is side["slot_b_has_new_hash"] is True + assert moved["slot_a_add"] == main_moved["slot_a_add"] == ["ok", None] + assert moved["slot_b_add"] == refusal("held", "slot_b_node") + assert main_moved["slot_b_add"] == ["ok", None] + assert moved["final"] == ["slot_a", "SelectDataColumns", "held", "slot_a_node"] + def test_project_dup_differs_from_main_as_accepted(main_package: Path) -> None: branch, main = both(main_package, "project-dup") From f5b474a7db4638863ce12774495b51c347f3a1fe Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 08:54:02 -0800 Subject: [PATCH 06/12] test(pipeline): unit tests of CompiledDAG's node-hash check (ITL-1848) An equal but distinct vertex is refused (CodeRabbit on PR 695), a refused edge inserts and reserves nothing, a moved vertex is checked by its node hash now, and of_checked builds without reading node hashes. Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_compiled_dag.py | 141 +++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 tests/test_pipeline/test_compiled_dag.py diff --git a/tests/test_pipeline/test_compiled_dag.py b/tests/test_pipeline/test_compiled_dag.py new file mode 100644 index 000000000..f0d3cbfc1 --- /dev/null +++ b/tests/test_pipeline/test_compiled_dag.py @@ -0,0 +1,141 @@ +"""``CompiledDAG`` keeps node hashes unique (ITL-1848, rule iii). + +The vertices here stand in for pipeline nodes: they compare equal by their node hash, +as two nodes built from one pod and one input do, and their node hash can move after +insertion, as the compiled step's ``upstreams`` setter moves one. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +import pytest + +from orcapod.errors import InconsistentSourceError +from orcapod.pipeline.dag import CompiledDAG + + +@dataclass(frozen=True) +class _Hash: + text: str + + def to_string(self) -> str: + return self.text + + +class _Vertex: + """A vertex equal to every other vertex with its node hash.""" + + def __init__(self, label: str, node_hash: str) -> None: + self.label = label + self.current = node_hash + + def node_hash(self) -> _Hash: + return _Hash(self.current) + + def __eq__(self, other: object) -> bool: + return isinstance(other, _Vertex) and other.current == self.current + + def __hash__(self) -> int: + return hash(self.current) + + +def _refusal(held: str, other: str) -> str: + return f"Nodes {held!r} and {other!r} are two distinct nodes with one node hash" + + +def _labels(dag: CompiledDAG[_Vertex]) -> list[str]: + return [vertex.label for vertex in dag.nodes()] + + +def test_an_equal_but_distinct_vertex_is_refused() -> None: + # CodeRabbit on PR 695: equality must not let a second node merge into the first. + dag: CompiledDAG[_Vertex] = CompiledDAG() + held = _Vertex("held", "h1") + dag.add_node(held) + twin = _Vertex("twin", "h1") + assert twin == held and twin is not held + with pytest.raises(InconsistentSourceError, match=_refusal("held", "twin")): + dag.add_node(twin) + with pytest.raises(InconsistentSourceError, match=_refusal("held", "twin")): + dag.add_edge(held, twin) + assert _labels(dag) == ["held"] + assert list(dag.edges()) == [] + + +def test_the_dags_own_vertex_is_added_again_without_refusal() -> None: + dag: CompiledDAG[_Vertex] = CompiledDAG() + held, other = _Vertex("held", "h1"), _Vertex("other", "h2") + dag.add_node(held) + dag.add_node(held) + dag.add_edge(held, other) + dag.add_edge(held, other) + assert _labels(dag) == ["held", "other"] + assert [(up.label, down.label) for up, down in dag.edges()] == [("held", "other")] + + +@pytest.mark.parametrize("order", ["new-first", "new-second"]) +def test_a_refused_edge_inserts_nothing_and_reserves_nothing(order: str) -> None: + # D1: every end is checked before either is inserted. + dag: CompiledDAG[_Vertex] = CompiledDAG() + held = _Vertex("held", "h1") + dag.add_node(held) + candidate, target = _Vertex("candidate", "h2"), _Vertex("target", "h1") + ends = (candidate, target) if order == "new-first" else (target, candidate) + with pytest.raises(InconsistentSourceError, match=_refusal("held", "target")): + dag.add_edge(*ends) + assert _labels(dag) == ["held"] + assert list(dag.edges()) == [] + retry = _Vertex("retry", "h2") + dag.add_node(retry) + assert _labels(dag) == ["held", "retry"] + + +def test_two_new_ends_with_one_node_hash_are_refused() -> None: + dag: CompiledDAG[_Vertex] = CompiledDAG() + first, second = _Vertex("first", "h1"), _Vertex("second", "h1") + with pytest.raises(InconsistentSourceError, match=_refusal("first", "second")): + dag.add_edge(first, second) + assert _labels(dag) == [] + + +def test_a_moved_vertex_is_checked_by_its_node_hash_now() -> None: + # D2: the node hashes are read at the call, never remembered. + dag: CompiledDAG[_Vertex] = CompiledDAG() + held = _Vertex("held", "slot_a") + dag.add_node(held) + held.current = "slot_b" # as the compiled step's setter moves a vertex + dag.add_node(_Vertex("slot_a_node", "slot_a")) + with pytest.raises(InconsistentSourceError, match=_refusal("held", "slot_b_node")): + dag.add_node(_Vertex("slot_b_node", "slot_b")) + assert _labels(dag) == ["held", "slot_a_node"] + + +def test_a_vertex_without_a_node_hash_is_not_checked() -> None: + class _Undefined(_Vertex): + def node_hash(self) -> _Hash: + raise ValueError("Pipeline identity is undefined for a custom operator.") + + dag: CompiledDAG[_Vertex] = CompiledDAG() + dag.add_node(_Undefined("first", "x")) + dag.add_node(_Undefined("second", "y")) + assert _labels(dag) == ["first", "second"] + + +def test_of_checked_builds_without_reading_node_hashes() -> None: + # A compile or load has checked its node hashes before it builds the DAG. + class _Counted(_Vertex): + reads = 0 + + def node_hash(self) -> _Hash: + _Counted.reads += 1 + return super().node_hash() + + up, down = _Counted("up", "h1"), _Counted("down", "h2") + dag = CompiledDAG.of_checked([up, down], [(up, down)]) + assert _Counted.reads == 0 + assert _labels(dag) == ["up", "down"] + assert [(u.label, d.label) for u, d in dag.edges()] == [("up", "down")] + # Afterwards, a manual add is checked again. + with pytest.raises(InconsistentSourceError, match=_refusal("up", "copy")): + dag.add_node(_Counted("copy", "h1")) From 5eeff5a5e443e6350880ede2d4d614da5ab5cfe8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 09:11:48 -0800 Subject: [PATCH 07/12] fix(pipeline): private checked DAG builder; no unchecked window in add_edge (ITL-1848) Address the second delta review of PR 695: - The builder that skips node-hash checks is private (CompiledDAG._from_checked) and takes no edge endpoint outside its nodes. Pipeline.load refuses two nodes with one node hash before it builds the DAG, so both callers check first. - OrcaDAG's storage is split from add_node/add_edge; CompiledDAG.add_edge stores its checked ends directly instead of turning the check off, so a re-entrant add_node is still checked. - A source captured beside another pipeline's compiled slot over it is refused as two slots with one node hash (ROWS-37-38, rule iii), with a message that names the compiled slot. Documented and in the gate. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1848.md | 8 +- docs/concepts/sources.md | 10 +- src/orcapod/core/nodes/source_node.py | 3 + src/orcapod/pipeline/base.py | 20 ++-- src/orcapod/pipeline/dag.py | 65 +++++----- src/orcapod/pipeline/graph.py | 18 +-- tests/test_pipeline/test_compiled_dag.py | 111 +++++++++++++++++- .../test_graph_keys_main_compatibility.py | 28 +++-- 8 files changed, 198 insertions(+), 65 deletions(-) diff --git a/changelog.d/ITL-1848.md b/changelog.d/ITL-1848.md index 9306d8242..3d7b4c56e 100644 --- a/changelog.d/ITL-1848.md +++ b/changelog.d/ITL-1848.md @@ -20,9 +20,11 @@ at the capture that brings the second form, whether the names agree or not, and also when the slot takes the source's own name (`SourceNode.from_stream(source)`). Graphs imported with `from_invocations` are checked the same way. -- An explicit slot and another source object with the same name (two slots with one node - hash) are refused with `InconsistentSourceError` at the capture that brings the second - one; declare the second source under its own slot name. +- Two slots that would have one node hash are refused with `InconsistentSourceError` at the + capture that brings the second one: an explicit slot and another source object with the + same name, or a source and the slot another pipeline's compile built over it + (`other.nodes["a"]`). Read the source through one of them, or declare the second source + under its own slot name. - Setting a captured step's `upstreams` to other streams raises `InconsistentSourceError`; build a new step for the new inputs (following such a change is ITL-1847). Setting the same streams again is still accepted. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index eaba8e72a..edd5b2035 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -109,11 +109,13 @@ A slot holds one source object. Read a source either through an explicit slot (`SourceNode.from_stream(source, name="units")`) or directly, never both in one pipeline or job: the capture that brings the second form raises `InconsistentSourceError`, under the same name or another, and also when the slot takes the source's own name -(`SourceNode.from_stream(source)`). Likewise, an explicit slot `units` and another source object named -`units` would be two slots with one node hash, so the capture that brings the second one is -refused; declare the second source under its own slot name +(`SourceNode.from_stream(source)`). Likewise, two slots that would have one node hash are +refused: an explicit slot `units` and another source object named `units`, or a source and +the slot another pipeline's compile built over it (`other_pipeline.nodes["units"]`). The +capture that brings the second one raises `InconsistentSourceError`. Read the source through +one of them, or give the second its own slot name (`SourceNode.from_stream(other, name="units_2")`). Until source equivalence is defined -(ITL-1553), pass the same object again or give each its own slot. +(ITL-1553), a slot holds one source object. An output stream returned by a run uses the slot bindings that were in effect when its rows were produced. Binding any slot that feeds it makes that output stale, diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 825ba1612..bfc554192 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1754,6 +1754,9 @@ def from_stream( # The stream a slot declared with ``from_stream`` was declared from (ITL-1848). _declared_from: weakref.ReferenceType[StreamProtocol] | None = None + # Whether a pipeline's compile built this slot over a source it captured + # directly, rather than a user declaring it (ITL-1848). + _built_by_compile: bool = False class SourceJobNode(ProvenanceMethods, SourceNodeBase): diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 4b81c76cf..6ca8afdaf 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -540,7 +540,11 @@ def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLea declared = isinstance(stream, SourceNode) if declared: name = stream.name - described = f"declared slot {name!r}" + described = ( + f"compiled slot {name!r}" + if stream._built_by_compile # pyright: ignore[reportPrivateUsage] # set by a compile + else f"declared slot {name!r}" + ) leaf = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from else: name = slot_name_for(stream, ContentHash.from_string(key)) @@ -621,11 +625,12 @@ def _refuse_shared_node_hash(leaf: CaptureLeaf, known: list[CaptureLeaf]) -> Non # capturing (one content hash) or compiling (one slot name). continue raise InconsistentSourceError( - f"Slot {leaf.name!r} already holds {other.described}; " - f"{leaf.described} is another object under the same name. A slot " - "holds exactly one source object until source equivalence is defined " - "(ITL-1553). Pass the same object again, or declare the second one " - "under its own slot name with SourceNode.from_stream(stream, name=...)." + f"Slot {leaf.name!r} would be two slots with one node hash: " + f"{other.described} and {leaf.described} are distinct objects. A node " + "hash names one node within a pipeline (ITL-1559), and a slot holds " + "one source object until source equivalence is defined (ITL-1553). " + "Read the source through one of them, or give the second its own slot " + "name with SourceNode.from_stream(stream, name=...)." ) def _hold_captured(self, stream: StreamProtocol) -> None: @@ -722,6 +727,7 @@ def _source_node_from_recording(self, key: str) -> Any: # capture it beside its source, as on main (ITL-1848). A slot the user # declared (returned as it is) keeps its origin. node._declared_from = None + node._built_by_compile = True return node # ------------------------------------------------------------------ @@ -986,7 +992,7 @@ def _compile_nodes( # 5. Build node_graph (OrcaDAG with node objects as vertices). graph_edges = sorted(self._hash_graph.edges()) # The node hashes were checked above (_require_one_node_per_graph_key). - node_dag: OrcaDAG[NodeT] = CompiledDAG.of_checked( + node_dag: OrcaDAG[NodeT] = CompiledDAG._from_checked( # pyright: ignore[reportPrivateUsage] # node hashes checked by _graph_keys_for node_map.values(), ( (node_map[up_hash], node_map[down_hash]) diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index 1a52d4ee4..4cd31e10d 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -18,7 +18,6 @@ from __future__ import annotations import heapq -from contextlib import contextmanager from collections.abc import Hashable, KeysView from graphlib import CycleError, TopologicalSorter from inspect import getattr_static @@ -139,6 +138,10 @@ def add_node(self, node: NodeT, **attrs: Any) -> None: node: The node to add. **attrs: Attribute key/value pairs to store on the node. """ + self._store_node(node, attrs) + + def _store_node(self, node: NodeT, attrs: dict[str, Any]) -> None: + """Store *node* and its attributes; the storage under ``add_node``.""" if node not in self._attrs: self._attrs[node] = {} self._successors[node] = {} @@ -159,6 +162,10 @@ def add_edge(self, u: NodeT, v: NodeT) -> None: """ self.add_node(u) self.add_node(v) + self._store_edge(u, v) + + def _store_edge(self, u: NodeT, v: NodeT) -> None: + """Store the edge between two stored nodes; the storage under ``add_edge``.""" if v not in self._successors[u]: self._successors[u][v] = None self._predecessors[v][u] = None @@ -491,40 +498,33 @@ class CompiledDAG(OrcaDAG[NodeT]): """ @classmethod - def of_checked( + def _from_checked( cls, nodes: Iterable[NodeT], edges: Iterable[tuple[NodeT, NodeT]] ) -> CompiledDAG[NodeT]: """Build a compiled DAG from nodes whose node hashes the caller checked. - A compile (``_require_one_node_per_graph_key``) and a load (LOAD-DUP) refuse - two nodes with one node hash before they build the DAG, so this inserts - without checking again. + For a compile (``_require_one_node_per_graph_key``) and a load (LOAD-DUP), + which refuse two nodes with one node hash before they build the DAG. It + inserts through the storage without reading node hashes, and takes no edge + endpoint that is not among *nodes*. Args: nodes: The vertices, in insertion order. - edges: The edges, as pairs of vertices. + edges: The edges, as pairs of vertices among *nodes*. + + Raises: + ValueError: If an edge names a vertex that is not among *nodes*. """ dag = cls() - with dag._unchecked(): - for node in nodes: - dag.add_node(node) - for up, down in edges: - dag.add_edge(up, down) + for node in nodes: + dag._store_node(node, {}) + for up, down in edges: + # As the storage finds a vertex (an edge never adds one here). + if up not in dag._attrs or down not in dag._attrs: + raise ValueError("an edge of a checked DAG names a vertex it lacks") + dag._store_edge(up, down) return dag - def __init__(self) -> None: - super().__init__() - self._checking = True - - @contextmanager - def _unchecked(self) -> Iterator[None]: - """Insert without the node-hash check (the caller has checked).""" - previous, self._checking = self._checking, False - try: - yield - finally: - self._checking = previous - def add_node(self, node: NodeT, **attrs: Any) -> None: """Add *node* as ``OrcaDAG.add_node`` does, keeping node hashes unique. @@ -532,26 +532,25 @@ def add_node(self, node: NodeT, **attrs: Any) -> None: InconsistentSourceError: If another vertex already holds the node's node hash: a node hash names one node within a pipeline (ITL-1848). """ - if self._checking: - self._require_unique_node_hashes(node) - super().add_node(node, **attrs) + self._require_unique_node_hashes(node) + self._store_node(node, attrs) def add_edge(self, u: NodeT, v: NodeT) -> None: """Add an edge as ``OrcaDAG.add_edge`` does, keeping node hashes unique. Both ends are checked before either is inserted, so a refused edge leaves - the DAG as it was. + the DAG as it was. The checked ends are stored directly: no check is turned + off, so an ``add_node`` that runs meanwhile is checked as any other. Raises: InconsistentSourceError: If either end is a new vertex whose node hash another vertex already holds, or the two ends are distinct new vertices with one node hash (ITL-1848). """ - if self._checking: - self._require_unique_node_hashes(u, v) - # Both ends are checked: insert them without checking each again. - with self._unchecked(): - super().add_edge(u, v) + self._require_unique_node_hashes(u, v) + self._store_node(u, {}) + self._store_node(v, {}) + self._store_edge(u, v) def _require_unique_node_hashes(self, *candidates: NodeT) -> None: """Refuse a candidate whose node hash another vertex holds now. diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index d5c6894ee..81b43dad4 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -654,8 +654,15 @@ def load(cls, path: str | Path) -> "Pipeline": nodes_by_label[node.label] = node pipeline._nodes = nodes_by_label - # Two nodes with one node hash are refused below, before return (LOAD-DUP). - node_dag: CompiledDAG[GraphNode] = CompiledDAG.of_checked( + # A file in which two distinct nodes share one node hash is refused before + # anything is built from it (LOAD-DUP, ITL-1848). A loaded node is held under + # ``legacy:`` and its saved key until saved files record node hashes + # (ITL-1864). + pipeline._require_one_node_per_graph_key( + reconstructed, + {key: defined_node_hash(node) for key, node in reconstructed.items()}, + ) + node_dag: CompiledDAG[GraphNode] = CompiledDAG._from_checked( # pyright: ignore[reportPrivateUsage] # node hashes checked just above reconstructed.values(), ( (reconstructed[up_hash], reconstructed[down_hash]) @@ -688,13 +695,6 @@ def load(cls, path: str | Path) -> "Pipeline": h: n for h, n in reconstructed.items() if n.node_type == "source" } - # A loaded node is held under ``legacy:`` and its saved key until saved - # files record node hashes (ITL-1864); a file in which two distinct nodes - # share one node hash is refused (ITL-1848). - pipeline._require_one_node_per_graph_key( - reconstructed, - {key: defined_node_hash(node) for key, node in reconstructed.items()}, - ) pipeline._publish_graph_keys( {key: legacy_graph_key(key) for key in reconstructed} ) diff --git a/tests/test_pipeline/test_compiled_dag.py b/tests/test_pipeline/test_compiled_dag.py index f0d3cbfc1..c0299ea85 100644 --- a/tests/test_pipeline/test_compiled_dag.py +++ b/tests/test_pipeline/test_compiled_dag.py @@ -7,7 +7,11 @@ from __future__ import annotations +from collections.abc import Callable from dataclasses import dataclass +from pathlib import Path +from typing import Any +from unittest.mock import patch import pytest @@ -122,7 +126,7 @@ def node_hash(self) -> _Hash: assert _labels(dag) == ["first", "second"] -def test_of_checked_builds_without_reading_node_hashes() -> None: +def test_the_checked_builder_reads_no_node_hash() -> None: # A compile or load has checked its node hashes before it builds the DAG. class _Counted(_Vertex): reads = 0 @@ -132,10 +136,113 @@ def node_hash(self) -> _Hash: return super().node_hash() up, down = _Counted("up", "h1"), _Counted("down", "h2") - dag = CompiledDAG.of_checked([up, down], [(up, down)]) + dag = CompiledDAG._from_checked([up, down], [(up, down)]) # pyright: ignore[reportPrivateUsage] # the builder under test assert _Counted.reads == 0 assert _labels(dag) == ["up", "down"] assert [(u.label, d.label) for u, d in dag.edges()] == [("up", "down")] # Afterwards, a manual add is checked again. with pytest.raises(InconsistentSourceError, match=_refusal("up", "copy")): dag.add_node(_Counted("copy", "h1")) + + +def test_the_checked_builder_takes_no_endpoint_outside_its_nodes() -> None: + # E1: an edge cannot bring in a vertex the caller did not check. + first, second = _Vertex("first", "h1"), _Vertex("second", "h2") + with pytest.raises(ValueError, match="names a vertex it lacks"): + CompiledDAG._from_checked([first], [(first, second)]) # pyright: ignore[reportPrivateUsage] # the builder under test + + +def test_the_checked_builder_is_not_public() -> None: + assert not hasattr(CompiledDAG, "of_checked") + assert not hasattr(CompiledDAG, "from_checked") + + +class _Reentrant(_Vertex): + """A vertex whose first Python hash runs a callback (E2 reproduction).""" + + def __init__(self, label: str, node_hash: str) -> None: + super().__init__(label, node_hash) + self.on_hash: Callable[[], None] | None = None + + def __eq__(self, other: object) -> bool: + return other is self + + def __hash__(self) -> int: + callback, self.on_hash = self.on_hash, None + if callback is not None: + callback() + return object.__hash__(self) + + +def test_an_add_node_during_add_edge_is_checked() -> None: + # E2: inserting an edge turns no check off, so a nested add is still refused. + dag: CompiledDAG[_Vertex] = CompiledDAG() + dag.add_node(_Reentrant("held", "shared")) + start, end = _Reentrant("start", "x"), _Reentrant("end", "y") + duplicate = _Reentrant("duplicate", "shared") + inner: list[BaseException] = [] + + def nested_add() -> None: + try: + dag.add_node(duplicate) + except InconsistentSourceError as error: + inner.append(error) + + start.on_hash = nested_add + dag.add_edge(start, end) + assert len(inner) == 1 + assert _refusal("held", "duplicate") in str(inner[0]) + assert _labels(dag) == ["held", "start", "end"] + + +@pytest.mark.parametrize("route", ["compile", "load"]) +def test_node_hashes_are_checked_before_the_dag_is_built( + route: str, tmp_path: Path +) -> None: + """E1: the builder's precondition holds at both of its call sites.""" + from orcapod import Pipeline, function_pod + from orcapod.pipeline.base import AbstractPipelineBase + from orcapod.sources import DictSource + + @function_pod(output_keys="doubled") + def double(x: int) -> int: + return 2 * x + + pipeline = Pipeline("order") + with pipeline: + double.pod( + DictSource( + [{"id": 1, "x": 1}, {"id": 2, "x": 2}], + source_id="a", + tag_columns=["id"], + tag_only_columns=True, + ) + ) + path = tmp_path / "pipeline.json" + pipeline.save(path) + calls: list[str] = [] + check = AbstractPipelineBase._require_one_node_per_graph_key # pyright: ignore[reportPrivateUsage] # the order under test + build = CompiledDAG._from_checked # pyright: ignore[reportPrivateUsage] # the order under test + + def checked(nodes: Any, keys: Any) -> None: + calls.append("check") + check(nodes, keys) + + def built(nodes: Any, edges: Any) -> Any: + calls.append("build") + return build(nodes, edges) + + with ( + patch.object( + AbstractPipelineBase, + "_require_one_node_per_graph_key", + staticmethod(checked), + ), + patch.object(CompiledDAG, "_from_checked", staticmethod(built)), + ): + if route == "compile": + pipeline.compile() + else: + Pipeline.load(path) + assert calls and calls[-1] == "build" + assert "check" in calls[: calls.index("build")] diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 900d60c84..5b32ef10c 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -476,6 +476,17 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: lambda: double.pod(declared, label="slot"), lambda: triple.pod(shared, label="direct"), ] + elif case == "compiled-implicit-slot-and-direct": + # ROWS-37-38, wider reading (E3): another pipeline's compiled slot over the + # source, beside the source itself: two slots with one node hash. + first = Pipeline("first") + with first: + double.pod(shared, label="first_use") + compiled_slot = first.nodes["a"] + steps = [ + lambda: double.pod(compiled_slot, label="slot"), + lambda: triple.pod(shared, label="direct"), + ] elif case == "slot-and-direct-renamed": # R-MIX steps = [ lambda: double.pod(SourceNode.from_stream(shared, name="b"), label="slot"), @@ -914,10 +925,11 @@ def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( "R-MIX": "Source 'dict_v1:a' would be read by slots {first!r} and {second!r}. One " "source object on two slots is not supported yet (ITL-1559, step 6). Read it " "through one slot and branch from that slot.", - "ROWS-37-38": "Slot 'a' already holds {held}; {other} is another object under " - "the same name. A slot holds exactly one source object until source equivalence " - "is defined (ITL-1553). Pass the same object again, or declare the second one " - "under its own slot name with SourceNode.from_stream(stream, name=...).", + "ROWS-37-38": "Slot 'a' would be two slots with one node hash: {held} and " + "{other} are distinct objects. A node hash names one node within a pipeline " + "(ITL-1559), and a slot holds one source object until source equivalence is " + "defined (ITL-1553). Read the source through one of them, or give the second " + "its own slot name with SourceNode.from_stream(stream, name=...).", } @@ -926,11 +938,12 @@ def capture_refusal(code: str, order: str) -> str: if code == "R-MIX": first, second = ("b", "a") if order == "forward" else ("a", "b") return CAPTURE_REFUSALS[code].format(first=first, second=second) - if code == "ROWS-37-38": - held, other = "declared slot 'a'", "source 'dict_v1:a'" + if code in ("ROWS-37-38", "ROWS-37-38-compiled"): + slot = "compiled slot 'a'" if code.endswith("compiled") else "declared slot 'a'" + held, other = slot, "source 'dict_v1:a'" if order == "reversed": held, other = other, held - return CAPTURE_REFUSALS[code].format(held=held, other=other) + return CAPTURE_REFUSALS["ROWS-37-38"].format(held=held, other=other) return CAPTURE_REFUSALS[code] @@ -943,6 +956,7 @@ def capture_refusal(code: str, order: str) -> str: ("unnamed-slot-and-direct", "R-53/54"), ("slot-and-direct-renamed", "R-MIX"), ("compiled-slot-and-direct", "R-MIX"), + ("compiled-implicit-slot-and-direct", "ROWS-37-38-compiled"), ("slot-and-root-one-name", "ROWS-37-38"), ], ) From 114e398848293f36b2570865dc44b85b3a425a9f Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 09:25:51 -0800 Subject: [PATCH 08/12] fix(pipeline): refuse re-entrant DAG changes; name working remedies (ITL-1848) Address the third delta review of PR 695: - A change of a CompiledDAG made while another change of it is in progress (from a vertex's __hash__ or __eq__) raises RuntimeError before it writes anything; the guard is cleared in a finally block. - The refusal of a source beside another pipeline's compiled slot names remedies that work: capture the source itself in place of the compiled slot, or read every use through one declared slot. The gate runs both remedies. - The comment on compile-built slots says what happens to them now. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1848.md | 4 +- docs/concepts/sources.md | 10 +-- src/orcapod/pipeline/base.py | 27 +++++--- src/orcapod/pipeline/dag.py | 42 +++++++++--- tests/test_pipeline/test_compiled_dag.py | 65 ++++++++++++++++--- .../test_graph_keys_main_compatibility.py | 51 +++++++++++++-- 6 files changed, 164 insertions(+), 35 deletions(-) diff --git a/changelog.d/ITL-1848.md b/changelog.d/ITL-1848.md index 3d7b4c56e..72668242f 100644 --- a/changelog.d/ITL-1848.md +++ b/changelog.d/ITL-1848.md @@ -24,7 +24,9 @@ capture that brings the second one: an explicit slot and another source object with the same name, or a source and the slot another pipeline's compile built over it (`other.nodes["a"]`). Read the source through one of them, or declare the second source - under its own slot name. + under its own slot name; for a compiled slot, which keeps its name, capture the source + itself in its place, or read every use through one slot declared from the source + (`SourceNode.from_stream(source, name=...)`). - Setting a captured step's `upstreams` to other streams raises `InconsistentSourceError`; build a new step for the new inputs (following such a change is ITL-1847). Setting the same streams again is still accepted. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index edd5b2035..602f07974 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -112,10 +112,12 @@ the same name or another, and also when the slot takes the source's own name (`SourceNode.from_stream(source)`). Likewise, two slots that would have one node hash are refused: an explicit slot `units` and another source object named `units`, or a source and the slot another pipeline's compile built over it (`other_pipeline.nodes["units"]`). The -capture that brings the second one raises `InconsistentSourceError`. Read the source through -one of them, or give the second its own slot name -(`SourceNode.from_stream(other, name="units_2")`). Until source equivalence is defined -(ITL-1553), a slot holds one source object. +capture that brings the second one raises `InconsistentSourceError`. For two sources, read +the source through one of them, or give the second its own slot name +(`SourceNode.from_stream(other, name="units_2")`). For another pipeline's compiled slot, +which keeps its name, capture the source itself in its place, or read every use through one +slot declared from the source (`SourceNode.from_stream(source, name="units_2")`). Until source equivalence is +defined (ITL-1553), a slot holds one source object. An output stream returned by a run uses the slot bindings that were in effect when its rows were produced. Binding any slot that feeds it makes that output stale, diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 6ca8afdaf..6824c80a6 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -111,6 +111,7 @@ class CaptureLeaf: or the stream itself. ``None`` when it is not known. declared: Whether the leaf came through an explicit slot declaration. root: Whether the leaf is a source captured directly. + compiled: Whether the leaf is a slot a pipeline's compile built. """ capture_key: str @@ -120,6 +121,7 @@ class CaptureLeaf: leaf: ReferenceType[Any] | None declared: bool root: bool + compiled: bool = False def is_object(self, other: CaptureLeaf) -> bool: """Whether both leaves are one live object.""" @@ -538,12 +540,11 @@ def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLea from orcapod.types import ContentHash declared = isinstance(stream, SourceNode) + compiled = declared and stream._built_by_compile # pyright: ignore[reportPrivateUsage] # set by a compile if declared: name = stream.name described = ( - f"compiled slot {name!r}" - if stream._built_by_compile # pyright: ignore[reportPrivateUsage] # set by a compile - else f"declared slot {name!r}" + f"compiled slot {name!r}" if compiled else f"declared slot {name!r}" ) leaf = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from else: @@ -585,6 +586,7 @@ def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLea leaf=leaf, declared=declared, root=isinstance(stream, RootSource), + compiled=compiled, ) @staticmethod @@ -624,13 +626,21 @@ def _refuse_shared_node_hash(leaf: CaptureLeaf, known: list[CaptureLeaf]) -> Non # Two sources with one slot name: main refuses them itself, when # capturing (one content hash) or compiling (one slot name). continue + remedy = ( + # A compiled slot keeps its name: from_stream returns it unchanged. + "Capture the source itself in place of the compiled slot, or read " + "every use through one slot declared with " + "SourceNode.from_stream(source, name=...)." + if other.compiled or leaf.compiled + else "Read the source through one of them, or give the second its own " + "slot name with SourceNode.from_stream(stream, name=...)." + ) raise InconsistentSourceError( f"Slot {leaf.name!r} would be two slots with one node hash: " f"{other.described} and {leaf.described} are distinct objects. A node " "hash names one node within a pipeline (ITL-1559), and a slot holds " "one source object until source equivalence is defined (ITL-1553). " - "Read the source through one of them, or give the second its own slot " - "name with SourceNode.from_stream(stream, name=...)." + f"{remedy}" ) def _hold_captured(self, stream: StreamProtocol) -> None: @@ -723,9 +733,10 @@ def _source_node_from_recording(self, key: str) -> Any: stream = self._source_streams[key] node = self.source_node_class.from_stream(stream) if node is not stream: - # A slot a compile builds is not a declaration: another pipeline may - # capture it beside its source, as on main (ITL-1848). A slot the user - # declared (returned as it is) keeps its origin. + # A slot a compile builds is not a declaration: it has no origin to + # refuse as R-53/54. Captured beside its source in another pipeline it is + # refused as two slots with one node hash (ROWS-37-38, ITL-1848). A slot + # the user declared (returned as it is) keeps its origin. node._declared_from = None node._built_by_compile = True return node diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index 4cd31e10d..454a69d38 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -18,6 +18,7 @@ from __future__ import annotations import heapq +from contextlib import contextmanager from collections.abc import Hashable, KeysView from graphlib import CycleError, TopologicalSorter from inspect import getattr_static @@ -531,26 +532,51 @@ def add_node(self, node: NodeT, **attrs: Any) -> None: Raises: InconsistentSourceError: If another vertex already holds the node's node hash: a node hash names one node within a pipeline (ITL-1848). + RuntimeError: If called while another change of this DAG is in progress. """ - self._require_unique_node_hashes(node) - self._store_node(node, attrs) + with self._mutation("add_node"): + self._require_unique_node_hashes(node) + self._store_node(node, attrs) def add_edge(self, u: NodeT, v: NodeT) -> None: """Add an edge as ``OrcaDAG.add_edge`` does, keeping node hashes unique. Both ends are checked before either is inserted, so a refused edge leaves - the DAG as it was. The checked ends are stored directly: no check is turned - off, so an ``add_node`` that runs meanwhile is checked as any other. + the DAG as it was. Raises: InconsistentSourceError: If either end is a new vertex whose node hash another vertex already holds, or the two ends are distinct new vertices with one node hash (ITL-1848). + RuntimeError: If called while another change of this DAG is in progress. """ - self._require_unique_node_hashes(u, v) - self._store_node(u, {}) - self._store_node(v, {}) - self._store_edge(u, v) + with self._mutation("add_edge"): + self._require_unique_node_hashes(u, v) + self._store_node(u, {}) + self._store_node(v, {}) + self._store_edge(u, v) + + _mutating: bool = False + + @contextmanager + def _mutation(self, call: str) -> Iterator[None]: + """Refuse a change of this DAG made while another is in progress. + + Storing a vertex calls its ``__hash__`` and ``__eq__``; a change of the DAG + made from there (re-entrantly) is not supported, like an observer that + changes what it observes. It is refused before it writes anything. + """ + if self._mutating: + raise RuntimeError( + f"CompiledDAG.{call} was called while another change of this DAG was " + "in progress (from a vertex's __hash__ or __eq__). A compiled DAG " + "cannot be changed re-entrantly." + ) + self._mutating = True + try: + yield + finally: + self._mutating = False def _require_unique_node_hashes(self, *candidates: NodeT) -> None: """Refuse a candidate whose node hash another vertex holds now. diff --git a/tests/test_pipeline/test_compiled_dag.py b/tests/test_pipeline/test_compiled_dag.py index c0299ea85..0cfd86eeb 100644 --- a/tests/test_pipeline/test_compiled_dag.py +++ b/tests/test_pipeline/test_compiled_dag.py @@ -174,24 +174,69 @@ def __hash__(self) -> int: return object.__hash__(self) -def test_an_add_node_during_add_edge_is_checked() -> None: - # E2: inserting an edge turns no check off, so a nested add is still refused. +_REENTRANT = "was called while another change of this DAG was in progress" + + +@pytest.mark.parametrize("outer", ["add_node", "add_edge"]) +@pytest.mark.parametrize("nested", ["add_node", "add_edge"]) +@pytest.mark.parametrize("twin_of", ["held", "pending"]) +def test_a_reentrant_change_is_refused_and_the_outer_one_completes( + outer: str, nested: str, twin_of: str +) -> None: + """F1: a change made from a vertex's hash while the DAG changes is refused. + + ``pending`` is the reviewer's reentrant_pending_endpoint case: the twin shares the + node hash of the endpoint being added, which no check can see yet. + """ dag: CompiledDAG[_Vertex] = CompiledDAG() dag.add_node(_Reentrant("held", "shared")) start, end = _Reentrant("start", "x"), _Reentrant("end", "y") - duplicate = _Reentrant("duplicate", "shared") + twin = _Reentrant("twin", "shared" if twin_of == "held" else "x") inner: list[BaseException] = [] - def nested_add() -> None: + def nested_change() -> None: try: - dag.add_node(duplicate) - except InconsistentSourceError as error: + if nested == "add_node": + dag.add_node(twin) + else: + dag.add_edge(twin, _Reentrant("other", "z")) + except RuntimeError as error: inner.append(error) - start.on_hash = nested_add - dag.add_edge(start, end) - assert len(inner) == 1 - assert _refusal("held", "duplicate") in str(inner[0]) + start.on_hash = nested_change + if outer == "add_node": + dag.add_node(start) + else: + dag.add_edge(start, end) + assert len(inner) == 1 and _REENTRANT in str(inner[0]) + assert f"CompiledDAG.{nested}" in str(inner[0]) + expected = ["held", "start"] + (["end"] if outer == "add_edge" else []) + assert _labels(dag) == expected + # The guard is cleared: the next change is checked as usual. + with pytest.raises(InconsistentSourceError, match=_refusal("start", "twin2")): + dag.add_node(_Reentrant("twin2", "x")) + + +@pytest.mark.parametrize("outer", ["add_node", "add_edge"]) +def test_a_reentrant_change_that_propagates_leaves_the_dag_unchanged( + outer: str, +) -> None: + dag: CompiledDAG[_Vertex] = CompiledDAG() + dag.add_node(_Reentrant("held", "shared")) + start, end = _Reentrant("start", "x"), _Reentrant("end", "y") + + def nested_change() -> None: + dag.add_node(_Reentrant("twin", "x")) + + start.on_hash = nested_change + with pytest.raises(RuntimeError, match=_REENTRANT): + if outer == "add_node": + dag.add_node(start) + else: + dag.add_edge(start, end) + assert _labels(dag) == ["held"] + assert list(dag.edges()) == [] + dag.add_edge(start, end) # the guard is cleared assert _labels(dag) == ["held", "start", "end"] diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 5b32ef10c..9b520a077 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -507,9 +507,35 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: for number, step in enumerate(steps, start=1): outcome[f"step_{number}"] = caught(lambda: step() and None) outcome["nodes"] = caught(lambda: sorted(graph.nodes)) + if case == "compiled-implicit-slot-and-direct": + outcome["remedies"] = compiled_slot_remedies(shared) return outcome +def compiled_slot_remedies(shared: DictSource) -> dict[str, Any]: + """The two remedies the compiled-slot refusal names, each in a fresh pipeline.""" + + def source_in_its_place() -> list[str]: + graph = Pipeline("remedy_source") + with graph: + triple.pod(shared, label="direct") + double.pod(shared, label="slot") + return sorted(graph.nodes) + + def one_declared_slot() -> list[str]: + declared = SourceNode.from_stream(shared, name="b") + graph = Pipeline("remedy_slot") + with graph: + triple.pod(declared, label="direct") + double.pod(declared, label="slot") + return sorted(graph.nodes) + + return { + "source_in_its_place": caught(source_in_its_place), + "one_declared_slot": caught(one_declared_slot), + } + + def rewire_case(kind: str, receiver: str, route: str) -> dict[str, Any]: """REWIRE-87: a captured descriptor's inputs are fixed; the same ones are accepted. @@ -928,8 +954,17 @@ def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( "ROWS-37-38": "Slot 'a' would be two slots with one node hash: {held} and " "{other} are distinct objects. A node hash names one node within a pipeline " "(ITL-1559), and a slot holds one source object until source equivalence is " - "defined (ITL-1553). Read the source through one of them, or give the second " - "its own slot name with SourceNode.from_stream(stream, name=...).", + "defined (ITL-1553). {remedy}", +} + + +ROWS_37_38_REMEDIES = { + "ROWS-37-38": "Read the source through one of them, or give the second its own " + "slot name with SourceNode.from_stream(stream, name=...).", + # A compiled slot keeps its name, so the remedy names the source (F2). + "ROWS-37-38-compiled": "Capture the source itself in place of the compiled slot, " + "or read every use through one slot declared with " + "SourceNode.from_stream(source, name=...).", } @@ -943,7 +978,9 @@ def capture_refusal(code: str, order: str) -> str: held, other = slot, "source 'dict_v1:a'" if order == "reversed": held, other = other, held - return CAPTURE_REFUSALS["ROWS-37-38"].format(held=held, other=other) + return CAPTURE_REFUSALS["ROWS-37-38"].format( + held=held, other=other, remedy=ROWS_37_38_REMEDIES[code] + ) return CAPTURE_REFUSALS[code] @@ -972,6 +1009,10 @@ def test_capture_refusals_differ_from_main_as_accepted( ], code # Main accepts both captures. assert main["step_1"] == main["step_2"] == ["ok", None], (code, main) + if "remedies" in branch: + # The remedies the refusal names work, here as on main (F2). + assert branch["remedies"] == main["remedies"] + assert all(result[0] == "ok" for result in branch["remedies"].values()) # The graph keeps what the first capture recorded, as main does before it. assert branch["nodes"][0] == "ok" @@ -1003,7 +1044,9 @@ def test_rewire_87_differs_from_main_as_accepted( "renamed": CAPTURE_REFUSALS["R-MIX"].format(first="a", second="different"), "same": CAPTURE_REFUSALS["R-53/54"], "other-object": CAPTURE_REFUSALS["ROWS-37-38"].format( - held="source 'dict_v1:a'", other="declared slot 'a'" + held="source 'dict_v1:a'", + other="declared slot 'a'", + remedy=ROWS_37_38_REMEDIES["ROWS-37-38"], ), } From c39916a9e42a83425f7469ce86c2f2baa4cee12a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 13:33:05 -0800 Subject: [PATCH 09/12] test(pipeline): pin the main-compatibility gate to main 924e62f94 (ITL-1848) Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_graph_keys_main_compatibility.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 9b520a077..aea7349be 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -64,7 +64,7 @@ from orcapod.sources import DictSource ROOT = Path(__file__).resolve().parents[2] -MAIN = "2075e85e2c9418444ec5368e800f71d354fd0b5e" +MAIN = "924e62f94d481adf2ab6717494d625613b51bc43" MODES = ["sync", "async"] # One sequence per interpreter, never restarted, so every run's ids are unique. FROZEN_RUNS = count(1) From 153eb97648e43245a66421a89df3c695c21f328a Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:24:35 -0800 Subject: [PATCH 10/12] fix(pipeline): keep every declared origin; build job DAGs in bulk (ITL-1848) Address the CodeRabbit review of c39916a9e: - Declarations of one slot name and schema from several streams share a capture key; each origin is now kept, so the refusal of one object captured through a slot and directly no longer depends on which declaration came first. - as_pipeline() and PipelineJob.load check node hashes once and build the compiled DAG with the checked builder instead of a quadratic add_node loop. - Narrow the rewire wording in the changelog and docs to steps a live pipeline or job holds as captured inputs. - Gate: validate the topological order before normalizing it, require no failed rows for the loaded-job and custom-operator runs, require the bind case's save to succeed, check the graph after a refused capture and the descriptor's inputs by identity after a refused rewire, add docstrings. Co-Authored-By: Claude Opus 5.5 --- changelog.d/ITL-1848.md | 8 +- docs/concepts/pipeline-job.md | 9 +- src/orcapod/pipeline/base.py | 50 +++++-- src/orcapod/pipeline/job.py | 60 +++++++-- tests/test_pipeline/test_compiled_dag.py | 59 +++++++++ .../test_graph_keys_main_compatibility.py | 125 ++++++++++++++++-- 6 files changed, 271 insertions(+), 40 deletions(-) diff --git a/changelog.d/ITL-1848.md b/changelog.d/ITL-1848.md index 72668242f..1a098ef44 100644 --- a/changelog.d/ITL-1848.md +++ b/changelog.d/ITL-1848.md @@ -27,9 +27,11 @@ under its own slot name; for a compiled slot, which keeps its name, capture the source itself in its place, or read every use through one slot declared from the source (`SourceNode.from_stream(source, name=...)`). -- Setting a captured step's `upstreams` to other streams raises `InconsistentSourceError`; - build a new step for the new inputs (following such a change is ITL-1847). Setting the - same streams again is still accepted. +- Setting `upstreams` to other streams on a step that a live pipeline or job holds as a + captured input, or as an upstream of one, raises `InconsistentSourceError`; build a new + step for the new inputs (following such a change is ITL-1847). Setting the same streams + again is still accepted, and so is the setter of a pipeline's or job's own compiled step + (`job.nodes[label].upstreams`), as before. - Adding to a compiled DAG a node whose node hash another of its nodes holds raises `InconsistentSourceError`, as does `job.as_pipeline()` when two of the job's nodes would share one node hash. diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md index db5760d21..ef3a20ce1 100644 --- a/docs/concepts/pipeline-job.md +++ b/docs/concepts/pipeline-job.md @@ -465,10 +465,11 @@ same function pod applied to both slots. Put the conflicting steps in separate j one form in the job. Within one pipeline or job, a node hash names one node: two distinct nodes with one node -hash are refused, never told apart. A step's inputs are fixed once a pipeline or job has -captured it: setting a captured step's `upstreams` to other streams raises -`InconsistentSourceError` (following such a change is ITL-1847); build a new step for the new -inputs. The same rule holds wherever nodes reach a compiled graph: adding to `job.dag` a node +hash are refused, never told apart. A step's inputs are fixed while a live pipeline or job +holds it as a captured input, or as an upstream of one: setting its `upstreams` to other +streams raises `InconsistentSourceError` (following such a change is ITL-1847); build a new +step for the new inputs. The setter of a pipeline's or job's own compiled step +(`job.nodes[label].upstreams`) still works as before. The same rule holds wherever nodes reach a compiled graph: adding to `job.dag` a node whose node hash another of its nodes holds, `job.as_pipeline()` of a job whose steps would give two nodes one node hash, and loading a saved file in which two distinct nodes share one node hash all raise `InconsistentSourceError`. diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 6824c80a6..6046528cd 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -232,8 +232,10 @@ def __init__( self._graph_key_of: dict[str, str] = {} # capture key -> graph key self._capture_key_of: dict[str, str] = {} # graph key -> capture key self._pinned_slot_names: dict[str, str] = {} # capture key -> slot name - # Leaves recorded so far, by capture key, checked at each new capture. - self._capture_leaves: dict[str, CaptureLeaf] = {} + # Leaves recorded so far, by capture key, checked at each new capture. A + # key holds one leaf per origin: declarations of one slot from several + # streams share the key, and each origin is kept. + self._capture_leaves: dict[str, list[CaptureLeaf]] = {} # ------------------------------------------------------------------ # Properties @@ -487,9 +489,10 @@ def _commit_capture_leaves( leaves: Leaves ``_new_capture_leaves`` admitted. streams: Capture key and stream of each input, leaves among them. """ - admitted = {leaf.capture_key: leaf for leaf in leaves} - self._capture_leaves.update(admitted) - new_keys = admitted.keys() + new_keys: set[str] = set() + for leaf in leaves: + self._capture_leaves.setdefault(leaf.capture_key, []).append(leaf) + new_keys.add(leaf.capture_key) held: set[str] = set() for input_key, stream in streams: if input_key in new_keys and input_key not in held: @@ -511,24 +514,51 @@ def _new_capture_leaves( and 38: a node hash is unique within a pipeline). Two sources sharing one slot name are left to main's own refusals. + A known capture key is skipped, except a declaration from a stream no leaf + of that key was declared from: declarations of one slot name and schema + share their key, and each origin is kept, so the refusal of one object + captured both ways does not depend on which declaration came first. + Raises: InconsistentSourceError: Naming the slot and both leaves. """ staged: list[CaptureLeaf] = [] for stream, key in zip(inputs, input_keys, strict=True): + same_key = [ + *self._capture_leaves.get(key, ()), + *(leaf for leaf in staged if leaf.capture_key == key), + ] if ( - key in self._invocation_lut - or key in self._source_streams - or any(leaf.capture_key == key for leaf in staged) - ): + same_key or key in self._invocation_lut or key in self._source_streams + ) and not self._declared_from_new_origin(stream, same_key): continue leaf = self._describe_capture_leaf(stream, key) - known = [*self._capture_leaves.values(), *staged] + known = [ + *chain.from_iterable(self._capture_leaves.values()), + *staged, + ] self._refuse_one_object_twice(leaf, known) self._refuse_shared_node_hash(leaf, known) staged.append(leaf) return staged + @staticmethod + def _declared_from_new_origin( + stream: StreamProtocol, same_key: list[CaptureLeaf] + ) -> bool: + """Whether ``stream`` declares a known slot from a stream no leaf names.""" + from orcapod.core.nodes.source_node import SourceNode + + if not isinstance(stream, SourceNode): + return False + declared_from = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from + origin = declared_from() if declared_from is not None else None + if origin is None: + return False + return not any( + leaf.leaf is not None and leaf.leaf() is origin for leaf in same_key + ) + def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLeaf: """Describe a new leaf: the slot name and node hash compiling will give it.""" from orcapod.core.nodes.source_node import ( diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index e976a25c3..408772f7d 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 Callable, Iterable, Iterator, Sequence +from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence from copy import deepcopy from dataclasses import dataclass from itertools import chain @@ -38,6 +38,7 @@ from orcapod.pipeline.dag import CompiledDAG, OrcaDAG from orcapod.pipeline.graph_keys import ( compiled_graph_key, + defined_node_hash, is_legacy_graph_key, legacy_graph_key, shared_graph_keys, @@ -81,7 +82,6 @@ from orcapod.utils.schema_utils import ReservedColumnNameError if TYPE_CHECKING: - from collections.abc import Mapping from pathlib import Path from types import FrameType @@ -1169,11 +1169,13 @@ def as_pipeline(self) -> "Pipeline": # Build _node_graph (OrcaDAG with node objects as vertices). # node_map here contains GraphNode objects (blueprint nodes). - bp_dag: OrcaDAG = CompiledDAG() - for node in pipeline._persistent_node_map.values(): - bp_dag.add_node(node) - for up_h, down_h in new_graph_edges: - bp_dag.add_edge(new_node_map[up_h], new_node_map[down_h]) + bp_dag: OrcaDAG = _checked_compiled_dag( + pipeline._persistent_node_map, + ( + (new_node_map[up_h], new_node_map[down_h]) + for up_h, down_h in new_graph_edges + ), + ) pipeline._node_graph = bp_dag # The blueprint's graph keys (ITL-1848): each node's node hash, or its @@ -2704,16 +2706,18 @@ def load( # 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._publish_graph_keys(pipeline._graph_key_of) # pyright: ignore[reportPrivateUsage] # the loaded pipeline's graph keys - job_dag: OrcaDAG = CompiledDAG() 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) - 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) - if u_node is not None and v_node is not None: - job_dag.add_edge(u_node, v_node) + persistent = job._persistent_node_map + job_dag: OrcaDAG = _checked_compiled_dag( + persistent, + ( + (persistent[u_hash], persistent[v_hash]) + for u_hash, v_hash in job._graph_edges + if u_hash in persistent and v_hash in persistent + ), + ) job._node_graph = job_dag if effective_database is not None: @@ -2727,3 +2731,31 @@ def load( job._run_id = run_id return job + + +def _checked_compiled_dag( + nodes: Mapping[str, Any], edges: Iterable[tuple[Any, Any]] +) -> CompiledDAG[Any]: + """A compiled DAG of *nodes*, their node hashes checked once (ITL-1848). + + Reads each node's node hash once, refuses two distinct nodes with one node hash + before anything is built, then builds the DAG without reading them again (a + vertex-by-vertex ``add_node`` reads every held vertex's node hash each time). + + Args: + nodes: The vertices by key, in insertion order. + edges: The edges, as pairs of vertices among *nodes*. + + Raises: + InconsistentSourceError: If two distinct nodes share one node hash. + """ + unique: dict[str, Any] = {} + seen: set[int] = set() + for key, node in nodes.items(): + if id(node) not in seen: + seen.add(id(node)) + unique[key] = node + PipelineJob._require_one_node_per_graph_key( # pyright: ignore[reportPrivateUsage] # the one uniqueness rule + unique, {key: defined_node_hash(node) for key, node in unique.items()} + ) + return CompiledDAG._from_checked(unique.values(), edges) # pyright: ignore[reportPrivateUsage] # node hashes checked just above diff --git a/tests/test_pipeline/test_compiled_dag.py b/tests/test_pipeline/test_compiled_dag.py index 0cfd86eeb..f05dea24d 100644 --- a/tests/test_pipeline/test_compiled_dag.py +++ b/tests/test_pipeline/test_compiled_dag.py @@ -291,3 +291,62 @@ def built(nodes: Any, edges: Any) -> Any: Pipeline.load(path) assert calls and calls[-1] == "build" assert "check" in calls[: calls.index("build")] + + +def test_job_dags_are_built_in_bulk(tmp_path: Path) -> None: + """A job's blueprint and a loaded job build their DAGs with one check. + + CodeRabbit on PR 695: inserting vertex by vertex reads every held vertex's node + hash at each insertion, which is quadratic in the number of nodes. + """ + from orcapod import PipelineJob, function_pod + from orcapod.databases import InMemoryArrowDatabase + from orcapod.pipeline.job import PipelineJob as JobClass + from orcapod.sources import DictSource + + @function_pod(output_keys="doubled") + def double(x: int) -> int: + return 2 * x + + @function_pod(output_keys="tripled") + def triple(x: int) -> int: + return 3 * x + + database = InMemoryArrowDatabase() + job = PipelineJob("bulk", database=database) + with job: + for name in ("a", "b"): + data = DictSource( + [{"id": 1, "x": 1}, {"id": 2, "x": 2}], + source_id=name, + tag_columns=["id"], + tag_only_columns=True, + ) + double.pod(data, label=f"double_{name}") + triple.pod(data, label=f"triple_{name}") + path = tmp_path / "job.json" + checks: list[int] = [] + check = JobClass._require_one_node_per_graph_key # pyright: ignore[reportPrivateUsage] # counted below + + def counted(nodes: Any, keys: Any) -> None: + checks.append(len(nodes)) + check(nodes, keys) + + refuse = AssertionError("a job DAG was built vertex by vertex") + with ( + patch.object(CompiledDAG, "add_node", side_effect=refuse), + patch.object(CompiledDAG, "add_edge", side_effect=refuse), + patch.object( + JobClass, "_require_one_node_per_graph_key", staticmethod(counted) + ), + ): + blueprint = job.pipeline + job.save(path) + loaded = PipelineJob.load(path, database=database) + assert sorted(node.label for node in blueprint.dag.nodes()) == sorted( + blueprint.nodes + ) + assert sorted(node.label for node in loaded.dag.nodes()) == sorted(loaded.nodes) + assert len(list(loaded.dag.edges())) == len(list(job.dag.edges())) + # Every DAG built was checked as a whole, once per build. + assert checks and all(count == len(job.nodes) for count in checks) diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index aea7349be..8b88808b5 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -126,6 +126,8 @@ def source(name: str, base: int, *, column: str = "x") -> DictSource: class FrozenClock(datetime): + """A clock fixed at 2026-01-01 UTC, so stored times compare.""" + @classmethod @override def now(cls, tz: tzinfo | None = None) -> datetime: @@ -163,6 +165,20 @@ def rows(graph: Pipeline | PipelineJob) -> dict[str, Any]: return result +def topological(dag: Any) -> list[str]: + """The DAG's topological order, checked, then normalized for comparison. + + Every vertex appears once and every edge points forward in the traversal itself; + the labels are then sorted, since independent nodes may come in any valid order. + """ + order = list(dag.topological_sort()) + position = {id(node): number for number, node in enumerate(order)} + assert len(position) == len(order) == len(list(dag.nodes())), "a vertex repeated" + for up, down in dag.edges(): + assert position[id(up)] < position[id(down)], (up.label, down.label) + return sorted(node.label for node in order) + + def listing(graph: Pipeline | PipelineJob) -> dict[str, Any]: """The public shape of a compiled graph, by label.""" dag = graph.dag @@ -171,9 +187,7 @@ def listing(graph: Pipeline | PipelineJob) -> dict[str, Any]: "kinds": {label: node.node_type for label, node in sorted(graph.nodes.items())}, "dag_nodes": sorted(node.label for node in dag.nodes()), "edges": sorted([up.label, down.label] for up, down in dag.edges()), - "topological": [node.label for node in dag.topological_sort()] - if len(graph.nodes) < 2 - else sorted(node.label for node in dag.topological_sort()), + "topological": topological(dag), "pipeline_hashes": { label: node.pipeline_hash().to_string() for label, node in sorted(graph.nodes.items()) @@ -184,6 +198,7 @@ def listing(graph: Pipeline | PipelineJob) -> dict[str, Any]: def saved(job: PipelineJob, path: Path) -> str: + """The job's saved file, with the library version pinned so bytes compare.""" with patch("orcapod.__version__", "0.4.0"): job.save(path) return path.read_text() @@ -243,6 +258,7 @@ def frozen_run(job: PipelineJob, mode: str) -> dict[str, Any]: def stored_tables(path: Path) -> dict[str, Any]: + """Every Delta table under *path*: its schema and its rows, sorted.""" tables = {} for log in sorted(path.rglob("_delta_log")): table = DeltaTable(str(log.parent)).to_pyarrow_table() @@ -285,7 +301,7 @@ def lifecycle_case(directory: Path, mode: str) -> dict[str, Any]: for label, node in sorted(loaded.nodes.items()) if node.node_type != "source" } - run(loaded, mode, load_only=True) + outcome["loaded_summary"] = run(loaded, mode, load_only=True) outcome["loaded_rows"] = rows(loaded) with patch("orcapod.__version__", "0.4.0"): job.pipeline.save(directory / "pipeline.json") @@ -387,11 +403,20 @@ class CommutativeJoin(Join): class OrderedJoin(Join): + """A custom operator that keeps its inputs in argument order.""" + def argument_symmetry(self, streams: Any) -> Any: return tuple(streams) def custom_operator_case(directory: Path, kind: str, mode: str) -> dict[str, Any]: + """Two custom joins without a node hash, captured, run and read. + + Args: + directory: Unused; every case takes its working directory. + kind: ``commutative`` or ``ordered`` (a custom argument symmetry). + mode: ``sync`` or ``async``. + """ operator_class = {"commutative": CommutativeJoin, "ordered": OrderedJoin}[kind] job = PipelineJob("custom", database=InMemoryArrowDatabase()) with job: @@ -411,7 +436,7 @@ def custom_operator_case(directory: Path, kind: str, mode: str) -> dict[str, Any label: caught(lambda label=label: job.nodes[label].node_hash()) for label in ("ab", "ab_total") } - run(job, mode) + outcome["summary"] = run(job, mode) outcome["rows"] = rows(job) return outcome @@ -512,6 +537,39 @@ def capture_case(case: str, receiver: str, order: str) -> dict[str, Any]: return outcome +def two_declarations_case(receiver: str, order: str) -> dict[str, Any]: + """R-MIX after two declarations of one slot from two streams, in either order. + + Two declarations of slot ``alias`` with one schema share a capture key: the + second adds no step of its own. Each origin is kept, so the later direct capture + of either origin is refused whichever declaration came first (CodeRabbit on PR + 695: only the first origin was kept). + """ + graph = ( + PipelineJob("declarations", database=InMemoryArrowDatabase()) + if receiver == "job" + else Pipeline("declarations") + ) + shared, other = source("a", 3), source("other", 8) + declarations = [ + SourceNode.from_stream(other, name="alias"), + SourceNode.from_stream(shared, name="alias"), + ] + if order == "shared-first": + declarations.reverse() + steps = [ + lambda: double.pod(declarations[0], label="first"), + lambda: triple.pod(declarations[1], label="second"), + lambda: double.pod(shared, label="direct"), + ] + outcome: dict[str, Any] = {} + with graph: + for number, step in enumerate(steps, start=1): + outcome[f"step_{number}"] = caught(lambda: step() and None) + outcome["nodes"] = caught(lambda: sorted(graph.nodes)) + return outcome + + def compiled_slot_remedies(shared: DictSource) -> dict[str, Any]: """The two remedies the compiled-slot refusal names, each in a fresh pipeline.""" @@ -593,12 +651,18 @@ def recompile() -> list[str]: graph.compile() return sorted(graph.nodes) - return { + outcome = { "same": caught(lambda: set_upstreams(inputs)), "same_compile": caught(recompile), "other": caught(lambda: set_upstreams(replacement)), - "other_compile": caught(recompile), } + # Read right after the setter: the descriptor holds its first inputs, by identity. + kept = tuple(descriptor.upstreams) + outcome["inputs_kept"] = len(kept) == len(inputs) and all( + now is before for now, before in zip(kept, inputs, strict=True) + ) + outcome["other_compile"] = caught(recompile) + return outcome def imported_mixed_case(receiver: str, case: str = "renamed") -> dict[str, Any]: @@ -813,6 +877,15 @@ def require_no_write_failure(outcome: dict[str, Any]) -> None: def dispatch(args: list[str]) -> Any: + """Run one case in this interpreter. + + Args: + args: The case name, then its arguments as text, in the order its function + takes them (``lifecycle`` and ``bind``: directory, mode, arrangement). + + Returns: + The case's outcome, written as JSON by the worker for comparison. + """ name, rest = args[0], args[1:] if name in ("lifecycle", "bind"): CASE_SETTINGS["arrangement"] = rest[2] @@ -824,6 +897,8 @@ def dispatch(args: list[str]) -> Any: return membership_case(rest[0]) if name == "capture": return capture_case(rest[0], rest[1], rest[2]) + if name == "two-declarations": + return two_declarations_case(rest[0], rest[1]) if name == "rewire": return rewire_case(rest[0], rest[1], rest[2]) if name == "imported-mixed": @@ -840,6 +915,7 @@ def dispatch(args: list[str]) -> Any: def no_failed_rows(summary: dict[str, list[int]]) -> bool: + """Whether no node of a run summary (``run``'s counts) reports a failed row.""" return all(counts[2] == 0 for counts in summary.values()) @@ -857,6 +933,7 @@ def test_lifecycle_rows_stores_and_saved_bytes_match_main( for row in map(eval, branch["rows"]["double_a"]) ) == [(1, "p", 6), (2, "q", 8)] assert no_failed_rows(branch["summary"]) + assert no_failed_rows(branch["loaded_summary"]) assert branch["recompiled"]["dag_is_orca_dag"] is True require_no_write_failure(branch) assert branch == probe(main_package, *args, cwd=tmp_path / "main") @@ -886,6 +963,8 @@ def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( for row in map(eval, branch["rebind"][-1][1]["rows"]["left_doubled"]) ) == [(1, "p", 60), (2, "q", 62)] assert branch["own_node"][0] == "SourceSpecMismatchError" + # The saved bytes are compared, never two equal save errors. + assert branch["saved"][0] == "ok", branch["saved"] require_no_write_failure(branch) assert branch == probe(main_package, *args, cwd=tmp_path / "main") @@ -898,6 +977,7 @@ def test_custom_operators_keep_main_nodes_and_rows( branch, main = both(main_package, "custom", str(tmp_path), kind, mode) if kind == "ordered": assert {"ab_total", "ba_total"} <= set(branch["listing"]["labels"]) + assert no_failed_rows(branch["summary"]) # S1: main's exact ValueError, never another error type. assert {error[0] for error in branch["node_hash"].values()} == {"ValueError"} require_no_write_failure(branch) @@ -1013,8 +1093,33 @@ def test_capture_refusals_differ_from_main_as_accepted( # The remedies the refusal names work, here as on main (F2). assert branch["remedies"] == main["remedies"] assert all(result[0] == "ok" for result in branch["remedies"].values()) - # The graph keeps what the first capture recorded, as main does before it. + # The graph keeps what the first capture recorded and nothing of the refused one. + first = "slot" if order == "forward" else "direct" assert branch["nodes"][0] == "ok" + assert first in branch["nodes"][1] and second not in branch["nodes"][1] + + +@pytest.mark.parametrize("order", ["other-first", "shared-first"]) +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +def test_every_declared_origin_is_kept_for_the_r_mix_refusal( + main_package: Path, receiver: str, order: str +) -> None: + """The refusal does not depend on which of two declarations came first.""" + branch, main = both(main_package, "two-declarations", receiver, order) + for side in (branch, main): + assert side["step_1"] == side["step_2"] == ["ok", None] + assert branch["step_3"] == [ + "InconsistentSourceError", + "While capturing step 'direct': " + + CAPTURE_REFUSALS["R-MIX"].format(first="alias", second="a"), + ] + # Main accepts the direct capture. + assert main["step_3"] == ["ok", None] + assert branch["nodes"][0] == main["nodes"][0] == "ok" + assert {"alias", "first", "second"} <= set(branch["nodes"][1]) + # Auto-select labels are numbered by how many there are, so compare the rest. + assert {"a", "direct"} <= set(main["nodes"][1]) + assert not {"a", "direct"} & set(branch["nodes"][1]) @pytest.mark.parametrize("route", ["capture", "import"]) @@ -1036,7 +1141,9 @@ def test_rewire_87_differs_from_main_as_accepted( "input is ITL-1847.", ] assert main["other"] == ["ok", None] - # Refused, the step keeps its inputs: the graph compiles as before. + # Refused, the step keeps its inputs, the same objects, and compiles as before. + assert branch["inputs_kept"] is True + assert main["inputs_kept"] is False assert branch["other_compile"] == branch["same_compile"] From c4df24f722f20feb93362eaf6f65787ca2c06435 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 14:39:16 -0800 Subject: [PATCH 11/12] fix(pipeline): drop dead declared origins from capture records (ITL-1848) A capture key kept one record per declared origin and never dropped one whose origin had died, so temporary declarations of one slot grew the records for the life of the graph. Each declared origin is now referenced with a callback that prunes its key when it dies, and appending prunes too: a key holds one record per live origin, or one record of the slot. Also give every function in the main-compatibility gate a docstring, and say that the second of two same-named declarations adds no slot. Co-Authored-By: Claude Opus 5.5 --- src/orcapod/pipeline/base.py | 36 +++++++- tests/test_pipeline/test_capture_leaves.py | 92 +++++++++++++++++++ .../test_graph_keys_main_compatibility.py | 40 +++++++- 3 files changed, 166 insertions(+), 2 deletions(-) create mode 100644 tests/test_pipeline/test_capture_leaves.py diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 6046528cd..5eea5144e 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -492,6 +492,7 @@ def _commit_capture_leaves( new_keys: set[str] = set() for leaf in leaves: self._capture_leaves.setdefault(leaf.capture_key, []).append(leaf) + self._prune_capture_leaves(leaf.capture_key) new_keys.add(leaf.capture_key) held: set[str] = set() for input_key, stream in streams: @@ -503,6 +504,37 @@ def _commit_capture_leaves( # Capture leaves (ITL-1848) # ------------------------------------------------------------------ + def _prune_capture_leaves(self, key: str) -> None: + """Drop the leaves of *key* whose declared origin has died. + + Every leaf of one capture key describes one slot (one name and schema), so + the first is kept when none is alive: the structural checks still see the + slot. A key holds at most one leaf per live origin, or one leaf. + """ + leaves = self._capture_leaves.get(key) + if leaves is None or len(leaves) < 2: + return + # A leaf with no reference names no live object (its origin was gone at + # capture, or it cannot be referenced weakly): it is kept only as the first. + live = [ + leaf for leaf in leaves if leaf.leaf is not None and leaf.leaf() is not None + ] + if len(live) < len(leaves): + self._capture_leaves[key] = live or leaves[:1] + + def _origin_ref( + self, origin: StreamProtocol, key: str + ) -> ReferenceType[StreamProtocol]: + """A weak reference to a declared origin that prunes *key* when it dies.""" + owner = ref(self) + + def prune(_dead: ReferenceType[StreamProtocol]) -> None: + graph = owner() + if graph is not None: + graph._prune_capture_leaves(key) + + return ref(origin, prune) + def _new_capture_leaves( self, inputs: tuple[StreamProtocol, ...], input_keys: tuple[str, ...] ) -> list[CaptureLeaf]: @@ -576,7 +608,9 @@ def _describe_capture_leaf(self, stream: StreamProtocol, key: str) -> CaptureLea described = ( f"compiled slot {name!r}" if compiled else f"declared slot {name!r}" ) - leaf = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from + declared_from = stream._declared_from # pyright: ignore[reportPrivateUsage] # the stream the slot was declared from + origin = declared_from() if declared_from is not None else None + leaf = self._origin_ref(origin, key) if origin is not None else None else: name = slot_name_for(stream, ContentHash.from_string(key)) if isinstance(stream, RootSource): diff --git a/tests/test_pipeline/test_capture_leaves.py b/tests/test_pipeline/test_capture_leaves.py new file mode 100644 index 000000000..a2b12c4e1 --- /dev/null +++ b/tests/test_pipeline/test_capture_leaves.py @@ -0,0 +1,92 @@ +"""A pipeline keeps the origins of its declared slots while they live (ITL-1848). + +Declarations of one slot name and schema from several streams share a capture key, and +each declared origin is kept so the refusal of one object captured both through a slot +and directly does not depend on declaration order. An origin that dies is dropped: the +records stay bounded by the live origins. +""" + +from __future__ import annotations + +import gc + +import pytest + +from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.identity_chains import graph_hash +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import InconsistentSourceError +from orcapod.sources import DictSource + + +@function_pod(output_keys="doubled") +def double(x: int) -> int: + return 2 * x + + +def _source(name: str, base: int) -> DictSource: + return DictSource( + [ + {"id": 1, "part": "p", "x": base, "x_note": "n"}, + {"id": 2, "part": "q", "x": base + 1, "x_note": "m"}, + ], + source_id=name, + tag_columns=["id", "part"], + tag_only_columns=True, + ) + + +def _graph(receiver: str) -> Pipeline | PipelineJob: + if receiver == "job": + return PipelineJob( + "leaves", database=InMemoryArrowDatabase(), auto_compile=False + ) + return Pipeline("leaves", auto_compile=False) + + +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +def test_dead_declared_origins_are_dropped(receiver: str) -> None: + """Delta review 4 on PR 695: 128 temporary declarations left 128 dead records.""" + graph = _graph(receiver) + key = graph_hash(SourceNode.from_stream(_source("probe", 0), name="alias")) + + def capture(number: int) -> None: + slot = SourceNode.from_stream(_source(f"origin_{number}", number), name="alias") + assert graph_hash(slot) == key + double.pod(slot, label="same") + + with graph: + for number in range(128): + capture(number) + gc.collect() + leaves = graph._capture_leaves[key.to_string()] # pyright: ignore[reportPrivateUsage] # the records under test + # No origin is alive: one record of the slot is kept, for the structural checks. + assert len(leaves) == 1 + + +@pytest.mark.parametrize("receiver", ["pipeline", "job"]) +def test_a_live_origin_is_still_refused_after_dead_ones_are_dropped( + receiver: str, +) -> None: + graph = _graph(receiver) + kept = _source("a", 3) + with graph: + for number in range(8): + double.pod( + SourceNode.from_stream( + _source(f"origin_{number}", number), name="alias" + ), + label="same", + ) + double.pod(SourceNode.from_stream(kept, name="alias"), label="same") + gc.collect() + key = graph_hash(SourceNode.from_stream(kept, name="alias")).to_string() + leaves = graph._capture_leaves[key] # pyright: ignore[reportPrivateUsage] # the records under test + # Records of live origins only: the kept source's among them, no dead one. + origins = [leaf.leaf() if leaf.leaf is not None else None for leaf in leaves] + assert None not in origins + assert any(origin is kept for origin in origins) + assert len(leaves) == 1 + with pytest.raises(InconsistentSourceError, match="would be read by slots"): + with graph: + double.pod(kept, label="direct") diff --git a/tests/test_pipeline/test_graph_keys_main_compatibility.py b/tests/test_pipeline/test_graph_keys_main_compatibility.py index 8b88808b5..56982748f 100644 --- a/tests/test_pipeline/test_graph_keys_main_compatibility.py +++ b/tests/test_pipeline/test_graph_keys_main_compatibility.py @@ -75,21 +75,25 @@ @function_pod(output_keys="doubled") def double(x: int) -> int: + """Double ``x``.""" return 2 * x @function_pod(output_keys="tripled") def triple(x: int) -> int: + """Triple ``x``.""" return 3 * x @function_pod(output_keys="plus") def plus_one(doubled: int) -> int: + """Add one to ``doubled``.""" return doubled + 1 @function_pod(output_keys="total") def total(x: int, y: int) -> int: + """Add ``x`` and ``y``.""" return x + y @@ -131,6 +135,7 @@ class FrozenClock(datetime): @classmethod @override def now(cls, tz: tzinfo | None = None) -> datetime: + """The fixed time, in *tz*.""" return cls(2026, 1, 1, tzinfo=timezone.utc).astimezone(tz) @@ -214,6 +219,7 @@ class _ResultIds: """ def __init__(self) -> None: + """Start a run's id sequence.""" self.run = next(FROZEN_RUNS) self.seen: Counter[str] = Counter() self.lock = threading.Lock() @@ -221,6 +227,7 @@ def __init__(self) -> None: self.build = PythonDataFunction._build_output_data # pyright: ignore[reportPrivateUsage] # wrapped to know the output def build_output_data(self, function: Any, values: Any) -> Any: + """Build a function's output, noting what it is for ``uuid7``.""" self.current.key = f"{function.uri}|{values!r}" try: return self.build(function, values) @@ -228,6 +235,7 @@ def build_output_data(self, function: Any, values: Any) -> Any: self.current.key = None def uuid7(self) -> UUID: + """An id from the current output and its occurrence.""" key = getattr(self.current, "key", None) assert key is not None, "a result id outside a function's output" with self.lock: @@ -323,6 +331,7 @@ def bind_case(directory: Path, mode: str) -> dict[str, Any]: steps: dict[str, Any] = {} def state() -> dict[str, Any]: + """The job's bindings and which nodes can run.""" return { "sources": { name: getattr(bound, "source_id", None) @@ -333,9 +342,11 @@ def state() -> dict[str, Any]: } def run_and_read() -> dict[str, Any]: + """Run the job and read every node's rows.""" return {"summary": frozen_run(job, mode), "rows": rows(job)} def recompile() -> list[str]: + """Compile again; the compiled labels.""" job.compile() return sorted(node.label for node in job.dag.nodes()) @@ -345,6 +356,7 @@ def recompile() -> list[str]: steps["rebind"] += [state(), caught(recompile), caught(run_and_read)] def capture_after_rebind() -> None: + """Capture a new step after a rebind.""" with job: double.pod(source("late", 1), label="late") @@ -358,6 +370,7 @@ def capture_after_rebind() -> None: steps["run_unbound"] = caught(run_and_read) def setter() -> None: + """Bind the slot through its ``bound_source`` setter.""" job.nodes["right"].bound_source = second # pyright: ignore[reportAttributeAccessIssue] # a source slot steps["setter"] = [caught(setter), state(), caught(recompile), caught(run_and_read)] @@ -382,6 +395,7 @@ def setter() -> None: double.pod(SourceNode.from_stream(source("o", 7), name="slot"), label="o") def foreign_slot() -> None: + """Capture another job's slot.""" with job: triple.pod(other.nodes["slot"], label="foreign") @@ -389,6 +403,7 @@ def foreign_slot() -> None: prebuilt = triple.pod(job.nodes["left"]) def prebuilt_over_own_slot() -> None: + """Capture a stream built over the job's own slot.""" with job: double.pod(SelectDataColumns(["tripled"])(prebuilt), label="prebuilt") @@ -406,6 +421,7 @@ class OrderedJoin(Join): """A custom operator that keeps its inputs in argument order.""" def argument_symmetry(self, streams: Any) -> Any: + """The inputs in argument order.""" return tuple(streams) @@ -450,6 +466,7 @@ def membership_case(receiver: str) -> dict[str, Any]: """R-IN and R-GRAPH.""" def build() -> Pipeline | PipelineJob: + """A pipeline or job of one function step.""" graph = ( PipelineJob("members", database=InMemoryArrowDatabase()) if receiver == "job" @@ -541,7 +558,7 @@ def two_declarations_case(receiver: str, order: str) -> dict[str, Any]: """R-MIX after two declarations of one slot from two streams, in either order. Two declarations of slot ``alias`` with one schema share a capture key: the - second adds no step of its own. Each origin is kept, so the later direct capture + second adds no slot of its own (a second step reads it). Each origin is kept, so the later direct capture of either origin is refused whichever declaration came first (CodeRabbit on PR 695: only the first origin was kept). """ @@ -574,6 +591,7 @@ def compiled_slot_remedies(shared: DictSource) -> dict[str, Any]: """The two remedies the compiled-slot refusal names, each in a fresh pipeline.""" def source_in_its_place() -> list[str]: + """Capture the source itself where the compiled slot was.""" graph = Pipeline("remedy_source") with graph: triple.pod(shared, label="direct") @@ -581,6 +599,7 @@ def source_in_its_place() -> list[str]: return sorted(graph.nodes) def one_declared_slot() -> list[str]: + """Read every use through one declared slot.""" declared = SourceNode.from_stream(shared, name="b") graph = Pipeline("remedy_slot") with graph: @@ -645,9 +664,11 @@ def rewire_case(kind: str, receiver: str, route: str) -> dict[str, Any]: inputs = tuple(descriptor.upstreams) def set_upstreams(value: tuple[Any, ...]) -> None: + """Set the descriptor's inputs.""" descriptor.upstreams = value def recompile() -> list[str]: + """Compile again; the compiled labels.""" graph.compile() return sorted(graph.nodes) @@ -676,6 +697,7 @@ def imported_mixed_case(receiver: str, case: str = "renamed") -> dict[str, Any]: def narrow(base: int) -> DictSource: # One data column: an invocation reads exactly its function's parameters. + """A source with one data column.""" return DictSource( [{"id": 1, "x": base}, {"id": 2, "x": base + 1}], source_id="a", @@ -788,6 +810,7 @@ def projection_duplicate_case() -> dict[str, Any]: ) def project() -> dict[str, Any]: + """Project the job to a pipeline.""" blueprint = job.as_pipeline() return { "nodes": sorted(blueprint.nodes), @@ -813,6 +836,7 @@ def shared_node_hash_file(path: Path) -> dict[str, Any]: triple.pod(source("a", 3), label="direct") def save() -> list[str]: + """Save the pipeline with the version pinned.""" with patch("orcapod.__version__", "0.4.0"): pipeline.save(path) return sorted(pipeline.nodes) @@ -924,6 +948,7 @@ def no_failed_rows(summary: dict[str, list[int]]) -> bool: def test_lifecycle_rows_stores_and_saved_bytes_match_main( main_package: Path, tmp_path: Path, mode: str, arrangement: str ) -> None: + """Capture, run, store, save and load give main's outcome exactly, with no failed row.""" (tmp_path / "branch").mkdir() (tmp_path / "main").mkdir() args = ("lifecycle", "work", mode, arrangement) @@ -944,6 +969,7 @@ def test_lifecycle_rows_stores_and_saved_bytes_match_main( def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( main_package: Path, tmp_path: Path, mode: str, arrangement: str ) -> None: + """Every bind step recompiles, runs and saves as on main, and refuses as main does.""" (tmp_path / "branch").mkdir() (tmp_path / "main").mkdir() args = ("bind", "work", mode, arrangement) @@ -974,6 +1000,7 @@ def test_bind_rebind_unbind_and_itl_1469_refusals_match_main( def test_custom_operators_keep_main_nodes_and_rows( main_package: Path, tmp_path: Path, kind: str, mode: str ) -> None: + """Custom operators keep main's nodes, rows and ``node_hash`` error, with no failed row.""" branch, main = both(main_package, "custom", str(tmp_path), kind, mode) if kind == "ordered": assert {"ab_total", "ba_total"} <= set(branch["listing"]["labels"]) @@ -988,6 +1015,7 @@ def test_custom_operators_keep_main_nodes_and_rows( def test_r_in_and_r_graph_membership_differs_from_main_as_accepted( main_package: Path, receiver: str ) -> None: + """Membership and the ``graph`` attribute differ from main only as R-IN and R-GRAPH.""" branch, main = both(main_package, "membership", receiver) refused = [ "UndefinedGraphMembershipError", @@ -1080,6 +1108,7 @@ def capture_refusal(code: str, order: str) -> str: def test_capture_refusals_differ_from_main_as_accepted( main_package: Path, case: str, code: str, receiver: str, order: str ) -> None: + """The second capture is refused with its code's exact text; main accepts both.""" branch, main = both(main_package, "capture", case, receiver, order) second = "direct" if order == "forward" else "slot" assert branch["step_1"] == ["ok", None] @@ -1128,6 +1157,7 @@ def test_every_declared_origin_is_kept_for_the_r_mix_refusal( def test_rewire_87_differs_from_main_as_accepted( main_package: Path, kind: str, receiver: str, route: str ) -> None: + """Rewiring a captured descriptor is refused at the setter and leaves its inputs.""" branch, main = both(main_package, "rewire", kind, receiver, route) # The same inputs again: accepted, as main, and the graph compiles. assert branch["same"] == main["same"] == ["ok", None] @@ -1166,6 +1196,7 @@ def test_rewire_87_differs_from_main_as_accepted( def test_capture_refusals_through_from_invocations_differ_from_main_as_accepted( main_package: Path, receiver: str, case: str, code: str ) -> None: + """An imported graph is refused as a direct capture is; main imports it.""" branch, main = both(main_package, "imported-mixed", receiver, case) # An imported graph is checked as a direct capture is (B3). assert branch["import"] == ["InconsistentSourceError", IMPORT_REFUSALS[case]], code @@ -1178,6 +1209,7 @@ def test_capture_refusals_through_from_invocations_differ_from_main_as_accepted( def test_dag_dup_differs_from_main_as_accepted(main_package: Path) -> None: + """A compiled DAG refuses a second node with a held node hash; main adds it.""" branch, main = both(main_package, "dag-dup") refused = [ "InconsistentSourceError", @@ -1195,6 +1227,7 @@ def test_dag_dup_differs_from_main_as_accepted(main_package: Path) -> None: assert sorted(set(main["dag_nodes"])) == sorted(branch["dag_nodes"]) def refusal(held: str, other: str) -> list[str]: + """The DAG-DUP refusal naming *held* and *other*.""" return [ refused[0], refused[1].replace("'d' and 'd'", f"{held!r} and {other!r}"), @@ -1223,6 +1256,7 @@ def refusal(held: str, other: str) -> list[str]: def test_project_dup_differs_from_main_as_accepted(main_package: Path) -> None: + """``as_pipeline()`` refuses two nodes with one node hash; main collapses them.""" branch, main = both(main_package, "project-dup") # The compiled step's setter stays as main (Q-B). assert branch["setter"] == main["setter"] == ["ok", None] @@ -1242,6 +1276,7 @@ def test_project_dup_differs_from_main_as_accepted(main_package: Path) -> None: def test_load_dup_refuses_a_file_main_writes_with_two_nodes_of_one_hash( main_package: Path, tmp_path: Path ) -> None: + """A file main writes with two nodes of one node hash is refused on load.""" path = tmp_path / "dup.json" written = probe(main_package, "save-dup", str(path)) assert written["saved"][0] == "ok" @@ -1257,7 +1292,10 @@ def test_load_dup_refuses_a_file_main_writes_with_two_nodes_of_one_hash( class _Logged(logging.Handler): + """Collect the warnings and errors Orcapod logs while a case runs.""" + def emit(self, record: logging.LogRecord) -> None: + """Keep the record's message.""" LOGGED.append(f"{record.levelname}: {record.getMessage()}") From 416cc7e36be84a9e53510b752314daf662ea5383 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Wed, 2 Dec 2026 15:11:25 -0800 Subject: [PATCH 12/12] test(pipeline): exercise the origin-pruning callback directly (ITL-1848) Keep the 128 origins alive through recording, check every one is recorded, then let them die with no further capture, so only the weak-reference callback can drop their records. Co-Authored-By: Claude Opus 5.5 --- tests/test_pipeline/test_capture_leaves.py | 27 +++++++++++++--------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/tests/test_pipeline/test_capture_leaves.py b/tests/test_pipeline/test_capture_leaves.py index a2b12c4e1..31809c405 100644 --- a/tests/test_pipeline/test_capture_leaves.py +++ b/tests/test_pipeline/test_capture_leaves.py @@ -46,22 +46,27 @@ def _graph(receiver: str) -> Pipeline | PipelineJob: @pytest.mark.parametrize("receiver", ["pipeline", "job"]) def test_dead_declared_origins_are_dropped(receiver: str) -> None: - """Delta review 4 on PR 695: 128 temporary declarations left 128 dead records.""" + """Delta review 4 on PR 695: 128 temporary declarations left 128 dead records. + + The origins stay alive through recording, so every one is recorded; they die + afterwards, with no further capture, so the weak-reference callback alone drops + their records (CodeRabbit on PR 695). + """ graph = _graph(receiver) key = graph_hash(SourceNode.from_stream(_source("probe", 0), name="alias")) - - def capture(number: int) -> None: - slot = SourceNode.from_stream(_source(f"origin_{number}", number), name="alias") - assert graph_hash(slot) == key - double.pod(slot, label="same") - + origins = [_source(f"origin_{number}", number) for number in range(128)] with graph: - for number in range(128): - capture(number) + for origin in origins: + slot = SourceNode.from_stream(origin, name="alias") + assert graph_hash(slot) == key + double.pod(slot, label="same") + records = graph._capture_leaves # pyright: ignore[reportPrivateUsage] # the records under test + # Every live origin is recorded under the one capture key. + assert len(records[key.to_string()]) == len(origins) + origins.clear() gc.collect() - leaves = graph._capture_leaves[key.to_string()] # pyright: ignore[reportPrivateUsage] # the records under test # No origin is alive: one record of the slot is kept, for the structural checks. - assert len(leaves) == 1 + assert len(records[key.to_string()]) == 1 @pytest.mark.parametrize("receiver", ["pipeline", "job"])