diff --git a/.zed/rules b/.zed/rules index 454407896..91ce94002 100644 --- a/.zed/rules +++ b/.zed/rules @@ -1332,7 +1332,11 @@ these preimages anywhere else. else: blocks) only for a module `import orcapod` never loads (networkx, deltalake, pyarrow.fs, pyarrow.dataset, git) and the optional extras (psycopg, ray, spiral); tests/test_utils/test_lazy_module_use.py checks it. -- Argument symmetry — operators return frozenset (commutative) or tuple (ordered). +- Argument symmetry — `structural_argument_symmetry(streams)` describes the occurrences + in a structural identity. A commutative `SymmetricGroup` sorts hashes and keeps repeats. + A tuple preserves argument order. Content hashes use the resulting pipeline hash + and the source chain. System-tag suffixes use the same structural digest as stored + table paths (ITL-1590). - StaticOutputPod.process() → DynamicPodStream — wraps static_process() with staleness detection and automatic recomputation. - Source delegation — CSVSource, DictSource, etc. create an internal ArrowTableSource. diff --git a/CLAUDE.md b/CLAUDE.md index 91ffef8d2..f782b3711 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1376,8 +1376,11 @@ and `as_table()` methods. `all_info=True` sets everything to True. `import orcapod` never loads (networkx, deltalake, `pyarrow.fs`, `pyarrow.dataset`, git) and for the optional extras (psycopg, ray, spiral). `tests/test_utils/test_lazy_module_use.py` checks it. -- **Argument symmetry** — each operator declares `argument_symmetry(streams)` returning - `frozenset` (commutative) or `tuple` (ordered). Determines how upstream hashes combine. +- **Argument symmetry** — `structural_argument_symmetry(streams)` describes the occurrences + in a structural identity. A commutative `SymmetricGroup` sorts hashes and keeps repeats. + A tuple preserves argument order. Content hashes use the resulting pipeline hash + and the source chain. System-tag suffixes use the same structural digest as stored + table paths (ITL-1590). - **`StaticOutputPod.process()` → `DynamicPodStream`** — wraps `static_process()` output with timestamp-based staleness detection and automatic recomputation. - **Source delegation** — CSVSource, DictSource, etc. all create an internal diff --git a/changelog.d/ITL-1590.md b/changelog.d/ITL-1590.md new file mode 100644 index 000000000..398b05bc7 --- /dev/null +++ b/changelog.d/ITL-1590.md @@ -0,0 +1,33 @@ +### Breaking changes and migration + +- The pipeline hash now counts every input to a commutative operator. It changes + for a pipeline with a commutative step whose inputs include repeated or + content-equal streams. Its content hash changes with the pipeline hash and + source chain. Stored table paths for that step and its downstream + steps move because those paths include the pipeline hash. +- In a recorded `Join(a, a)` or a Join of two slots bound to the same source, + the stored rows used to have one source-id column and one record-id column + without a Join suffix. They now have both + columns at each of `:::0` and `:::1`, + with the same names as `Join(a, b)` when `a` and `b` have the same + structure. This changes the repeated join's stored entry IDs. Direct table, + row-channel and batch joins already included both positions. Downstream + operators that use the repeated join as an input to a system-tag suffix + now use its two-input hash, changing those names and entry IDs as well. +- Pre-change stores for joins with repeated or content-equal inputs, including + two slots bound to one source, use the old system-tag column names, + entry IDs, and table paths. Runs skip affected + rows in load-only mode and recompute them in normal mode. In a two-row + self-join saved on `main`, `job.run(load_only=True)` reports + `0 loaded, 2 not stored (skipped)`, and `out.as_source()` still returns + both original rows. Jobs written and replayed with the new layout load + their stored rows. This migration affects only pre-release stores. + +### Fixed + +- The pipeline, source, and name chains retain every occurrence of an input + to a commutative step. Capture preserves the same multiplicity when compiling + the graph. Sync and async execution feed each declared operand, even when + several positions share a graph predecessor. Cold and warm pipeline hashes + share one memo and handle deep pipelines without recursion. +- Capture and execution distinguish invocations whose input repeat counts differ. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index 5fd19a531..b83c0345c 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -10,9 +10,8 @@ It also cannot follow a slot through a rebind while identifying the same computa (ITL-1442, ITL-1427). Step 1 computes separate structure, source and name chains. The new node hash is -available even when no source is bound. The graph and persistence still use their -existing hashes. ITL-1590 tracks the remaining structural dependency on source equality -when a commutative operator receives equal-structure inputs. +available even when no source is bound. ITL-1590 makes commutative structure +independent of source equality and retains every input occurrence. The step 1 follow-up serializes binding and chain reads. Saved jobs retain the existing file format. An unavailable built-in with one input uses its saved structure @@ -21,8 +20,7 @@ symmetry to report the new chains. Schema-less polling sources report a node has before their first batch, including when wrapped in a cache. **Fix:** The execution protocols require both combined identity accessors. The -combined hashes raise when the legacy commutative grouping drops content-equal -arguments, including in downstream nodes. Recovering the lost order remains ITL-1590. +three chains retain content-equal argument occurrences. Row layout uses each input occurrence. Source chains follow rebindings inside composite bindings and source wrappers. Downstream chain reads never poll for a missing schema. Mixed nested input groups use the pipeline hash's canonical ordering. diff --git a/docs/dev/design_issues/ITL-1590-CS1.md b/docs/dev/design_issues/ITL-1590-CS1.md new file mode 100644 index 000000000..75ae70af5 --- /dev/null +++ b/docs/dev/design_issues/ITL-1590-CS1.md @@ -0,0 +1,22 @@ +## Pipeline identity + +### CS1 — Commutative pipeline hashes lost equal input occurrences +**Status:** resolved +**Severity:** high +**Issue:** ITL-1590 + +Join's set of streams could collapse operands that compared equal by content. +The resulting pipeline hash depended on source equality and lost an argument. + +**Fix:** Carry every argument occurrence through the pipeline, source and name +chains. A commutative structural preimage sorts its input hashes and keeps repeats. +The capture registry keeps repeated occurrences and computes keys bottom-up, +reusing upstream keys across captures. Compilation preserves each recorded +operand. The content hash includes the pipeline hash and source chain, so the +execution graph distinguishes invocations whose input repeat counts differ. + +Both job orchestrators feed every declared operand position when equal upstreams +share a graph edge, including distinct slots bound to one source. The declaration +keeps both slots for serialization and rebinding. Join uses the same digest and +positions for table, row-channel and batch system tags. Pipeline hashing resolves cold +dependencies iteratively in the same memo used by the Join input sorter. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 49826b24c..2c57ee33a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -315,8 +315,9 @@ combines the pipeline hash and the source chain for streams, invocations and nod A root source's own content hash remains its address. Reading the source chain or the combined content hash raises `UnboundSourceError` while a contributing slot is unbound. Orcapod uses the combined hash for stored node rows and bound graph keys. -Unbound graph declarations use their node hashes. ITL-1590 tracks cases where the -existing pipeline hash depends on source equality within a commutative input tie. +Unbound graph declarations use their node hashes. Pipeline hashes and capture keys +include every commutative input occurrence (ITL-1590). Stored table paths use the +pipeline hash. The saved job format does not carry input symmetry yet. A loaded built-in with one input uses the saved pipeline hash and hashes that input's chains, even when its operator implementation is unavailable. An unavailable operator with multiple @@ -457,12 +458,13 @@ 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._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_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`, `pipeline/base.py:AbstractPipelineBase.compile..`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) | +| in-memory 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` | | in-memory lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` | | 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..` | +| 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 structural identity counts all input positions | `core/operators/join.py:Join.order_input_streams..` | | canonical input order for source and name chains (pipeline inputs' canonical JSON, then each chain's labelled hash within a tie) | `core/identity_chains.py:_pool_group` | | 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__` | @@ -637,6 +639,7 @@ How containers expand (canonical JSON: sorted object keys, no whitespace, UTF-8) | `tuple` | `{"__type__": "tuple", "items": [...]}` | order | | `set` | `{"__type__": "set", "items": [...]}`, items sorted by their canonical JSON text | membership only; never iteration order or `PYTHONHASHSEED` (ITL-942: before v0.3, items were sorted by `str()`, so `{1, "1"}` hashed differently per process) | | `frozenset` | `{"__type__": "frozenset", "items": [...]}`, items sorted as for `set` | membership, and that it is a `frozenset`: a frozenset and a set of the same items differ (ITL-1154) | +| `SymmetricGroup` | the historical `frozenset` encoding with all members sorted and repeats preserved | every commutative argument occurrence (ITL-1590) | | `dict` with only `str` keys, none of them `"__type__"` | JSON object | keys and values, not insertion order | | any other `dict` | `{"__type__": "dict", "items": [[key, value], ...]}`, pairs sorted by canonical JSON | key types: `{1: "x"}` and `{"1": "x"}` differ (ITL-942: before v0.3, keys went through `str()` and could collapse) | | namedtuple | `{"__type__": "namedtuple", "name": ..., "fields": [[name, value], ...]}` | class name, field names and values, in declared order (ITL-942: before v0.3 fields were sorted by name, so `Point(x=1, y=2)` and a `Point` declared `(y, x)` holding `y=2, x=1` shared a hash) | @@ -1478,6 +1481,16 @@ compares it with every other input's as it arrives. An input that sends no row o row channel (`Join().async_execute(...)` called directly, outside a job) declares nothing there; in a job the node knows its inputs' types, and both orchestrators refuse. Carrying the declared types over row channels is ITL-1527. +When calling an operator with raw row channels, pass one `stream.pipeline_hash()` +per input occurrence in `input_pipeline_hashes`. A Join with two or more operands +appends `:::` to each operand's system-tag +column names. Recorded jobs feed each declared operand in both orchestrators. +For example, a recorded `Join(a, a)` yields the same system-tag columns as +`Join(a, b)` when `a` and `b` have the same pipeline hash. +For a self-join written before both positions were retained, load-only replay +skips affected rows, a normal run recomputes them, and the saved node's +`as_source()` can still read the original rows. + Item fields that differ only in name or metadata between two inputs' declarations are not refused: both paths give the first input's type (in the join's canonical input order). diff --git a/src/orcapod/core/base.py b/src/orcapod/core/base.py index 0e465f265..1ca4a6955 100644 --- a/src/orcapod/core/base.py +++ b/src/orcapod/core/base.py @@ -6,7 +6,7 @@ from contextlib import contextmanager from contextvars import ContextVar from datetime import datetime, timezone -from typing import Any +from typing import Any, ClassVar import orcapod.contexts as contexts from orcapod.config import DEFAULT_CONFIG, OrcapodConfig @@ -17,6 +17,17 @@ _live_content_hashes: ContextVar[ dict[int, tuple[object, dict[str, ContentHash]]] | None ] = ContextVar("live_content_hashes", default=None) +_pipeline_hash_probe: ContextVar[object] = ContextVar( + "pipeline_hash_probe", default=None +) + + +class _UncachedPipelineHash(Exception): + """Suspend a structural hash until its resolver's upstream is hashed.""" + + def __init__(self, element: PipelineElementBase) -> None: + super().__init__() + self.element = element @contextmanager @@ -131,6 +142,18 @@ class ContentIdentifiableBase(DataContextMixin, ABC): Two content-identifiable objects are considered equal if their `identity_structure` returns the same value. """ + _content_hash_generation: ClassVar[object] = object() + + @staticmethod + def content_hash_generation() -> object: + """Return the generation of state used in capture identities.""" + return ContentIdentifiableBase._content_hash_generation + + @staticmethod + def _invalidate_capture_keys() -> None: + """Invalidate recorded-stream key memos after a lineage or hash change.""" + ContentIdentifiableBase._content_hash_generation = object() + def __init__( self, data_context: str | contexts.DataContext | None = None, @@ -240,6 +263,7 @@ def _invalidate_content_hash_cache(self) -> None: accessing ``_content_hash_cache`` directly. """ self._content_hash_cache.clear() + self._invalidate_capture_keys() self._cached_int_hash = None @@ -287,7 +311,7 @@ def pipeline_hash(self, hasher=None) -> ContentHash: Return the pipeline-level hash of this element, computed from pipeline_identity_structure() and cached by hasher_id. - The hasher is used for the entire recursive computation — all nested + The hasher is used for the entire computation — all nested objects are resolved using the same hasher, ensuring one consistent context per hash computation. @@ -298,17 +322,42 @@ def pipeline_hash(self, hasher=None) -> ContentHash: if hasher is None: hasher = self.data_context.semantic_hasher cache_key = hasher.hasher_id - if cache_key not in self._pipeline_hash_cache: - from orcapod.protocols.hashing_protocols import PipelineElementProtocol - - def pipeline_resolver(obj: Any) -> ContentHash: - if isinstance(obj, PipelineElementProtocol): + cached = self._pipeline_hash_cache.get(cache_key) + if cached is not None: + return cached + if _pipeline_hash_probe.get() is hasher: + raise _UncachedPipelineHash(self) + + from orcapod.protocols.hashing_protocols import PipelineElementProtocol + + def pipeline_resolver(obj: Any) -> ContentHash: + if isinstance(obj, PipelineElementProtocol): + token = _pipeline_hash_probe.set(hasher) + try: return obj.pipeline_hash(hasher) - return obj.content_hash(hasher) + finally: + _pipeline_hash_probe.reset(token) + return obj.content_hash(hasher) - self._pipeline_hash_cache[cache_key] = hasher.hash_object( - self.pipeline_identity_structure(), resolver=pipeline_resolver - ) + pending: list[tuple[PipelineElementBase, Any]] = [ + (self, self.pipeline_identity_structure()) + ] + active = {id(self)} + while pending: + element, structure = pending[-1] + try: + digest = hasher.hash_object(structure, resolver=pipeline_resolver) + except _UncachedPipelineHash as request: + upstream = request.element + identity = id(upstream) + if identity in active: + raise ValueError("Cycle in pipeline hash dependencies") from None + pending.append((upstream, upstream.pipeline_identity_structure())) + active.add(identity) + else: + element._pipeline_hash_cache[cache_key] = digest + active.remove(id(element)) + pending.pop() return self._pipeline_hash_cache[cache_key] def _invalidate_pipeline_hash_cache(self) -> None: diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 81afd792e..0ac6c3293 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -3,22 +3,28 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Callable, Iterator, Mapping +from collections import Counter, defaultdict, deque +from collections.abc import Callable, Iterable, Iterator, Mapping from contextlib import AbstractContextManager, contextmanager from contextvars import ContextVar from dataclasses import dataclass from functools import cached_property from itertools import groupby -from typing import TYPE_CHECKING, ClassVar, final +from typing import TYPE_CHECKING, ClassVar, TypeVar, final from weakref import WeakValueDictionary from orcapod.core.output_bindings import identity_lock, require_current_outputs from orcapod.errors import UnboundSourceError from orcapod.protocols.hashing_protocols import IdentityChains from orcapod.types import ContentHash +from orcapod.types.argument_groups import SymmetricGroup if TYPE_CHECKING: - from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol + from orcapod.protocols.core_protocols import ( + ArgumentGroup, + PodProtocol, + StreamProtocol, + ) from orcapod.protocols.hashing_protocols import ( ContentIdentifiableProtocol, IdentityChainProtocol, @@ -159,81 +165,109 @@ class _SymmetricInputs: _ChainHasher = Callable[[str, _ChainEntry, tuple[ContentHash, ...]], ContentHash] +_GroupValue = TypeVar("_GroupValue") + + +def _argument_children(group: ArgumentGroup) -> Iterable[ArgumentGroup] | None: + """Return the immediate children of an argument group.""" + if isinstance(group, SymmetricGroup): + return group.members + if isinstance(group, (tuple, frozenset)): + return group + return None + + +def _transform_argument_group( + group: ArgumentGroup, + leaf: Callable[[ArgumentGroup], _GroupValue], + combine: Callable[[ArgumentGroup, list[_GroupValue]], _GroupValue], +) -> _GroupValue: + """Transform occurrences bottom-up, retaining the order of each group's children.""" + pending: list[tuple[ArgumentGroup, int | None]] = [(group, None)] + values: list[_GroupValue] = [] + while pending: + node, start = pending.pop() + if start is not None: + value = combine(node, values[start:]) + del values[start:] + values.append(value) + continue + children = _argument_children(node) + if children is None: + values.append(leaf(node)) + else: + pending.append((node, len(values))) + pending.extend((child, None) for child in reversed(tuple(children))) + return values[0] + + +def structural_argument_group( + inputs: tuple[StreamProtocol, ...], group: ArgumentGroup +) -> ArgumentGroup: + """Read a symmetry declaration without losing argument occurrences. + + A flat legacy set declares that all inputs commute. Nested declarations + must express each occurrence explicitly, since a missing nested group + cannot be reconstructed from the surviving members. + """ + positions = Counter(map(id, inputs)) + if isinstance(group, frozenset) and all( + id(member) in positions for member in group + ): + return SymmetricGroup(inputs) + + pending = [group] + occurrences: Counter[int] = Counter() + while pending: + node = pending.pop() + children = _argument_children(node) + if children is None: + occurrences[id(node)] += 1 + else: + pending.extend(children) + + if occurrences != positions: + raise ValueError("argument_symmetry must describe every argument occurrence") + return group + + +def structural_argument_symmetry( + pod: PodProtocol, inputs: tuple[StreamProtocol, ...] +) -> ArgumentGroup: + """Read the argument occurrences used by all three identity chains.""" + from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod + + if isinstance(pod, StaticOutputOperatorPod): + return pod.structural_argument_symmetry(inputs) + return pod.argument_symmetry(inputs) + + +def pipeline_argument_group( + pod: PodProtocol, inputs: tuple[StreamProtocol, ...] +) -> ArgumentGroup: + """Keep all input occurrences in the structural preimage.""" + return structural_argument_group(inputs, structural_argument_symmetry(pod, inputs)) + + def encode_input_symmetry( - inputs: tuple[StreamProtocol, ...], - symmetry: Callable[[tuple[StreamProtocol, ...]], ArgumentGroup], -) -> tuple[InputSymmetry | None, bool]: - """Encode argument positions and report whether a symmetric group lost inputs.""" + inputs: tuple[StreamProtocol, ...], group: ArgumentGroup +) -> InputSymmetry: + """Encode each argument occurrence as a position in the symmetry tree.""" if len(inputs) < 2: - return None, False - - remaining = dict(enumerate(inputs)) - symmetric: list[tuple[ArgumentGroup, InputSymmetry, list[InputSymmetry]]] = [] - - def encode( - group: ArgumentGroup, available: dict[int, StreamProtocol], *, repeat: bool - ) -> InputSymmetry: - if isinstance(group, tuple): - return [encode(child, available, repeat=repeat) for child in group] - if isinstance(group, frozenset): - children: list[InputSymmetry] = [] - for child in group: - position = encode(child, available, repeat=repeat) - children.append(position) - if not repeat: - symmetric.append((child, position, children)) - return _SymmetricInputs(children) - index = next( - (index for index, stream in available.items() if stream is group), None - ) - if index is None and repeat: - index = next( - (index for index, stream in available.items() if stream == group), - None, - ) - if index is not None: - del available[index] - return index - raise ValueError("argument_symmetry did not group arguments by occurrence") + return list(range(len(inputs))) - group = symmetry(inputs) - try: - grouped = encode(group, remaining, repeat=False) - except ValueError: - # Use argument order when the callback does not return the input streams. - return None, False - - collapsed = bool(remaining and symmetric) - # A frozenset can collapse an equal leaf or an entire equal subgroup. - # Keep the standalone chains' existing fallback. This can recover repeats, - # but cannot recover the order of equal inputs within a missing subgroup. - if remaining: - members = [ - (child, siblings, _input_positions(encoded)) - for child, encoded, siblings in symmetric - ] - members.sort( - key=lambda member: (-len(member[2]), min(member[2], default=len(inputs))) - ) - for child, siblings, positions in members: - while positions and len(remaining) >= len(positions): - available = remaining.copy() - try: - siblings.append(encode(child, available, repeat=True)) - except ValueError: - break - remaining = available - if remaining: - return None, collapsed - return (None if grouped == list(range(len(inputs))) else grouped), collapsed - - -def _input_positions(group: InputSymmetry) -> tuple[int, ...]: - """Return every explicit position in a grouping.""" - if isinstance(group, int): - return (group,) - children = group.children if isinstance(group, _SymmetricInputs) else group - return tuple(index for child in children for index in _input_positions(child)) + group = structural_argument_group(inputs, group) + remaining: dict[int, deque[int]] = defaultdict(deque) + for index, stream in enumerate(inputs): + remaining[id(stream)].append(index) + + def position(node: ArgumentGroup) -> InputSymmetry: + return remaining[id(node)].popleft() + + def encode(node: ArgumentGroup, children: list[InputSymmetry]) -> InputSymmetry: + return children if isinstance(node, tuple) else _SymmetricInputs(children) + + return _transform_argument_group(group, position, encode) def _has_symmetric_group(group: InputSymmetry) -> bool: @@ -305,12 +339,6 @@ def _pool_group( ) -def _require_complete_symmetry(chains: IdentityChains) -> None: - """Refuse to combine chains if a commutative ancestor lost input order.""" - if chains.collapsed_input_symmetry: - raise ValueError("A commutative group dropped content-equal inputs (ITL-1590).") - - class IdentityChainsMixin(ABC): """Memoize chains per node and invalidate descendants of a changed slot.""" @@ -488,9 +516,11 @@ def hash_chain( upstreams = tuple(walk.visit(stream) for stream in inputs) # Symmetric groups use structural ordering. Occurrences keep repeats. - group, collapsed = encode_input_symmetry(inputs, self._identity_symmetry) - if group is None: - group = list[InputSymmetry](range(len(inputs))) + group = ( + encode_input_symmetry(inputs, self._identity_symmetry(inputs)) + if len(inputs) >= 2 + else list[InputSymmetry](range(len(inputs))) + ) from orcapod.hashing.semantic_hashing.semantic_hasher import ( canonical_json, nested_hash, @@ -522,8 +552,6 @@ def hash_chain( frozenset( name for upstream in upstreams for name in upstream.unbound_slots ), - collapsed_input_symmetry=collapsed - or any(upstream.collapsed_input_symmetry for upstream in upstreams), ) def source_chain(self) -> ContentHash: @@ -547,12 +575,7 @@ def source_chain(self) -> ContentHash: return chains.sources def name_chain(self) -> ContentHash: - """Return the chain of source-slot names. - - Raises: - ValueError: If legacy symmetry needs an unavailable input digest, - such as for a Join over a cold polling source in step 1. - """ + """Return the chain of source-slot names.""" with self._identity_lock, _identity_read(): return ( IdentityWalk(self._identity_hasher, include_sources=False) @@ -585,13 +608,7 @@ def content_hash(self, hasher: SemanticHasherProtocol | None = None) -> ContentH ) def node_hash(self) -> ContentHash: - """Combine structure and slot names. - - Raises: - ValueError: If a commutative group dropped content-equal inputs - (ITL-1590) or legacy symmetry needs an unavailable input digest, - such as for a Join over a cold polling source in step 1. - """ + """Combine structure and slot names.""" with _identity_read(): return self._name_based_hash() @@ -600,8 +617,6 @@ def _name_based_hash(self) -> ContentHash: with self._identity_lock: walk = IdentityWalk(self._identity_hasher, include_sources=False) chains = walk.visit(self) - if reading_identity_chains(): - _require_complete_symmetry(chains) structure = chains.node_pipeline_hash or chains.pipeline_hash return self._identity_hash( NODE_HASH_LABEL, (structure(walk.hasher), chains.names) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 9facc8dc3..315c3a5af 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -588,6 +588,7 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: with self._identity_lock: self._input_stream = value[0] invalidate_output_lineage() + self._invalidate_capture_keys() self._invalidate_identity_chains(names=True) self._forget_output_schema() diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 5cce26591..007e1cd20 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -21,7 +21,7 @@ import sys import logging from abc import abstractmethod -from collections.abc import Collection, Iterator, Mapping, Sequence +from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence from datetime import datetime, timezone from typing import TYPE_CHECKING, Any, Literal, cast @@ -40,7 +40,10 @@ ) from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel from orcapod.config import OrcapodConfig -from orcapod.core.identity_chains import require_builtin_operator_identity +from orcapod.core.identity_chains import ( + pipeline_argument_group, + require_builtin_operator_identity, +) from orcapod.core.output_bindings import ( capture_output_bindings, invalidate_output_lineage, @@ -204,6 +207,24 @@ def job_input_stream( return reader.stream if type(reader) is _InputTap else None +def ordered_operator_inputs(node: Any, predecessors: Iterable[Any]) -> list[Any]: + """Resolve each declared operand position to its execution predecessor.""" + upstreams: tuple[StreamProtocol, ...] = node.upstreams + # Graph adjacency merges equal nodes, including distinct slots bound to one + # source. Keep the declared slots for rebinding and serialization, and feed + # their shared graph predecessor once per operand position during execution. + occurrences: dict[StreamProtocol, list[int]] = {} + for index, upstream in enumerate(upstreams): + occurrences.setdefault(upstream, []).append(index) + ranked = [ + (index, predecessor) + for predecessor in predecessors + for index in occurrences.get(predecessor, [0]) + ] + ranked.sort(key=lambda pair: pair[0]) + return [predecessor for _, predecessor in ranked] + + # --------------------------------------------------------------------------- # OperatorNodeBase — shared base (no DB) # --------------------------------------------------------------------------- @@ -305,6 +326,14 @@ def load_status(self) -> Any: def identity_structure(self) -> Any: return self.pipeline_identity_structure() + def pipeline_identity_structure(self) -> Any: + require_current_outputs(*self._identity_inputs()) + require_builtin_operator_identity(self._operator) + return ( + self._operator, + pipeline_argument_group(self._operator, self._input_streams), + ) + def _identity_leaf(self, walk: IdentityWalkProtocol) -> None: """Require the operator's grouping unless the saved unary form suffices.""" if self._operator is not None: @@ -334,11 +363,6 @@ def _identity_leaf(self, walk: IdentityWalkProtocol) -> None: "does not carry input symmetry yet and the operator is unavailable." ) - def pipeline_identity_structure(self) -> Any: - require_current_outputs(*self._identity_inputs()) - require_builtin_operator_identity(self._operator) - return (self._operator, self._operator.argument_symmetry(self._input_streams)) - # ------------------------------------------------------------------ # Read-only overrides (for deserialized nodes without live operator) # ------------------------------------------------------------------ @@ -414,6 +438,7 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: with self._identity_lock: self._input_streams = value invalidate_output_lineage() + self._invalidate_capture_keys() self._invalidate_identity_chains(names=True) self._forget_output_schema() diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py index 870b75784..1fd6a554d 100644 --- a/src/orcapod/core/operators/join.py +++ b/src/orcapod/core/operators/join.py @@ -51,6 +51,7 @@ ) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, ContentHash, DataType, Schema +from orcapod.types.argument_groups import SymmetricGroup from orcapod.utils import arrow_utils, schema_utils # The row-number columns of the frames Polars joins (``_inner_join``); a tag, so a @@ -377,14 +378,18 @@ def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None: raise InputValidationError(f"Input streams are not compatible: {e}") from e def order_input_streams(self, *streams: StreamProtocol) -> list[StreamProtocol]: - # Canonically order by pipeline_hash for deterministic operation. - # pipeline_hash is structure-only, so streams with the same schema+topology - # get the same ordering regardless of data content. + # Canonically order by structure, retaining input order within ties. return sorted(streams, key=lambda s: s.pipeline_hash().to_hex()) def argument_symmetry(self, streams: Collection) -> ArgumentGroup: return frozenset(streams) + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] + ) -> ArgumentGroup: + """Declare every interchangeable occurrence without comparing the streams.""" + return SymmetricGroup(streams) + def output_schema( self, *streams: StreamProtocol, @@ -966,8 +971,8 @@ async def async_execute( output: Writable channel for downstream. input_pipeline_hashes: Pipeline hash for each input, positionally matching ``inputs``. With 2+ inputs, each input's - system-tag columns are renamed after its hash, as on the sync - path. + system-tag columns are renamed after its hash and canonical + position, as on the sync path. Include every input occurrence. Raises: ValueError: If ``input_pipeline_hashes`` does not have one hash per input. diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index dcfa2a89f..471f8e781 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -36,6 +36,7 @@ ) from orcapod.core.function_pod import FunctionPodStream from orcapod.core.identity_chains import ( + pipeline_argument_group, refuse_identity_io, require_builtin_operator_identity, ) @@ -285,6 +286,12 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou """ ... + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] + ) -> ArgumentGroup: + """Declare argument occurrences for structural identities.""" + return self.argument_symmetry(streams) + @abstractmethod def output_schema( self, @@ -1831,13 +1838,7 @@ def pipeline_hash(self, hasher=None) -> ContentHash: return super().pipeline_hash(hasher) def identity_structure(self) -> Any: - require_current_outputs(*self._upstreams) - require_builtin_operator_identity(self._pod) - self._pod._note_provisional_identity_use() # a direct read is a use (ITL-1279) - structure = (self._pod,) - if self._upstreams: - structure += (self._pod.argument_symmetry(self._upstreams),) - return structure + return self.pipeline_identity_structure() def pipeline_identity_structure(self) -> Any: require_current_outputs(*self._upstreams) @@ -1845,7 +1846,7 @@ def pipeline_identity_structure(self) -> Any: self._pod._note_provisional_identity_use() # a direct read is a use (ITL-1279) structure = (self._pod,) if self._upstreams: - structure += (self._pod.argument_symmetry(self._upstreams),) + structure += (pipeline_argument_group(self._pod, self._upstreams),) return structure @property diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 7dc4afb68..916afcf81 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -33,6 +33,8 @@ from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names from orcapod.core.identity_chains import ( + pipeline_argument_group, + structural_argument_symmetry, IdentityChainsMixin, graph_hash, reading_identity_chains, @@ -773,7 +775,11 @@ def _identity_inputs(self) -> tuple[StreamProtocol, ...]: def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: """Respect the producer's symmetry, or the input order with no producer.""" producer = self.producer - return inputs if producer is None else producer.argument_symmetry(inputs) + return ( + inputs + if producer is None + else structural_argument_symmetry(producer, inputs) + ) def _identity_leaf( self, walk: IdentityWalkProtocol @@ -810,22 +816,29 @@ def producer(self) -> PodProtocol | None: ... def upstreams(self) -> tuple[StreamProtocol, ...]: ... def identity_structure(self) -> Any: + producer = self._identity_producer() + if producer is None: + raise NotImplementedError("StreamBase.identity_structure") + return producer, producer.argument_symmetry(self.upstreams) + + def _identity_producer(self) -> PodProtocol | None: + """Return the producer when its identity is available.""" require_current_outputs(self) producer = self.producer - if producer is not None: - if reading_identity_chains(): - from orcapod.core.operators.static_output_pod import ( - StaticOutputOperatorPod, - ) - - if isinstance(producer, StaticOutputOperatorPod): - require_builtin_operator_identity(producer) - return (producer, producer.argument_symmetry(self.upstreams)) + if producer is not None and reading_identity_chains(): + from orcapod.core.operators.static_output_pod import ( + StaticOutputOperatorPod, + ) - raise NotImplementedError("StreamBase.identity_structure") + if isinstance(producer, StaticOutputOperatorPod): + require_builtin_operator_identity(producer) + return producer def pipeline_identity_structure(self) -> Any: - return self.identity_structure() + producer = self._identity_producer() + if producer is None: + return self.identity_structure() + return producer, pipeline_argument_group(producer, self.upstreams) @property def is_stale(self) -> bool: diff --git a/src/orcapod/hashing/semantic_hashing/semantic_hasher.py b/src/orcapod/hashing/semantic_hashing/semantic_hasher.py index 3f692f801..d4feb756e 100644 --- a/src/orcapod/hashing/semantic_hashing/semantic_hasher.py +++ b/src/orcapod/hashing/semantic_hashing/semantic_hasher.py @@ -89,6 +89,7 @@ ) from orcapod.protocols import hashing_protocols as hp from orcapod.types import ContentHash +from orcapod.types.argument_groups import SymmetricGroup from orcapod.utils.canonical_type_names import ( canonical_module_name, canonical_type_name, @@ -405,16 +406,19 @@ def _expand_structure( ], } - if isinstance(obj, (set, frozenset)): + if isinstance(obj, (set, frozenset, SymmetricGroup)): + members = obj.members if isinstance(obj, SymmetricGroup) else obj expanded_items = [ - self._expand_element(item, _visited, resolver=resolver) for item in obj + self._expand_element(item, _visited, resolver=resolver) + for item in members ] # Sort by each item's canonical JSON text: a total order that never # ties two distinct items ({1, "1"} sorts as [1, "1"]), so the order, # and the hash, never depend on set iteration order (PYTHONHASHSEED). # A frozenset is a type of its own (ITL-1154): tagged apart from set. return { - "__type__": "frozenset" if isinstance(obj, frozenset) else "set", + # Preserve the historical group encoding, including repeated items. + "__type__": "set" if isinstance(obj, set) else "frozenset", "items": sorted(expanded_items, key=canonical_json), } @@ -591,7 +595,7 @@ def canonical_json(obj: Any) -> str: def _is_structure(obj: Any) -> bool: """Return True if *obj* is a container type handled by _expand_structure.""" - return isinstance(obj, (list, tuple, dict, set, frozenset, Mapping)) + return isinstance(obj, (list, tuple, dict, set, frozenset, Mapping, SymmetricGroup)) def _is_namedtuple(obj: Any) -> bool: diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py index 7a5bd4b65..a83d789be 100644 --- a/src/orcapod/pipeline/async_orchestrator.py +++ b/src/orcapod/pipeline/async_orchestrator.py @@ -211,6 +211,7 @@ async def _run_async( held_rows: Mapping[Any, list[tuple[TagProtocol, DataProtocol]]] | None = None, ) -> OrchestratorResult: """Core async logic: wire channels, launch tasks, collect results.""" + from orcapod.core.nodes.operator_node import ordered_operator_inputs from orcapod.core.operators.static_output_pod import ( rows_on_read, ) @@ -229,26 +230,32 @@ async def _run_async( buf = self._buffer_size # Build edge maps - out_edges: dict[Any, list[Any]] = defaultdict(list) in_edges: dict[Any, list[Any]] = defaultdict(list) for upstream_node, downstream_node in graph.edges(): - out_edges[upstream_node].append(downstream_node) in_edges[downstream_node].append(upstream_node) + out_edges: dict[Any, list[tuple[Any, int]]] = defaultdict(list) + for node, predecessors in in_edges.items(): + if is_operator_node(node): + predecessors = in_edges[node] = ordered_operator_inputs( + node, predecessors + ) + for position, upstream in enumerate(predecessors): + out_edges[upstream].append((node, position)) # Create channels for each edge node_output_channels: dict[Any, Channel | BroadcastChannel] = {} - edge_readers: dict[tuple[Any, Any], Any] = {} + edge_readers: dict[tuple[Any, int], Any] = {} for node, downstreams in out_edges.items(): if len(downstreams) == 1: ch = Channel(buffer_size=buf) node_output_channels[node] = ch - edge_readers[(node, downstreams[0])] = ch.reader + edge_readers[downstreams[0]] = ch.reader else: bch = BroadcastChannel(buffer_size=buf) node_output_channels[node] = bch for ds in downstreams: - edge_readers[(node, ds)] = bch.add_reader() + edge_readers[ds] = bch.add_reader() # Terminal nodes need sink channels terminal_channels: list[Channel] = [] @@ -286,8 +293,8 @@ def collected_output( # Not run: the rows of its current run feed its successors. Its # own inputs are read and discarded, so no producer blocks on # a channel nobody reads. - for upstream in in_edges.get(node, []): - tg.create_task(_drain(edge_readers[(upstream, node)])) + for position in range(len(in_edges.get(node, []))): + tg.create_task(_drain(edge_readers[(node, position)])) _start_node( tg, failed_nodes, @@ -308,7 +315,7 @@ def collected_output( raise ValueError( f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}" ) - input_reader = edge_readers[(predecessors[0], node)] + input_reader = edge_readers[(node, 0)] _start_node( tg, failed_nodes, @@ -324,16 +331,9 @@ def collected_output( ) elif is_operator_node(node): predecessors = in_edges.get(node, []) - # Sort by node.upstreams order for non-commutative operators - upstream_order = { - id(s): i for i, s in enumerate(node.upstreams) - } - sorted_preds = sorted( - predecessors, - key=lambda p: upstream_order.get(id(p), 0), - ) input_readers = [ - edge_readers[(upstream, node)] for upstream in sorted_preds + edge_readers[(node, position)] + for position in range(len(predecessors)) ] _start_node( tg, @@ -352,7 +352,7 @@ def collected_output( raise ValueError( "SideEffectNode expects exactly 1 upstream, got 0" ) - input_reader = edge_readers[(predecessors[0], node)] + input_reader = edge_readers[(node, 0)] # In a load-only run the node passes its rows on and delivers # nothing. _start_node( diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py index 08a72bed9..a65c271dc 100644 --- a/src/orcapod/pipeline/base.py +++ b/src/orcapod/pipeline/base.py @@ -4,12 +4,15 @@ import logging from abc import ABC, abstractmethod -from collections.abc import Callable, Hashable, Iterable, Iterator +from collections import ChainMap +from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping from dataclasses import dataclass from functools import partial from itertools import chain from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast +from weakref import ReferenceType, ref +from orcapod.core.base import ContentIdentifiableBase from orcapod.core.identity_chains import graph_hash from orcapod.core.nodes.function_node import FunctionNodeBase from orcapod.core.tracker import AutoRegisteringContextBasedTracker @@ -35,6 +38,7 @@ from orcapod.types.provenance import Highlight from orcapod.protocols.database_protocols import ArrowDatabaseProtocol from orcapod.pipeline.source_consistency import SourceUse + from orcapod.pipeline.pod_invocation import CaptureStreamKeys from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.hashing_protocols import IdentityChainProtocol else: @@ -137,8 +141,10 @@ def __init__( self._name: tuple[str, ...] = (name,) if isinstance(name, str) else tuple(name) # --- Additive recording state (never cleared) ----------------- - # Maps content-hash-string → PodInvocation for each recorded invocation. + # Maps capture key → PodInvocation for each recorded invocation. self._invocation_lut: dict[str, PodInvocation] = {} + self._capture_key_generation = ContentIdentifiableBase.content_hash_generation() + self._capture_stream_keys: dict[int, CaptureStreamKeys] = {} # Ordered graph keys chosen at capture, which stay fixed across rebindings. self._invocation_input_keys: dict[str, tuple[str, ...]] = {} # Maps content-hash-string → raw stream for each unregistered upstream. @@ -326,7 +332,7 @@ def record_side_effect_pod_invocation( def _record_invocation(self, invocation: PodInvocation) -> None: """Validate the invocation and record it immediately.""" - key, input_keys = self._validate_invocation(invocation) + key, input_keys = self._validate_invocation(invocation, remember_streams=True) self._remember_invocation(key, invocation, input_keys) self._hash_graph.add_node(key) for upstream, upstream_hash in zip( @@ -356,7 +362,7 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: return partial(self._record_invocation, invocation) def _validate_invocation( - self, invocation: PodInvocation + self, invocation: PodInvocation, *, remember_streams: bool = False ) -> tuple[str, tuple[str, ...]]: """Check whether a capture can be recorded and resolve its graph keys. @@ -384,8 +390,10 @@ def _validate_invocation( self._validate_capture_sources(inputs) uses = tuple(self._source_uses(invocation)) require_live_source_bindings(stream for _, stream in uses) - key = graph_hash(invocation).to_string() - input_keys = tuple(self._input_graph_key(upstream) for upstream in inputs) + capture_streams = self._capture_key_memo() + key, input_keys = invocation.capture_keys( + capture_streams, self._input_graph_key + ) # Checked before anything is recorded, so a refused invocation leaves the # graph as it was. A restriction does not change a source's identity, so the # pipeline keeps one restriction (or none) per source identity, whatever @@ -395,12 +403,50 @@ def _validate_invocation( require_consistent_sources(uses) require_one_restriction(stream for _, stream in uses) + if remember_streams: + self._remember_capture_stream_keys(capture_streams.maps[0]) return key, input_keys def _input_graph_key(self, upstream: StreamProtocol) -> str: """Return the capture graph key for an invocation input.""" return graph_hash(upstream).to_string() + def _capture_key_memo(self) -> ChainMap[int, CaptureStreamKeys]: + """Reuse upstream keys until binding or upstream invalidation.""" + generation = ContentIdentifiableBase.content_hash_generation() + if self._capture_key_generation is not generation: + self._capture_stream_keys.clear() + self._capture_key_generation = generation + # Stage new entries until validation succeeds. + return ChainMap({}, self._capture_stream_keys) + + def _remember_capture_stream_keys( + self, keys: Mapping[int, CaptureStreamKeys] + ) -> None: + """Memoize keys without holding on to streams that coalesced at capture.""" + owner = ref(self) + for identity, (stream, key) in keys.items(): + if isinstance(stream, ReferenceType): + continue + + def discard( + dead: ReferenceType[StreamProtocol], *, identity: int = identity + ) -> None: + graph = owner() + if graph is not None: + memo = graph._capture_stream_keys + if (current := memo.get(identity)) is not None and current[ + 0 + ] is dead: + del memo[identity] + + try: + stream_ref = ref(stream, discard) + except TypeError: + # A third-party stream can implement the protocol without weak refs. + continue + self._capture_stream_keys[identity] = (stream_ref, key) + def _remember_invocation( self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...] ) -> None: @@ -866,13 +912,16 @@ def from_invocations( require_live_source_bindings(inputs) require_consistent_sources(invocation_source_uses(graph.invocations)) instance._source_streams = dict(graph.source_streams) + capture_streams = instance._capture_key_memo() for inv in graph.invocations: - key = graph_hash(inv).to_string() - input_keys = tuple(graph_hash(up).to_string() for up in inv.input_streams) + key, input_keys = inv.capture_keys( + capture_streams, instance._input_graph_key + ) instance._remember_invocation(key, inv, input_keys) instance._hash_graph.add_node(key) for input_key in input_keys: instance._hash_graph.add_edge(input_key, key) + instance._remember_capture_stream_keys(capture_streams.maps[0]) # 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/graph.py b/src/orcapod/pipeline/graph.py index dee62cbaa..7bfe340e8 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -706,6 +706,8 @@ def _clone_for_execution(self) -> "Pipeline": # Shared read-only structural state (recording + compiled) clone._name = self._name clone._invocation_lut = self._invocation_lut + clone._capture_key_generation = self._capture_key_generation + clone._capture_stream_keys = {} clone._invocation_input_keys = self._invocation_input_keys clone._source_streams = self._source_streams clone._node_lut = self._node_lut diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py index acad141fe..d7d394f90 100644 --- a/src/orcapod/pipeline/pod_invocation.py +++ b/src/orcapod/pipeline/pod_invocation.py @@ -1,24 +1,29 @@ """PodInvocation — minimal recording primitives for pipeline invocations. These lightweight value objects capture a pod-plus-streams invocation at -recording time. Their ``content_hash()`` is structurally identical to the -corresponding compiled node's ``content_hash()``, which means the same hash -key can be used in both ``_invocation_lut`` and ``_persistent_node_map``. +recording time. Bound capture keys use the structure and source chain, +and unbound capture keys use the structure and name chain. """ from __future__ import annotations from typing import TYPE_CHECKING, Any +from weakref import ReferenceType from orcapod.contexts import resolve_context from orcapod.core.base import ContentIdentifiableBase, PipelineElementBase from orcapod.core.output_bindings import require_current_outputs from orcapod.core.identity_chains import ( + graph_hash, + pipeline_argument_group, + structural_argument_symmetry, IdentityChainsMixin, require_builtin_operator_identity, ) if TYPE_CHECKING: + from collections.abc import Callable, MutableMapping + from orcapod.protocols.core_protocols import ( ArgumentGroup, FunctionPodProtocol, @@ -30,16 +35,16 @@ from orcapod.types import ContentHash +CaptureStreamKeys = tuple["StreamProtocol | ReferenceType[StreamProtocol]", str] + + class PodInvocation( # pyright: ignore[reportUnsafeMultipleInheritance] # Both hash bases use cooperative super().__init__. ContentIdentifiableBase, PipelineElementBase, IdentityChainsMixin ): """Abstract recording primitive for a pod applied to input streams. - ``PodInvocation.identity_structure()`` returns - ``(pod, pod.argument_symmetry(input_streams))``, which mirrors - ``StreamBase.identity_structure()`` and therefore guarantees that the - hash of a ``PodInvocation`` equals the hash of the corresponding - compiled node (``FunctionNode`` / ``OperatorNode``). + Its identity follows the pod and each argument occurrence, as on the + corresponding compiled node. Args: pod: The pod being invoked (function or operator). @@ -94,7 +99,7 @@ def _identity_inputs(self) -> tuple[StreamProtocol, ...]: def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: """Respect the recorded pod's argument symmetry.""" - return self._pod.argument_symmetry(inputs) + return structural_argument_symmetry(self._pod, inputs) def pipeline_hash( self, hasher: SemanticHasherProtocol | None = None @@ -110,19 +115,45 @@ def content_hash(self, hasher: SemanticHasherProtocol | None = None) -> ContentH return IdentityChainsMixin.content_hash(self, hasher) def identity_structure(self) -> Any: - """Return ``(pod, pod.argument_symmetry(input_streams))``. + return self.pipeline_identity_structure() - This matches the identity structure of the corresponding compiled - node, ensuring hash equality between invocation and node. - """ + def pipeline_identity_structure(self) -> Any: + """Return the pod and its complete structural argument group.""" require_current_outputs(*self._input_streams) if isinstance(self, OperatorInvocation): require_builtin_operator_identity(self._pod) - return (self._pod, self._pod.argument_symmetry(self._input_streams)) + return ( + self._pod, + pipeline_argument_group(self._pod, self._input_streams), + ) - def pipeline_identity_structure(self) -> Any: - """Return same as ``identity_structure()``.""" - return self.identity_structure() + def capture_keys( + self, + streams: MutableMapping[int, CaptureStreamKeys], + input_key: Callable[[StreamProtocol], str], + ) -> tuple[str, tuple[str, ...]]: + """Compute graph keys bottom-up so deep captures stay stack-safe.""" + pending = [(stream, False) for stream in reversed(self.input_streams)] + while pending: + stream, expanded = pending.pop() + stream_id = id(stream) + if (previous := streams.get(stream_id)) is not None: + owner = previous[0] + if (owner() if isinstance(owner, ReferenceType) else owner) is stream: + continue + if ( + not expanded + and stream.producer is not None + and (inputs := stream.upstreams) + ): + pending.append((stream, True)) + pending.extend((upstream, False) for upstream in reversed(inputs)) + continue + streams[stream_id] = (stream, input_key(stream)) + + return graph_hash(self).to_string(), tuple( + streams[id(stream)][1] for stream in self.input_streams + ) class FunctionInvocation(PodInvocation): diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py index ae3de57b1..bfb2c51ac 100644 --- a/src/orcapod/pipeline/restrictions.py +++ b/src/orcapod/pipeline/restrictions.py @@ -187,13 +187,14 @@ def sources_read( from orcapod.core.sources.base import RootSource found: list[tuple[str, str, Restriction | None]] = [] - visited: list[StreamProtocol] = [] + visited: dict[int, StreamProtocol] = {} pending = list(streams) while pending: current = pending.pop() - if any(current is seen for seen in visited): + identity = id(current) + if identity in visited: continue - visited.append(current) + visited[identity] = current if isinstance(current, RootSource) and current.live_source_inputs is None: found.append( ( diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py index 3286caab7..5167ea901 100644 --- a/src/orcapod/pipeline/sync_orchestrator.py +++ b/src/orcapod/pipeline/sync_orchestrator.py @@ -193,15 +193,11 @@ def _ordered_inputs( outputs: dict[Any, StreamProtocol], ) -> list[StreamProtocol]: """The output streams of an operator node's predecessors, in ``node.upstreams`` order.""" - predecessors = list(graph.predecessors(node)) - upstream_order = {id(upstream): i for i, upstream in enumerate(node.upstreams)} - sorted_preds = sorted( - predecessors, - key=lambda p: upstream_order.get(id(p), 0), - ) + from orcapod.core.nodes.operator_node import ordered_operator_inputs from orcapod.core.operators.static_output_pod import at_edge - return [at_edge(outputs[p]) for p in sorted_preds] + predecessors = ordered_operator_inputs(node, graph.predecessors(node)) + return [at_edge(outputs[p]) for p in predecessors] @staticmethod def _release_built_inputs( diff --git a/src/orcapod/protocols/core_protocols/pod.py b/src/orcapod/protocols/core_protocols/pod.py index 4a8b0a582..4b8c41cac 100644 --- a/src/orcapod/protocols/core_protocols/pod.py +++ b/src/orcapod/protocols/core_protocols/pod.py @@ -7,10 +7,10 @@ from orcapod.protocols.core_protocols.traceable import TraceableProtocol from orcapod.types import ColumnConfig, Schema -# Core recursive types -ArgumentGroup: TypeAlias = "SymmetricGroup | OrderedGroup | StreamProtocol" +from orcapod.types.argument_groups import SymmetricGroup -SymmetricGroup: TypeAlias = frozenset[ArgumentGroup] # Order-independent +# Core recursive types +ArgumentGroup: TypeAlias = "SymmetricGroup[ArgumentGroup] | frozenset[ArgumentGroup] | OrderedGroup | StreamProtocol" OrderedGroup: TypeAlias = tuple[ArgumentGroup, ...] # Order-dependent @@ -70,7 +70,7 @@ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGrou Describe symmetry/ordering constraints on input arguments. Returns a structure encoding which arguments can be reordered: - - SymmetricGroup (frozenset): Arguments commute (order doesn't matter) + - frozenset: Arguments commute (order doesn't matter) - OrderedGroup (tuple): Arguments have fixed positions - Nesting expresses partial symmetry diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index a7423d10d..8995daa42 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -16,8 +16,8 @@ class IdentityChains: """The three chains of one element. - An unbound slot leaves sources absent. Collapsed symmetry invalidates the - combined hashes. A source leaf also holds its binding digest before chain hashing. + An unbound slot leaves sources absent. A source leaf also holds its binding + digest before chain hashing. """ pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] @@ -25,7 +25,6 @@ class IdentityChains: names: ContentHash unbound_slots: frozenset[str] = frozenset() node_pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] | None = None - collapsed_input_symmetry: bool = False leaf_source: ContentHash | None = None @@ -52,12 +51,7 @@ def source_chain(self) -> ContentHash: ... def name_chain(self) -> ContentHash: - """Return the chain of source-slot names. - - Raises: - ValueError: If legacy symmetry needs an unavailable input digest, - such as for a Join over a cold polling source in step 1. - """ + """Return the chain of source-slot names.""" ... def content_hash(self, hasher: SemanticHasherProtocol | None = None) -> ContentHash: @@ -69,14 +63,7 @@ def content_hash(self, hasher: SemanticHasherProtocol | None = None) -> ContentH ... def node_hash(self) -> ContentHash: - """Combine structure and slot names. - - Raises: - ValueError: If a commutative group dropped content-equal inputs - (ITL-1590), which can also occur in an unbound pipeline, or - legacy symmetry needs an unavailable input digest, such as for - a Join over a cold polling source in step 1. - """ + """Combine structure and slot names.""" ... def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: diff --git a/src/orcapod/types/argument_groups.py b/src/orcapod/types/argument_groups.py new file mode 100644 index 000000000..a61845329 --- /dev/null +++ b/src/orcapod/types/argument_groups.py @@ -0,0 +1,26 @@ +"""Multiplicity-preserving argument groups for commutative operators.""" + +from __future__ import annotations + +from collections import Counter +from dataclasses import dataclass +from typing import Generic, TypeVar + +_T_co = TypeVar("_T_co", covariant=True) + + +@dataclass(frozen=True, slots=True, eq=False) +class SymmetricGroup(Generic[_T_co]): + """A list of interchangeable occurrences, with repeats preserved.""" + + members: tuple[_T_co, ...] + + def __eq__(self, other: object) -> bool: + """Compare argument multiplicities without comparing their positions.""" + if not isinstance(other, SymmetricGroup): + return NotImplemented + return Counter(self.members) == Counter(other.members) + + def __hash__(self) -> int: + """Keep groups hashable for nested declarations.""" + return hash(frozenset(Counter(self.members).items())) diff --git a/tests/test_channels/test_polling_source.py b/tests/test_channels/test_polling_source.py index 71d0f5c01..1cf067744 100644 --- a/tests/test_channels/test_polling_source.py +++ b/tests/test_channels/test_polling_source.py @@ -1866,10 +1866,10 @@ def unexpected_callback(*_args: object, **_kwargs: object) -> None: assert stream.content_hash() -def test_join_name_and_node_hashes_use_warm_polling_digest( +def test_join_name_and_node_hashes_do_not_need_polling_digest( monkeypatch: pytest.MonkeyPatch, ) -> None: - """A cold Join refuses legacy symmetry, but job binding warms the digest.""" + """A cold Join uses only the polling stream's declared structure.""" from orcapod import PipelineJob, SourceNode from orcapod.databases import InMemoryArrowDatabase from orcapod.operators import Join @@ -1902,9 +1902,8 @@ def unexpected_callback(*_args: object, **_kwargs: object) -> None: with monkeypatch.context() as guard: for method in ("identity", "schema", "poll", "fetch"): guard.setattr(impl, method, unexpected_callback) - for accessor in (direct.name_chain, direct.node_hash): - with pytest.raises(ValueError, match="undefined.*polling.*identity"): - _ = accessor() + assert direct.name_chain() + assert direct.node_hash() job.bind(sources={"left": source}) for method in ("identity", "schema", "poll", "fetch"): diff --git a/tests/test_core/operators/test_async_sync_equivalence.py b/tests/test_core/operators/test_async_sync_equivalence.py index ae37dd608..7efa528e9 100644 --- a/tests/test_core/operators/test_async_sync_equivalence.py +++ b/tests/test_core/operators/test_async_sync_equivalence.py @@ -1249,6 +1249,31 @@ def _symmetric_tie_snapshot(arity: int, mode: str) -> tuple[str, ...]: return tuple(snapshot) +@pytest.mark.parametrize("peer_is_join", [False, True]) +def test_nested_self_join_system_tags_match_in_all_modes(peer_is_join: bool) -> None: + """Raw row channels and batches use the same structural suffixes as tables.""" + table = pa.table({"k": [1, 2], "m": [3, 4]}) + a = ArrowTableSource(table, tag_columns=("k", "m"), source_id="a") + b = ArrowTableSource(table, tag_columns=("k", "m"), source_id="b") + repeated = Join()(a, a) + peer = Join()(a, b) if peer_is_join else b + _, expected = _tied_join_outputs("sync", Join(), (repeated, peer)) + assert expected + hasher = get_default_arrow_hasher() + expected_ids = sorted( + entry_id(hasher, tag, data).to_hex() for tag, data in expected + ) + + for inputs in ((repeated, peer), (peer, repeated)): + for mode in ("sync", "rows", "batches"): + _, actual = _tied_join_outputs(mode, Join(), inputs) + assert_equivalent(expected, actual) + assert ( + sorted(entry_id(hasher, tag, data).to_hex() for tag, data in actual) + == expected_ids + ) + + # Captured from origin/main at 37f78431, where all permutations and modes agree. @pytest.mark.parametrize( ("arity", "table_digest", "expected_entry_id"), @@ -1377,6 +1402,30 @@ def _ipc_bytes(table: pa.Table) -> bytes: return output.getvalue().to_pybytes() +@pytest.mark.parametrize("arity", [2, 3, 4]) +def test_commutative_hash_counts_content_equal_inputs(arity: int) -> None: + """Source equality changes neither the flat nor the nested structure.""" + distinct = _tied_declaration_inputs(arity, "same") + equal = _tied_declaration_inputs(arity, "same")[0] + first = distinct[0] + assert first is not equal and first == equal + + variants = (distinct, [first] * arity, [first, equal, *distinct[2:]]) + direct = [Join()(*inputs) for inputs in variants] + assert len({stream.pipeline_hash() for stream in direct}) == 1 + assert len({Join()(stream, first).pipeline_hash() for stream in direct}) == 1 + assert direct[1].pipeline_hash() != Join()(*([first] * (arity + 1))).pipeline_hash() + + for inputs, stream in zip(variants, direct, strict=True): + sync = list(stream.iter_data()) + async_ = async_rows(Join(), *inputs) + assert len(sync) == len(async_) == 2 + hasher = get_default_arrow_hasher() + assert sorted( + entry_id(hasher, tag, data).to_string() for tag, data in sync + ) == (sorted(entry_id(hasher, tag, data).to_string() for tag, data in async_)) + + def _tied_declaration_snapshot(arity: int, variant: str, mode: str) -> str: """Digest all tables, row declarations, and entry IDs in permutation order.""" hasher = get_default_arrow_hasher() diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index c492bc236..1cefe7e45 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -26,9 +26,10 @@ from orcapod.protocols.core_protocols import StreamProtocol from orcapod.sources import DictSource, SourceProxy from orcapod.types import ContentHash +from orcapod.types.argument_groups import SymmetricGroup if TYPE_CHECKING: - from collections.abc import Callable, Collection + from collections.abc import Callable from orcapod.protocols.core_protocols import ArgumentGroup from orcapod.protocols.hashing_protocols import ( @@ -346,7 +347,7 @@ def count_hash(label: str, preimage: tuple[object, ...]) -> ContentHash: assert counts == { SOURCE_CHAIN_HASH_LABEL: 5, NAME_CHAIN_HASH_LABEL: 5, - identity_chains.CONTENT_HASH_LABEL: 3, + identity_chains.CONTENT_HASH_LABEL: 1, NODE_HASH_LABEL: 1, } counts.clear() @@ -677,12 +678,36 @@ def test_commutative_equal_structure_sorts_the_chains_independently( assert _hashes(job.nodes["joined"]) == _hashes(result) -@pytest.mark.xfail(strict=True, reason="ITL-1590: legacy P drops content-equal inputs") -def test_equal_structure_join_pipeline_hash_depends_only_on_structure() -> None: - """Pin the legacy structure hash's dependence on content equality at ties.""" +def test_equal_structure_join_pipeline_hash_depends_only_on_structure( + tmp_path: Path, +) -> None: + """A tie has the same structure for identical, equal and distinct operands.""" left, right = _data_tags("a"), _data_tags("b") assert left.pipeline_hash() == right.pipeline_hash() - assert Join()(left, left).pipeline_hash() == Join()(left, right).pipeline_hash() + equal_left = _data_tags("a") + assert left == equal_left and left is not equal_left + expected = Join()(left, right).pipeline_hash() + assert Join()(left, left).pipeline_hash() == expected + assert Join()(left, equal_left).pipeline_hash() == expected + assert Join()(left).pipeline_hash() != expected + assert Join()(left, left, right).pipeline_hash() != expected + + job = PipelineJob(name="repeated_inputs", database=InMemoryArrowDatabase()) + with job: + _ = Join()(left, left, label="repeated") + invocation = next( + inv for inv in job._invocation_lut.values() if inv.label == "repeated" + ) + assert invocation.input_streams == (left, left) + assert invocation.pipeline_hash() == expected + assert job.nodes["repeated"].pipeline_hash() == expected + assert len(job.nodes["repeated"].upstreams) == 2 + path = tmp_path / "repeated.json" + job.save(path) + loaded = PipelineJob.load(path, database=InMemoryArrowDatabase()) + assert loaded.nodes["repeated"].pipeline_hash() == expected + upstreams = loaded.nodes["repeated"].upstreams + assert len(upstreams) == 2 and upstreams[0] is upstreams[1] @pytest.mark.parametrize("missing_builtin", [False, True]) @@ -797,11 +822,11 @@ def test_nested_symmetry_keeps_repeated_ordered_pairs( class PairJoin(Join): @override - def argument_symmetry( - self, streams: Collection[StreamProtocol] + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] ) -> ArgumentGroup: a, b, c, d = streams - return frozenset(((a, b), (c, d))) + return SymmetricGroup(((a, b), (c, d))) allow_synthetic_symmetry(PairJoin) left, right = _data_tags("a"), _data_tags("b") @@ -821,11 +846,11 @@ def test_mixed_nested_symmetry_uses_pipeline_order( class MixedJoin(Join): @override - def argument_symmetry( - self, streams: Collection[StreamProtocol] + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] ) -> ArgumentGroup: a, b, c = streams - return frozenset((a, (b, c))) + return SymmetricGroup((a, (b, c))) allow_synthetic_symmetry(MixedJoin) a, b, c = (_data_tags(name) for name in "abc") @@ -844,7 +869,7 @@ def argument_symmetry( @pytest.fixture -def collapsed_nested_pair( +def repeated_nested_pair( allow_synthetic_symmetry: Callable[[type], None], ) -> tuple[StreamProtocol, StreamProtocol]: """Build the review's two orderings of content-equal, differently named slots.""" @@ -852,11 +877,11 @@ def collapsed_nested_pair( class ReversedPairJoin(Join): @override - def argument_symmetry( - self, streams: Collection[StreamProtocol] + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] ) -> ArgumentGroup: a, b, c, d = streams - return frozenset(((a, b), (d, c))) + return SymmetricGroup(((a, b), (d, c))) allow_synthetic_symmetry(ReversedPairJoin) source = _data_tags("reading") @@ -869,39 +894,35 @@ def argument_symmetry( job.bind(dict.fromkeys("abcd", source)) a, b, c, d = (cast("StreamProtocol", job.nodes[name]) for name in "abcd") assert a == b == c == d - symmetry = ReversedPairJoin().argument_symmetry((a, b, c, d)) - assert isinstance(symmetry, frozenset) and len(symmetry) == 1 + symmetry = ReversedPairJoin().structural_argument_symmetry((a, b, c, d)) + assert isinstance(symmetry, SymmetricGroup) and len(symmetry.members) == 2 return ReversedPairJoin()(a, b, c, d), ReversedPairJoin()(d, c, b, a) -@pytest.mark.xfail( - strict=True, raises=AssertionError, reason="ITL-1590: a nested group loses a pair" -) -def test_nested_symmetry_preserves_order_in_collapsed_pairs( - collapsed_nested_pair: tuple[StreamProtocol, StreamProtocol], +def test_nested_symmetry_preserves_order_in_equal_pairs( + repeated_nested_pair: tuple[StreamProtocol, StreamProtocol], ) -> None: """Swapping the commutative groups preserves their ordered name chains.""" - original, swapped = collapsed_nested_pair + original, swapped = repeated_nested_pair assert original.pipeline_hash() == swapped.pipeline_hash() assert original.source_chain() == swapped.source_chain() assert original.name_chain() == swapped.name_chain() -def test_node_hash_refuses_collapsed_commutative_groups( - collapsed_nested_pair: tuple[StreamProtocol, StreamProtocol], +def test_combined_hashes_keep_repeated_commutative_arguments( + repeated_nested_pair: tuple[StreamProtocol, StreamProtocol], ) -> None: - """Standalone node identity keeps its provisional guard on collapsed input groups.""" + """Repeated occurrences are retained through downstream identities.""" from orcapod.operators import SelectDataColumns source = _data_tags("reading") repeated = Join()(source, source) - for result in (repeated, *collapsed_nested_pair): + for result in (repeated, *repeated_nested_pair): assert result.pipeline_hash() unary = SelectDataColumns(["x", "y"])(result) ordered = MergeJoin()(result, source) for stream in (result, unary, ordered): - with pytest.raises(ValueError, match="commutative.*ITL-1590"): - _ = stream.node_hash() + assert stream.node_hash() assert stream.content_hash() @@ -1048,10 +1069,8 @@ def unexpected_row_hash(*args: object) -> None: with monkeypatch.context() as guard: guard.setattr(ArrowTableStream, "_identity_table", unexpected_row_hash) assert left.node_hash() - for accessor in ( - joined.node_hash, - left.source_chain, - ): + assert joined.node_hash() + for accessor in (left.source_chain,): with pytest.raises(ValueError, match="undefined.*hashing Arrow rows"): _ = accessor() assert joined.pipeline_hash() @@ -1367,8 +1386,8 @@ class StreamCheckingJoin(Join): calls: int = 0 @override - def argument_symmetry( - self, streams: Collection[StreamProtocol] + def structural_argument_symmetry( + self, streams: tuple[StreamProtocol, ...] ) -> ArgumentGroup: assert all( isinstance(stream, (DictSource, SourceNodeBase)) for stream in streams @@ -1565,17 +1584,29 @@ def test_bound_slot_and_root_share_a_python_key() -> None: assert source == slot assert hash(source) == hash(slot) assert {source: 1}[slot] == 1 - # This is the main-branch digest when the frozenset sees one input. - assert Join()(source, slot).pipeline_hash().to_hex() == ( - "e4143f9276aaf4f9f0d207a4abc277b07263e5f6755f5c8f88c5c81a3b9fa518" - ) + assert Join()(source, slot).pipeline_hash() == Join()(slot, source).pipeline_hash() + assert Join()(source, slot).pipeline_hash() != Join()(source).pipeline_hash() def test_repeated_join_input_has_content_identity_and_captures() -> None: - """Step 5 keeps repeated-input Join hash and capture available.""" + """The three identity chains retain both positions of a self-join.""" source = _join_source() - result = Join()(source, source) - assert result.content_hash() + pod = Join() + result = pod(source, source) + structural_hasher = source.data_context.semantic_hasher + assert result.pipeline_hash() == structural_hasher.hash_object( + (pod, SymmetricGroup((source, source))), + resolver=lambda obj: obj.pipeline_hash(structural_hasher), + ) + assert result.source_chain() == _chain( + SOURCE_CHAIN_HASH_LABEL, None, source.source_chain(), source.source_chain() + ) + assert result.name_chain() == _chain( + NAME_CHAIN_HASH_LABEL, None, source.name_chain(), source.name_chain() + ) + assert result.content_hash() == SemanticAwarePythonHasher( + hasher_id=CONTENT_HASH_LABEL + ).hash_object((result.pipeline_hash(), result.source_chain())) job = PipelineJob(name="repeat", database=InMemoryArrowDatabase()) with job: Join()(source, source, label="result") @@ -1609,3 +1640,72 @@ def test_loaded_partial_job_refreshes_unrecorded_function_content( ).hash_object((restored.pipeline_hash(), restored.source_chain())) job.bind(sources={"absent": b}) assert restored.content_hash() == job.nodes["two"].content_hash() + + +@pytest.mark.parametrize("pipeline_kind", ["job", "pipeline"]) +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("case", ["nested", "flat"]) +def test_capture_distinguishes_joins_by_multiplicity( + case: str, reverse: bool, pipeline_kind: str +) -> None: + """Capture retains Joins whose only difference is a repeat count.""" + a, b = _data_tags("a"), _data_tags("b") + if case == "nested": + captures = [("two", (a, a)), ("three", (a, a, a))] + else: + captures = [("two", (a, b)), ("more_b", (a, b, b))] + if reverse: + captures.reverse() + graph = ( + PipelineJob(name="multiplicities", database=InMemoryArrowDatabase()) + if pipeline_kind == "job" + else Pipeline(name="multiplicities") + ) + with graph: + first_label, first_inputs = captures[0] + _ = Join()(*first_inputs, label=first_label) + second_label, second_inputs = captures[1] + _ = Join()(*second_inputs, label=second_label) + # The same multiset again, in another order, is the recorded node. + _ = Join()(*reversed(first_inputs), label="z_again") + + sources = {"a"} if case == "nested" else {"a", "b"} + assert set(graph.nodes) == {first_label, second_label, *sources} + assert len(graph.nodes[first_label].upstreams) == len(first_inputs) + assert len(graph.nodes[second_label].upstreams) == len(second_inputs) + assert ( + graph.nodes[first_label].pipeline_hash() + != graph.nodes[second_label].pipeline_hash() + ) + + +def test_capture_keys_follow_a_rewired_join() -> None: + """A key memo must pick up a changed repeat count through a held stream.""" + from orcapod.core.nodes.operator_node import OperatorNode + + 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) + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_nested_repeated_join_records_its_operands(reverse: bool) -> None: + """A repeated Join inside another Join keeps its operand positions.""" + a, b = _data_tags("a"), _data_tags("b") + job = PipelineJob(name="nested_repeat", database=InMemoryArrowDatabase()) + with job: + two = Join()(a, a, label="two") + operands = (b, two) if reverse else (two, b) + joined = Join()(*operands, label="joined") + + node = job.nodes["joined"] + invocation = next( + inv for inv in job._invocation_lut.values() if inv.label == "joined" + ) + assert invocation.pipeline_hash() == joined.pipeline_hash() == node.pipeline_hash() + assert len(job.nodes["two"].upstreams) == 2 diff --git a/tests/test_pipeline/test_deep_capture.py b/tests/test_pipeline/test_deep_capture.py new file mode 100644 index 000000000..3a85b8f74 --- /dev/null +++ b/tests/test_pipeline/test_deep_capture.py @@ -0,0 +1,89 @@ +"""Capture a deep DAG with the normal interpreter recursion limit.""" + +from __future__ import annotations + +from typing import cast + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob +from orcapod.core.operators import Join +from orcapod.core.streams import ArrowTableStream +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import UnboundSourceError +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.sources import ArrowTableSource + + +@pytest.mark.parametrize("kind", ["pipeline", "job", "job_with_database"]) +@pytest.mark.parametrize("warm", [False, True]) +def test_capture_and_hash_2000_node_unary_chain(kind: str, warm: bool) -> None: + graph: Pipeline | PipelineJob + if kind == "pipeline": + graph = Pipeline("depth") + else: + database = InMemoryArrowDatabase() if kind == "job_with_database" else None + graph = PipelineJob("depth", database=database) + stream: StreamProtocol = ArrowTableSource( + pa.table({"k": [1, 2], "l": [3, 4]}), + tag_columns=["k", "l"], + source_id="depth_source", + ) + peer = ArrowTableSource( + pa.table({"k": [1, 2], "l": [3, 4]}), + tag_columns=["k", "l"], + source_id="depth_peer", + ) + join = Join() + with graph: + for i in range(2000): + stream = stream.select_tag_columns(["k", "l"], label=f"s{i}") + if warm: + _ = stream.pipeline_hash() + assert {id(s) for s in join.order_input_streams(stream, peer)} == { + id(stream), + id(peer), + } + joined = join(stream, peer, label="joined") + + assert len(graph.nodes) == 2003 + previous = cast(StreamProtocol, graph.nodes["s1998"]) + assert previous.pipeline_hash().to_hex() == ( + "467403fa55f2abc2bb2ca628b0b698cd031574628f4709fd1fa6fe9a0489aed8" + ) + last = cast(StreamProtocol, graph.nodes["s1999"]) + assert last.pipeline_hash() == stream.pipeline_hash() + compiled_join = cast(StreamProtocol, graph.nodes["joined"]) + assert compiled_join.pipeline_hash() == joined.pipeline_hash() + assert [ + s.pipeline_hash() for s in join.order_input_streams(*compiled_join.upstreams) + ] == sorted((last.pipeline_hash(), peer.pipeline_hash()), key=lambda h: h.to_hex()) + if kind == "job": + assert last.content_hash() == stream.content_hash() + elif kind == "pipeline": + with pytest.raises(UnboundSourceError, match="depth_source"): + _ = previous.content_hash() + + +def test_capture_and_hash_deep_diamond_ladder() -> None: + graph = Pipeline("depth") + stream: StreamProtocol = ArrowTableStream( + pa.table({"k": [1, 2], "l": [3, 4]}), + tag_columns=["k", "l"], + data_tags=["k", "l"], + ) + with graph: + for i in range(400): + left = stream.select_tag_columns(["k", "l"], label=f"left{i}") + right = stream.drop_data_columns([], label=f"right{i}") + stream = Join()(left, right, label=f"join{i}") + + assert len(graph.nodes) == 1201 + last = cast(StreamProtocol, graph.nodes["join399"]) + # The structure matches a capture of the same non-tied graph on main. + assert last.pipeline_hash().to_hex() == ( + "8cb18fa56dbef6a92ca31c782b51b9b796fc4f0c5216db17c010aa612874816a" + ) + with pytest.raises(UnboundSourceError, match="ArrowTableStream"): + _ = last.content_hash() diff --git a/tests/test_pipeline/test_loaded_argument_order.py b/tests/test_pipeline/test_loaded_argument_order.py index af154b56c..6d8dfcbee 100644 --- a/tests/test_pipeline/test_loaded_argument_order.py +++ b/tests/test_pipeline/test_loaded_argument_order.py @@ -434,20 +434,19 @@ def test_a_loaded_read_only_node_keeps_its_inputs( @pytest.mark.parametrize("mode", ["sync", "async"]) @pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) -def test_one_stream_given_twice_fails_to_run_in_a_job( - operator: type, mode: str, tmp_path: Path +def test_one_stream_given_twice_runs_in_both_argument_positions( + operator: type[MergeJoin | SemiJoin], mode: str, tmp_path: Path ) -> None: - """Finding 5 (pre-existing on main, pinned; ITL-1419): a job's - graph has one edge for two argument slots of one stream, so ``MergeJoin()(a, a)`` - and ``SemiJoin()(a, a)`` fail when the job runs, though they run as plain - streams. A fix makes this test fail; it is then changed to the fixed behaviour.""" + """A job gives both operands the same stream through one graph edge.""" a = _inputs(tmp_path)["a"] - assert operator()(a, a).as_table().num_rows == 3 + columns = {"system_tags": True} + expected = operator()(a, a).as_table(columns=columns) + assert expected.num_rows == 3 job = PipelineJob(name="repeat", database=DeltaTableDatabase(tmp_path / "db")) with job: - operator()(a, a, label="repeat") - with pytest.raises((ValueError, IndexError)): - _run(job, mode) + _ = operator()(a, a, label="repeat") + _run(job, mode) + assert _rows(job.repeat.as_table(columns=columns)) == _rows(expected) @pytest.mark.parametrize("operator", [MergeJoin, SemiJoin]) diff --git a/tests/test_pipeline/test_shared_operator_inputs.py b/tests/test_pipeline/test_shared_operator_inputs.py new file mode 100644 index 000000000..c1a458cd7 --- /dev/null +++ b/tests/test_pipeline/test_shared_operator_inputs.py @@ -0,0 +1,187 @@ +"""Operators receive every declared operand from a shared execution vertex.""" + +from __future__ import annotations + +from pathlib import Path + +import pyarrow as pa +import pytest + +from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.contexts import get_default_context +from orcapod.core.row_ids import entry_id +from orcapod.databases import InMemoryArrowDatabase +from orcapod.operators import Join, MergeJoin, SemiJoin +from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator +from orcapod.protocols.core_protocols import StreamProtocol +from orcapod.sources import ArrowTableSource + + +@function_pod(output_keys="result") +def double_join_value(value: int) -> int: + """Double the shared tag.""" + return 2 * value + + +@function_pod(output_keys="other") +def other_join_value(value: int) -> int: + """Produce a disjoint data column for a downstream join.""" + return 3 * value + + +def source(name: str) -> ArrowTableSource: + """Build a source that can occupy more than one Join position.""" + return ArrowTableSource( + pa.table({"value": [1, 2], "key": ["a", "b"]}), + tag_columns=["value", "key"], + tag_only_columns=["key"], + source_id=name, + infer_nullable=True, + ) + + +@pytest.fixture(params=["sync", "async"]) +def runner( + request: pytest.FixtureRequest, +) -> SyncPipelineOrchestrator | AsyncPipelineOrchestrator: + """Exercise both execution paths with a small async fan-out buffer.""" + if request.param == "async": + return AsyncPipelineOrchestrator(buffer_size=1) + return SyncPipelineOrchestrator() + + +@pytest.mark.parametrize( + ("operator", "arity", "tag_count"), + [(Join, 2, 4), (Join, 3, 6), (MergeJoin, 2, 4), (SemiJoin, 2, 2)], +) +def test_shared_slots_match_repeated_source( + runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, + operator: type[Join | MergeJoin | SemiJoin], + arity: int, + tag_count: int, +) -> None: + """Compare rows and entry IDs against a job recorded with one source object.""" + a = source("a") + names = [f"slot_{i}" for i in range(arity)] + with Pipeline("shared") as pipeline: + slots = tuple(SourceNode.from_stream(a, name=name) for name in names) + _ = double_join_value.pod(operator()(*slots, label="joined"), label="out") + shared = PipelineJob.from_pipeline( + pipeline, + database=InMemoryArrowDatabase(), + sources=dict.fromkeys(names, a), + ) + repeated = PipelineJob("shared", database=InMemoryArrowDatabase()) + with repeated: + _ = double_join_value.pod(operator()(*[a] * arity, label="joined"), label="out") + + _ = shared.run(orchestrator=runner) + _ = repeated.run(orchestrator=runner) + + columns = {"system_tags": True} + shared_node = shared.nodes["joined"] + repeated_node = repeated.nodes["joined"] + shared_rows = shared_node.as_table(columns=columns).sort_by("value") + repeated_rows = repeated_node.as_table(columns=columns).sort_by("value") + assert shared_rows.equals(repeated_rows) + assert ( + sum(name.startswith("_tag_") for name in shared_rows.column_names) == tag_count + ) + assert ( + shared.nodes["out"].node_identity_path + == repeated.nodes["out"].node_identity_path + ) + hasher = get_default_context().arrow_hasher + entry_ids = [ + sorted(entry_id(hasher, tag, data).to_hex() for tag, data in node.iter_data()) + for node in (shared_node, repeated_node) + ] + assert entry_ids[0] == entry_ids[1] + assert shared_node.node_identity_path == repeated_node.node_identity_path + + +@pytest.mark.parametrize("jobs", ["one", "shared_first", "distinct_first"]) +def test_shared_slots_and_distinct_sources_share_storage( + runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, jobs: str +) -> None: + """Write both variants to the same function table in either execution order.""" + a, b = source("a"), source("b") + db = InMemoryArrowDatabase() + + def make_job(variants: tuple[bool, ...]) -> PipelineJob: + sources: dict[str, StreamProtocol] = {"a": a} + with Pipeline("shared") as pipeline: + left = SourceNode.from_stream(a, name="a") + for shared in variants: + name, right_source = ("a2", a) if shared else ("b", b) + sources[name] = right_source + right = SourceNode.from_stream(right_source, name=name) + _ = double_join_value.pod(Join()(left, right), label=name + "_out") + return PipelineJob.from_pipeline(pipeline, database=db, sources=sources) + + variants = { + "one": ((True, False),), + "shared_first": ((True,), (False,)), + "distinct_first": ((False,), (True,)), + } + paths = set() + for variant in variants[jobs]: + job = make_job(variant) + _ = job.run(orchestrator=runner) + for shared in variant: + node = job.nodes["a2_out" if shared else "b_out"] + paths.add(node.node_identity_path) + assert sorted(node.as_source().as_table()["result"].to_pylist()) == [2, 4] + assert len(paths) == 1 + + +def test_shared_slot_join_save_and_load_only( + runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, tmp_path: Path +) -> None: + """Keep both saved inputs when rebuilding the blueprint and the job.""" + a = source("a") + sources: dict[str, StreamProtocol] = {"a": a, "a2": a} + with Pipeline("shared") as pipeline: + left = SourceNode.from_stream(a, name="a") + right = SourceNode.from_stream(a, name="a2") + _ = double_join_value.pod(Join()(left, right, label="joined"), label="out") + db = InMemoryArrowDatabase() + job = PipelineJob.from_pipeline(pipeline, database=db, sources=sources) + _ = job.run(orchestrator=runner) + path = tmp_path / "job.json" + job.save(path) + + loaded = PipelineJob.load(path, database=db) + loaded.bind(sources=sources) + summary = loaded.run(orchestrator=runner, load_only=True) + assert summary.nodes["out"].reused == 2 + for label in ("joined", "out"): + assert loaded.nodes[label].pipeline_hash() == job.nodes[label].pipeline_hash() + columns = {"system_tags": True} + assert ( + loaded.nodes[label] + .as_table(columns=columns) + .sort_by("value") + .equals(job.nodes[label].as_table(columns=columns).sort_by("value")) + ) + + +def test_join_downstream_of_function_pods_on_shared_slots( + runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, +) -> None: + """A source that occupies two slots still feeds both branches through functions.""" + a = source("a") + with Pipeline("shared") as pipeline: + left = SourceNode.from_stream(a, name="a") + right = SourceNode.from_stream(a, name="a2") + _ = Join()( + double_join_value.pod(left), other_join_value.pod(right), label="joined" + ) + job = PipelineJob.from_pipeline( + pipeline, database=InMemoryArrowDatabase(), sources={"a": a, "a2": a} + ) + _ = job.run(orchestrator=runner) + rows = job.nodes["joined"].as_table(columns={"system_tags": True}).sort_by("value") + assert sum(name.startswith("_tag_") for name in rows.column_names) == 4 + assert rows["result"].to_pylist() == [2, 4] + assert rows["other"].to_pylist() == [3, 6] diff --git a/tests/test_pipeline/test_sync_orchestrator.py b/tests/test_pipeline/test_sync_orchestrator.py index ffd2c7907..24ae26fea 100644 --- a/tests/test_pipeline/test_sync_orchestrator.py +++ b/tests/test_pipeline/test_sync_orchestrator.py @@ -2,15 +2,18 @@ from __future__ import annotations +from pathlib import Path + import pyarrow as pa import pytest +from orcapod import function_pod from orcapod.core.function_pod import FunctionPod from orcapod.core.operators.join import Join from orcapod.core.operators.mappers import MapData from orcapod.core.data_function import PythonDataFunction from orcapod.core.sources import ArrowTableSource -from orcapod.databases import InMemoryArrowDatabase +from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase from orcapod.pipeline import AsyncPipelineOrchestrator from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator @@ -37,6 +40,79 @@ def add_values(value: int, score: int) -> int: return value + score +@function_pod(output_keys="result") +def _double_join_value(value: int) -> int: + return 2 * value + + +@pytest.mark.parametrize( + "orchestrator", [SyncPipelineOrchestrator, AsyncPipelineOrchestrator] +) +@pytest.mark.parametrize("existing_store", [False, True]) +def test_repeated_join_uses_the_distinct_join_table( + tmp_path: Path, + orchestrator: type[SyncPipelineOrchestrator] | type[AsyncPipelineOrchestrator], + existing_store: bool, +) -> None: + """Keep both repeated input positions when computing and storing a Join.""" + database = DeltaTableDatabase(base_path=tmp_path) + table = pa.table({"value": [1, 2]}) + a = ArrowTableSource( + table, tag_columns=["value"], source_id="a", infer_nullable=True + ) + b = ArrowTableSource( + table, tag_columns=["value"], source_id="b", infer_nullable=True + ) + pod = _double_join_value.pod + if existing_store: + initial = PipelineJob("join", database=database) + with initial: + _ = pod(Join()(a, b), label="distinct") + _ = initial.run() + + job = PipelineJob("join", database=database) + with job: + _ = pod(Join()(a, a, label="repeat_join"), label="repeat") + _ = pod(Join()(a, b, label="distinct_join"), label="distinct") + runner = ( + AsyncPipelineOrchestrator(buffer_size=1) + if orchestrator is AsyncPipelineOrchestrator + else SyncPipelineOrchestrator() + ) + _ = job.run(orchestrator=runner) + + repeat, distinct = (job.nodes[label] for label in ("repeat", "distinct")) + assert repeat.node_identity_path == distinct.node_identity_path + for node in (repeat, distinct): + assert sorted(node.as_source().as_table().column("result").to_pylist()) == [ + 2, + 4, + ] + + columns = {"system_tags": True} + repeated_rows = job.nodes["repeat_join"].as_table(columns=columns) + distinct_rows = job.nodes["distinct_join"].as_table(columns=columns) + suffix = a.pipeline_hash().to_hex() + tag_columns = { + f"{name}::{suffix}:{position}" + for name in a.as_table(columns=columns).column_names + if name.startswith("_tag_") + for position in (0, 1) + } + assert len(tag_columns) == 4 + assert ( + set(repeated_rows.column_names) + == set(distinct_rows.column_names) + == { + "value", + *tag_columns, + } + ) + for name in tag_columns: + if name.endswith(":0"): + assert repeated_rows[name].equals(repeated_rows[name[:-1] + "1"]) + + class TestSyncOrchestratorLinear: """Source -> FunctionPod."""