diff --git a/changelog.d/ITL-1436.md b/changelog.d/ITL-1436.md new file mode 100644 index 000000000..5db7da87b --- /dev/null +++ b/changelog.d/ITL-1436.md @@ -0,0 +1,7 @@ +### Fixed + +- Pipeline jobs build and restore nodes in a stable order across processes and definition + orders. Generated label suffixes leave explicitly named nodes addressable, and identical + invocations keep the alphabetically first explicit label. Saved jobs list source bindings + by slot name. Run summaries and `RestrictedAggregationWarning` list restricted sources by + slot name or direct source label. diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md index fd55fa681..7fc9c8f84 100644 --- a/docs/concepts/sources.md +++ b/docs/concepts/sources.md @@ -579,7 +579,8 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **Recorded.** `RunSummary.conditions` maps the slot of each source read under a condition to its `Condition`, `RunSummary.limits` the slot of each source read with a `limit=` to the limit, and `RunSummary.restricted_source_ids` every such slot to its source id; the - summary shows them (`spikes (spikes): where unit_id=106, limit 3`). A saved job records them in + summary shows them in alphabetical order by slot name or direct source label + (`spikes (spikes): where unit_id=106, limit 3`). A saved job records them in the source's config, and a loaded job reads with them. A slot's new restriction need not match its previous one: a restricted source fits the slot of the unrestricted one, and `bind` does not compare the two. But a bind after which two slots would read one source @@ -603,7 +604,8 @@ print(Condition.of(day=day, started=started, recorded=recorded)) - **Under an aggregation.** A `GroupBy`, `Batch` or `MergeJoin` below a restricted source builds its groups from the rows the restriction lets through. That is allowed (each aggregated row lists its members), and a job run issues one - `RestrictedAggregationWarning` naming the source and the step. + `RestrictedAggregationWarning` listing each source and step in alphabetical order by slot + name or direct source label, then by step label. - **Stored rows stay.** A run over a restricted source deletes nothing: a job node shows the rows of its current run, and `node.as_source()` shows everything stored for it. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 058dbccce..0a1ff215c 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -395,6 +395,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` | | hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` | | in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._record_invocation`, `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 topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` | | canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams..` | | in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` | | comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` | diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 501f83e45..abb112f5d 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -638,12 +638,13 @@ def _take_saved_state_of(self, other: "SourceNodeBase") -> None: ``from_slot``, ``as_node``, ...), so no copy drops a piece: the given Arrow schemas, the saved Arrow type texts of an unresolved slot (ITL-640) and the saved pipeline hash, which does not depend on the slot's name, are always - kept. The saved content hash covers the name too, so it is kept only when this - slot has *other*'s name. + kept. The label and saved content hash are kept when this slot has *other*'s + name. """ self._saved_pipeline_hash = other._saved_pipeline_hash self._given_arrow_schemas = other._given_arrow_schemas if self._name == other._name: + self._label = other._label self._saved_content_hash = other._saved_content_hash self._saved_arrow_texts = other._saved_arrow_texts diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index e17f3141b..0e6ee4606 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -349,13 +349,21 @@ def _record_invocation(self, invocation: PodInvocation) -> None: # every source the pipeline's streams read now (nothing is remembered: a # slot rebound since the last invocation changes what they read). require_one_restriction([*self._held_streams(), *inputs]) - self._invocation_lut[key] = invocation + self._remember_invocation(key, invocation) self._hash_graph.add_node(key) for upstream, upstream_hash in upstreams: self._hash_graph.add_edge(upstream_hash, key) if upstream_hash not in self._source_streams: self._source_streams[upstream_hash] = upstream + def _remember_invocation(self, key: str, invocation: PodInvocation) -> None: + """Keep the smallest explicit label when identical invocations share a node.""" + previous = self._invocation_lut.get(key) + if previous is not None and previous.label is not None: + if invocation.label is None or previous.label < invocation.label: + return + self._invocation_lut[key] = invocation + def _held_streams(self) -> list[Any]: """Every stream the pipeline holds: its leaves and every recorded input.""" return [ @@ -494,19 +502,17 @@ def compile(self) -> None: source_node_cls = self.source_node_class - # 1. Source hashes: inputs that have no registered invocation. - source_hashes = set(self._source_streams.keys()) - set( - self._invocation_lut.keys() + # 1. Resolve source nodes in hash order, then insert them by their slot + # labels. The original stream hash breaks ties between identical labels. + sources = [ + (h, source_node_cls.from_stream(self._source_streams[h])) + for h in sorted(self._source_streams.keys() - self._invocation_lut.keys()) + ] + node_map: dict[str, Any] = dict( + sorted(sources, key=lambda item: (item[1].label, item[0])) ) - # 2. Create source nodes keyed by the original stream hash. - node_map: dict[str, Any] = { - h: source_node_cls.from_stream(self._source_streams[h]) - for h in source_hashes - if h in self._source_streams - } - - # 2a. Validate source-node name uniqueness. + # 2. Validate source-node name uniqueness. # Source node names are identity-forming (used as bind() keys and # included in content_hash()). Two distinct source nodes with the # same name are refused: with different schemas by InconsistentSourceError, @@ -551,8 +557,8 @@ def compile(self) -> None: node_name, [self._source_streams[h] for h in hashes] ) - # 3. Topological pass — create function / operator nodes. - for key in _nx.topological_sort(self._hash_graph): + # 3. Topological pass with independent invocations ordered by hash. + for key in _nx.lexicographical_topological_sort(self._hash_graph): if key in node_map: continue # already added as a source node in step 2 if key not in self._invocation_lut: @@ -580,34 +586,44 @@ def compile(self) -> None: label=inv.label, ) - self._persistent_node_map = node_map - - # 4. Label disambiguation (preserves existing Pipeline.compile() behavior). + # 4. Reserve every original label before generating any suffixes. name_candidates: dict[str, list] = {} for node in node_map.values(): name_candidates.setdefault(node.label, []).append(node) - self._nodes.clear() + reserved_names = set(name_candidates) for label, nodes in name_candidates.items(): if len(nodes) > 1: + explicitly_named = [node for node in nodes if node._label is not None] + if len(explicitly_named) == 1: + # A computed label can coincide with an otherwise unique explicit one. + nodes = [node for node in nodes if node is not explicitly_named[0]] sorted_nodes = sorted(nodes, key=lambda n: n.content_hash().to_string()) - for i, node in enumerate(sorted_nodes, start=1): + i = 1 + for node in sorted_nodes: key = f"{label}_{i}" - self._nodes[key] = node + while key in reserved_names: + i += 1 + key = f"{label}_{i}" + reserved_names.add(key) node._label = key - else: - self._nodes[label] = nodes[0] + i += 1 + + node_map = self._ordered_node_map(node_map, self._hash_graph) + 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() - for up_hash, down_hash in self._hash_graph.edges(): + 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) - for node in node_map.values(): - if node not in node_dag: - node_dag.add_node(node) self._node_graph = node_dag # 6. Enrich hash_graph node attributes (used by serialization). @@ -633,10 +649,32 @@ def compile(self) -> None: self._upstreams = { h: n for h, n in node_map.items() if isinstance(n, source_node_cls) } - self._graph_edges = list(self._hash_graph.edges()) + self._graph_edges = graph_edges self._compiled = True + @staticmethod + def _ordered_node_map( + nodes: dict[str, Any], graph: nx.DiGraph[str] + ) -> dict[str, Any]: + """Order compiled or restored nodes with slots first and dependencies intact.""" + from orcapod.core.nodes.source_node import SourceNodeBase + + def order_key(key: str) -> tuple[int, str, str, str]: + node = nodes.get(key) + if isinstance(node, SourceNodeBase): + return (0, node.name, node.label, key) + if node is None: # An unrestored node may still be in the saved graph. + return (1, key, "", key) + # Live and saved nodes share the schema-only pipeline hash. + return (1, node.pipeline_hash().to_string(), node.label, key) + + return { + key: nodes[key] + for key in nx.lexicographical_topological_sort(graph, key=order_key) + if key in nodes + } + # ------------------------------------------------------------------ # InvocationGraph transitions # ------------------------------------------------------------------ @@ -724,7 +762,7 @@ def to_invocations(self) -> InvocationGraph: ) # Sort topologically using _hash_graph (node_hash keys match _hash_graph). - topo_keys = list(_nx.topological_sort(self._hash_graph)) + topo_keys = _nx.lexicographical_topological_sort(self._hash_graph) ordered = [inv_by_node_hash[k] for k in topo_keys if k in inv_by_node_hash] return InvocationGraph( @@ -752,17 +790,13 @@ def from_invocations( A compiled instance of ``cls``. """ instance = cls(name=name) - instance._invocation_lut = { - inv.content_hash().to_string(): inv for inv in graph.invocations - } instance._source_streams = dict(graph.source_streams) for inv in graph.invocations: - instance._hash_graph.add_node(inv.content_hash().to_string()) + key = inv.content_hash().to_string() + instance._remember_invocation(key, inv) + instance._hash_graph.add_node(key) for upstream in inv.input_streams: - instance._hash_graph.add_edge( - upstream.content_hash().to_string(), - inv.content_hash().to_string(), - ) + instance._hash_graph.add_edge(upstream.content_hash().to_string(), key) # Also add source hashes as isolated nodes (no incoming edges) for h in graph.source_streams: if h not in instance._hash_graph: diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py index ccd8cea82..b192a5c96 100644 --- a/src/orcapod/pipeline/dag.py +++ b/src/orcapod/pipeline/dag.py @@ -114,10 +114,9 @@ class OrcaDAG(Generic[NodeT]): def __init__(self) -> None: # node → mutable attribute dict self._attrs: dict[NodeT, dict[str, Any]] = {} - # node → set of immediate successors (outgoing edges) - self._successors: dict[NodeT, set[NodeT]] = {} - # node → set of immediate predecessors (incoming edges) - self._predecessors: dict[NodeT, set[NodeT]] = {} + # node → immediate neighbours in edge insertion order + self._successors: dict[NodeT, dict[NodeT, None]] = {} + self._predecessors: dict[NodeT, dict[NodeT, None]] = {} # node → number of incoming edges (kept in sync with _predecessors) self._in_degree: dict[NodeT, int] = {} @@ -137,8 +136,8 @@ def add_node(self, node: NodeT, **attrs: Any) -> None: """ if node not in self._attrs: self._attrs[node] = {} - self._successors[node] = set() - self._predecessors[node] = set() + self._successors[node] = {} + self._predecessors[node] = {} self._in_degree[node] = 0 if attrs: self._attrs[node].update(attrs) @@ -156,8 +155,8 @@ def add_edge(self, u: NodeT, v: NodeT) -> None: self.add_node(u) self.add_node(v) if v not in self._successors[u]: - self._successors[u].add(v) - self._predecessors[v].add(u) + self._successors[u][v] = None + self._predecessors[v][u] = None self._in_degree[v] += 1 # ------------------------------------------------------------------ @@ -268,16 +267,13 @@ def in_degree(self, node: NodeT) -> int: # Internal helpers # ------------------------------------------------------------------ - def _build_predecessor_dict(self) -> dict[NodeT, set[NodeT]]: + def _build_predecessor_dict(self) -> dict[NodeT, tuple[NodeT, ...]]: """Build the predecessor mapping required by TopologicalSorter. - Returns a copy of the internal predecessor sets — safe for mutation - by `graphlib.TopologicalSorter`. - Returns: - Mapping of each node to a fresh copy of its predecessor set. + Mapping of each node to its predecessors in edge insertion order. """ - return {node: set(preds) for node, preds in self._predecessors.items()} + return {node: tuple(preds) for node, preds in self._predecessors.items()} # ------------------------------------------------------------------ # Ordering @@ -286,11 +282,9 @@ def _build_predecessor_dict(self) -> dict[NodeT, set[NodeT]]: def topological_sort(self) -> list[NodeT]: """Return nodes in a valid topological order. - Uses `graphlib.TopologicalSorter` (Python stdlib). The order is - stable within a single run but is not guaranteed to be - deterministic across Python versions or between runs. Use - `topological_sort_deterministic` when a stable, reproducible - order is required (e.g. for content hashing). + Uses `graphlib.TopologicalSorter` (Python stdlib), whose order follows + node and edge insertion. Use `topological_sort_deterministic` for an + order independent of how the graph was built. Returns: List of nodes in topological order (sources before dependents). @@ -370,5 +364,5 @@ def ancestors(self, node: NodeT) -> frozenset[NodeT]: n = queue.pop() if n not in visited: visited.add(n) - queue.extend(self._predecessors.get(n, set())) + queue.extend(self._predecessors[n]) return frozenset(visited) diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 2d81d8d0d..baec82ecf 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -268,7 +268,7 @@ def save(self, path: str | Path) -> None: case OperatorNode(): # The inputs in argument order (ITL-1417): an ordered operator # (MergeJoin, SemiJoin) is rebuilt from this list, never from the - # edge list, whose order follows the order steps were recorded in. + # edge list, which is sorted by hash before serialization. inputs = [ key_of[id(upstream)] for upstream in node.upstreams @@ -363,7 +363,7 @@ def load(cls, path: str | Path) -> "Pipeline": for node_hash in nodes_data: if node_hash not in edge_graph: edge_graph.add_node(node_hash) - topo_order = list(nx.topological_sort(edge_graph)) + topo_order = nx.lexicographical_topological_sort(edge_graph) upstream_map: dict[str, list[str]] = {} for up_hash, down_hash in edges: @@ -605,6 +605,10 @@ def load(cls, path: str | Path) -> "Pipeline": descriptor, input_stream=upstream_node ) + # Keep old files' edge order only for the legacy input-order fallback above. + edges = sorted((up, down) for up, down in edges) + reconstructed = cls._ordered_node_map(reconstructed, edge_graph) + # Build Pipeline instance pipeline = cls(name=name, auto_compile=False) pipeline._loaded_output_schemas = { @@ -629,17 +633,16 @@ def load(cls, path: str | Path) -> "Pipeline": pipeline._nodes = nodes_by_label node_dag: OrcaDAG[GraphNode] = OrcaDAG() + 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) - for node in reconstructed.values(): - if node not in node_dag: - node_dag.add_node(node) pipeline._node_graph = node_dag - pipeline._graph_edges = [(up, down) for up, down in edges] + pipeline._graph_edges = edges pipeline._hash_graph = nx.DiGraph() for up_hash, down_hash in edges: pipeline._hash_graph.add_edge(up_hash, down_hash) diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py index 4abe1371c..434f198f3 100644 --- a/src/orcapod/pipeline/job.py +++ b/src/orcapod/pipeline/job.py @@ -761,11 +761,7 @@ def as_pipeline(self) -> "Pipeline": node_map: dict[str, object] = {} - for node_hash in _nx.topological_sort(self._hash_graph): - if node_hash not in persistent: - continue - job_node = persistent[node_hash] - + for node_hash, job_node in persistent.items(): if isinstance(job_node, SourceJobNode): node_map[node_hash] = job_node.as_node() @@ -832,17 +828,12 @@ def as_pipeline(self) -> "Pipeline": dict(self._hash_graph.nodes[old_h]) if old_h in self._hash_graph else {} ) bp_hash_graph.add_node(new_h, **old_attrs) - for up_h, down_h in self._hash_graph.edges(): - new_up = old_to_new.get(up_h) - new_down = old_to_new.get(down_h) - if new_up is not None and new_down is not None: - bp_hash_graph.add_edge(new_up, new_down) - - new_graph_edges = [ + new_graph_edges = sorted( (old_to_new[u], old_to_new[v]) for u, v in self._graph_edges if u in old_to_new and v in old_to_new - ] + ) + bp_hash_graph.add_edges_from(new_graph_edges) pipeline = Pipeline(name=self._name, auto_compile=False) pipeline._hash_graph = bp_hash_graph @@ -864,14 +855,10 @@ 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() - for up_h, down_h in self._hash_graph.edges(): - up_node = node_map.get(up_h) - down_node = node_map.get(down_h) - if up_node is not None and down_node is not None: - bp_dag.add_edge(up_node, down_node) - for node in node_map.values(): - if node not in bp_dag: - bp_dag.add_node(node) + 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 pipeline._compiled = True @@ -1630,7 +1617,7 @@ def save(self, path: "str | Path") -> None: # Serialize source configs (best-effort — skip non-reconstructable sources) sources_block: dict[str, Any] = {} - for spec_name, source in self._sources.items(): + for spec_name, source in sorted(self._sources.items()): if hasattr(source, "to_config"): try: # ``hasattr`` checked it: every source declares it. @@ -1980,7 +1967,6 @@ def load( # • _distribute_databases() wires their databases correctly # • job.nodes["label"].get_all_records() works after loading a completed job # • run() includes them in the execution DAG - import networkx as _nx from orcapod.core.nodes.function_node import FunctionNode as _FunctionNode from orcapod.core.nodes.operator_node import OperatorNode as _OperatorNode from orcapod.core.nodes.source_node import SourceNode as _SourceNode @@ -2022,11 +2008,7 @@ def load( # is the source of truth. expected_rows: dict[str, int] = run_block.get("expected_rows", {}) - for node_hash in _nx.topological_sort(job._hash_graph): - bp_node = pipeline._persistent_node_map.get(node_hash) - if bp_node is None: - continue - + for node_hash, bp_node in pipeline._persistent_node_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 diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index b993dc850..74fbebd05 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -485,7 +485,8 @@ def warn_restricted_aggregation(dag: OrcaDAG[StreamProtocol]) -> None: Called by ``job.run()`` and ``run_async()`` before the run (ITL-1218). The warning names each source slot and aggregating step, at the user's line that - started the run, at every run. + started the run, at every run. Pairs are ordered by slot name (or direct + source label), then by step label. Args: dag: The job's graph of the run. @@ -496,22 +497,25 @@ def warn_restricted_aggregation(dag: OrcaDAG[StreamProtocol]) -> None: from orcapod.errors import RestrictedAggregationWarning from orcapod.utils.warning_utils import outside_orcapod_stacklevel, warn_at_frame - pairs: list[str] = [] - for node in dag.topological_sort(): + position = {node: index for index, node in enumerate(dag.nodes())} + pairs: list[tuple[str, str, str]] = [] + for node in position: step = node.producer if not isinstance(step, (GroupBy, Batch, MergeJoin)): continue - restricted = sorted(restrictions_in_force(dag.ancestors(node))) + ancestors = sorted(dag.ancestors(node), key=position.__getitem__) pairs.extend( - f"{slot!r} feeds {type(step).__name__} {node.label!r}" - for slot in restricted + (slot, node.label, type(step).__name__) + for slot in restrictions_in_force(ancestors) ) if not pairs: return caller = sys._getframe(outside_orcapod_stacklevel() - 1) # pyright: ignore[reportPrivateUsage] # as the warnings module does warn_at_frame( "A restricted source feeds an aggregating step: " - + "; ".join(pairs) + + "; ".join( + f"{slot!r} feeds {kind} {label!r}" for slot, label, kind in sorted(pairs) + ) + ". Its groups are built from the rows the restriction lets through only " "(each aggregated row lists its members).", RestrictedAggregationWarning, diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py index 97a691b48..a10442636 100644 --- a/src/orcapod/pipeline/run_summary.py +++ b/src/orcapod/pipeline/run_summary.py @@ -120,7 +120,8 @@ def __init__( ran_nothing: Whether the run ran no node (every node held a current run). restricted_sources: Slot name to the source id, the condition (empty for none) and the limit of each restricted source of the run - (``restrictions.restrictions_in_force``). + (``restrictions.restrictions_in_force``). Displayed by slot name + or direct source label. """ self.job_name: str = job_name self.nodes: Mapping[str, NodeRunSummary] = {node.label: node for node in nodes} @@ -129,7 +130,7 @@ def __init__( self.unchecked_sources: tuple[str, ...] = tuple(unchecked_sources) self.ran_nothing: bool = ran_nothing # One mapping split three ways, so the keys cannot disagree. - restricted = dict(restricted_sources or {}) + restricted = dict(sorted((restricted_sources or {}).items())) self.conditions: Mapping[str, Condition] = { slot: condition for slot, (_, condition, _) in restricted.items() diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index d45fa0b05..778a9d98c 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -40,8 +40,12 @@ import itertools import json import operator +import os import re import sqlite3 +import subprocess +import sys +import warnings from collections.abc import Callable, Sequence from dataclasses import dataclass, field from pathlib import Path @@ -53,7 +57,15 @@ import pytest import orcapod -from orcapod import PipelineJob, col, function_pod, operators, sources, streams +from orcapod import ( + Pipeline, + PipelineJob, + col, + function_pod, + operators, + sources, + streams, +) from orcapod.channels import Channel from orcapod.core.nodes import SourceJobNode from orcapod.core.nodes.function_node import ( @@ -63,6 +75,8 @@ from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.core.streams import ArrowTableStream from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import RestrictedAggregationWarning +from orcapod.protocols.core_protocols import StreamProtocol from orcapod.system_constants import PIPELINE_DB_SCHEMA_VERSION from orcapod.types import Condition from orcapod.operators import ( @@ -101,6 +115,7 @@ ListSource, PollingSource, SQLiteTableSource, + SpiralDBTableSource, ) from orcapod.types import CacheMode, Cursor @@ -1205,3 +1220,175 @@ def test_a_saved_job_records_the_declared_order_and_loads_the_same_hashes( assert loaded.nodes["pod"].content_hash() == original hashes.append(original) assert hashes[0] == hashes[1] + + +@function_pod(output_keys="doubled") +def _double_reading(reading: int | None) -> int: + """Double one reading.""" + return (reading or 0) * 2 + + +@pytest.mark.parametrize("first_source", ["a", "step_1"]) +def test_explicit_suffixes_remain_addressable_in_every_definition_order( + first_source: str, +) -> None: + """A generated suffix never shadows a node with its own label.""" + definitions = ((first_source, 1, "step"), ("b", 2, "step"), ("c", 3, "step_1")) + results: dict[str, dict[str, Any]] = {} + for order in itertools.permutations(definitions): + job = PipelineJob(name="labels", database=InMemoryArrowDatabase()) + with job: + for name, value, label in order: + source = ListSource("reading", [value], source_id=name) + _ = _double_reading.pod(source, label=label) + summary = job.run() + assert set(summary.nodes) == {"step_1", "step_2", "step_3"} + assert job.nodes["step_1"].as_table()["doubled"].to_pylist() == [6] + results["".join(name for name, _, _ in order)] = { + "labels": list(job.nodes), + "rows": { + name: job.nodes[name].as_table()["doubled"].to_pylist() + for name in summary.nodes + }, + } + assert_all_equal(results) + + +@pytest.mark.parametrize("labels", [("label_z", "label_a"), (None, "label_a")]) +def test_identical_invocations_keep_the_smallest_explicit_label( + labels: tuple[str | None, str], +) -> None: + """Invocations deduplicate whichever label was recorded first.""" + for order in (labels, labels[::-1]): + source = ListSource("reading", [2], source_id="readings") + job = PipelineJob(name="labels", database=InMemoryArrowDatabase()) + with job: + for label in order: + _ = _double_reading.pod(source, label=label) + assert list(job.nodes) == ["readings", "label_a"] + assert list(job.run().nodes) == ["label_a"] + + +def _restricted_job_run(root: Path, names: Sequence[str]) -> None: + """Print the node labels, summary lines and warning for one job in a child process.""" + from tests.test_databases import fake_pyspiral + + keys = pa.schema([pa.field("subject", pa.string())]) + with fake_pyspiral.install(root): + project = fake_pyspiral.FakeSpiral().project("synthetic") + for value, name in enumerate(sorted(names)): + # Distinct readings avoid competing for the same cache entry in async. + rows = pa.table({"subject": ["a", "b"], "reading": [value, value + 1]}) + project.create_table(f"default.{name}", key_schema=keys).write(rows) + + bindings: dict[str, StreamProtocol] = { + name: SpiralDBTableSource( + "synthetic", name, source_id=name, tag_only_columns=True + ).where(subject="a") + for name in names + } + pipeline = Pipeline(name="restricted") + with pipeline: + for name, source in bindings.items(): + # The step labels run the opposite way to the source names. + _ = GroupBy(["subject"])(source, label=f"group_{name[-1]}") + if name == "alpha3": + _ = Batch(batch_size=2)(source, label="another_alpha") + _ = _double_reading.pod(source, label=f"read_{name}") + results = {} + path = root / "job.json" + for async_run in (False, True): + database = InMemoryArrowDatabase() + job = PipelineJob.from_pipeline(pipeline, database, sources=bindings) + labels = list(job.nodes) + summary_labels: list[str] = [] + assert labels.index("group_3") < labels.index("another_alpha") + for load_only in (False, True): + if load_only: + job = PipelineJob.load(path, database=database) + assert list(job.nodes) == labels + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", RestrictedAggregationWarning) + summary = ( + asyncio.run(job.run_async(load_only=load_only)) + if async_run + else job.run(load_only=load_only) + ) + (warning,) = ( + str(item.message) + for item in caught + if item.category is RestrictedAggregationWarning + ) + if load_only: + assert list(summary.nodes) == summary_labels + assert all(node.reused == 1 for node in summary.nodes.values()) + else: + summary_labels = list(summary.nodes) + results[f"{async_run}-{load_only}"] = { + "nodes": list(job.nodes), + "summary": str(summary), + "warning": warning, + } + if not load_only: + job.save(path) + saved = json.loads(path.read_text()) + assert list(saved["bindings"]["sources"]) == sorted(names) + # Independently vary the serialized order, as in pre-fix files. + saved["pipeline"]["edges"].reverse() + saved["pipeline"]["nodes"] = dict( + reversed(saved["pipeline"]["nodes"].items()) + ) + path.write_text(json.dumps(saved)) + print(json.dumps(results)) + + +def test_restricted_job_order_is_independent_of_hash_seed_and_definition_order( + tmp_path: Path, +) -> None: + """Compare the full summary and warning across processes and branch orders.""" + names = ("alpha3", "beta2", "gamma1") + results: dict[str, dict[str, Any]] = {} + for seed in ("1", "7", "42"): + for order in (names, names[::-1]): + variant = f"{seed}-{order[0]}" + process = subprocess.run( + [ + sys.executable, + "-c", + f"from {__name__} import _restricted_job_run, Path; " + "import sys; _restricted_job_run(Path(sys.argv[1]), sys.argv[2:])", + str(tmp_path / variant), + *order, + ], + env={**os.environ, "PYTHONHASHSEED": seed}, + capture_output=True, + text=True, + timeout=60, + ) + assert process.returncode == 0, process.stderr + results[variant] = json.loads(process.stdout) + + assert_all_equal(results) + for result in next(iter(results.values())).values(): + assert result["nodes"][: len(names)] == list(names) + restrictions = next( + line + for line in result["summary"].splitlines() + if line.lstrip().startswith("restricted sources:") + ) + entries = restrictions.lstrip().removeprefix("restricted sources: ").split("; ") + slots = [] + for entry in entries: + match = re.fullmatch( + r"(?P\w+) \(spiraldb_table_v1:(?P=slot)\): where subject='a'", + entry, + ) + assert match is not None, entry + slots.append(match["slot"]) + assert slots == list(names) + assert re.findall(r"'(\w+)' feeds \w+ '(\w+)'", result["warning"]) == [ + ("alpha3", "another_alpha"), + ("alpha3", "group_3"), + ("beta2", "group_2"), + ("gamma1", "group_1"), + ] diff --git a/tests/test_pipeline/test_store_errors_together.py b/tests/test_pipeline/test_store_errors_together.py index c5cd63bca..7976b54db 100644 --- a/tests/test_pipeline/test_store_errors_together.py +++ b/tests/test_pipeline/test_store_errors_together.py @@ -83,28 +83,33 @@ def _reset_damage() -> Iterator[None]: _DAMAGE_ON_NEXT_CALL.clear() -def build_job(database_path: Path, keys: str, *, reader_first: bool) -> PipelineJob: - """Two sibling nodes over one source: ``rd`` (doubles) and ``wr`` (triples). +def build_job( + database_path: Path, keys: str, *, reader_first: bool | None +) -> PipelineJob: + """Two independent nodes: ``rd`` (doubles) and ``wr`` (triples). - ``reader_first`` decides which node is added first, and so comes first in - node order. + ``reader_first`` decides which node reads the first source in slot order. + With ``None``, both nodes read the same source. """ - source = ArrowTableSource( - pa.table({"k": list(keys), "x": list(range(1, len(keys) + 1))}), - tag_columns=["k"], - tag_only_columns=True, - infer_nullable=True, - ) + table = pa.table({"k": list(keys), "x": list(range(1, len(keys) + 1))}) + sources = [ + ArrowTableSource( + table, + source_id=name, + tag_columns=["k"], + tag_only_columns=True, + infer_nullable=True, + ) + for name in (("first",) if reader_first is None else ("first", "second")) + ] + read_source = sources[-1] if reader_first is False else sources[0] + write_source = sources[0] if reader_first is False else sources[-1] job = PipelineJob( name="together", database=DeltaTableDatabase(base_path=database_path) ) with job: - if reader_first: - _ = double.pod(source, label="rd") - _ = triple.pod(source, label="wr") - else: - _ = triple.pod(source, label="wr") - _ = double.pod(source, label="rd") + _ = double.pod(read_source, label="rd") + _ = triple.pod(write_source, label="wr") return job @@ -145,7 +150,7 @@ def run_with_both_failures( tmp_path: Path, make_orchestrator: Callable[[], Any], *, - reader_first: bool, + reader_first: bool | None, ) -> OrcapodDatabaseError: """Run a job in which ``rd``'s read and ``wr``'s write fail on the new row d. @@ -172,9 +177,13 @@ def run_with_both_failures( return info.value -@pytest.mark.parametrize("reader_first", [True, False], ids=["rd-first", "wr-first"]) +@pytest.mark.parametrize( + ("reader_first", "winner"), + [(True, "rd"), (False, "wr"), (None, "wr")], + ids=["rd-first", "wr-first", "broadcast"], +) def test_sync_and_async_raise_the_same_error( - tmp_path: Path, reader_first: bool + tmp_path: Path, reader_first: bool | None, winner: str ) -> None: """Both orchestrators raise the error of the node that comes first.""" raised = { @@ -184,12 +193,12 @@ def test_sync_and_async_raise_the_same_error( expected_type, expected_node = ( (OrcapodDatabaseReadError, "rd") - if reader_first + if winner == "rd" else (OrcapodDatabaseWriteError, "wr") ) # rd's read failure surfaces when rd commits its batch, which names no row # (ITL-919); wr's failed write of row d names that row. - expected_tag = None if reader_first else {"k": "d"} + expected_tag = None if winner == "rd" else {"k": "d"} for name, err in raised.items(): assert type(err) is expected_type, (name, err) assert err.node_label == expected_node, (name, err) diff --git a/tests/test_pipeline/test_store_write_failure.py b/tests/test_pipeline/test_store_write_failure.py index 28edd6ea8..b46ffe287 100644 --- a/tests/test_pipeline/test_store_write_failure.py +++ b/tests/test_pipeline/test_store_write_failure.py @@ -703,13 +703,16 @@ def test_several_store_errors_raise_the_first_in_node_order( """Several database errors raise the first node's, the same on both orchestrators.""" faults = Faults(write_marker=RESULT_TABLE) job = build_siblings(FaultyStore(InMemoryArrowDatabase(), faults), triple_async) + first, second = sorted( + ("dbl", "other"), + key=lambda label: (job.nodes[label].pipeline_hash().to_string(), label), + ) with caplog.at_level("WARNING"): with pytest.raises(OrcapodDatabaseWriteError) as exc_info: job.run(orchestrator=orchestrator_cls()) - # The sync orchestrator meets ``dbl`` first; the async one raises the same. - assert_database_error(exc_info.value, faults, node_label="dbl", names_row=True) + assert_database_error(exc_info.value, faults, node_label=first, names_row=True) if orchestrator_cls is AsyncPipelineOrchestrator: others = [ record @@ -717,7 +720,7 @@ def test_several_store_errors_raise_the_first_in_node_order( if record.levelname == "WARNING" and "Another database write failed" in record.getMessage() ] - assert any("node 'other'" in r.getMessage() for r in others), others + assert any(f"node {second!r}" in r.getMessage() for r in others), others # ---------------------------------------------------------------------------