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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/ITL-1436.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 4 additions & 2 deletions docs/concepts/sources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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.

Expand Down
1 change: 1 addition & 0 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.<locals>.<lambda>`, `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.<locals>.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.<locals>.<lambda>` |
| 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__` |
Expand Down
5 changes: 3 additions & 2 deletions src/orcapod/core/nodes/source_node.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
106 changes: 70 additions & 36 deletions src/orcapod/pipeline/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 [
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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).
Expand All @@ -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
# ------------------------------------------------------------------
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down
34 changes: 14 additions & 20 deletions src/orcapod/pipeline/dag.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = {}

Expand All @@ -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)
Expand All @@ -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

# ------------------------------------------------------------------
Expand Down Expand Up @@ -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
Expand All @@ -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).
Expand Down Expand Up @@ -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)
Loading
Loading