From 7091585f0f0bdef017a261ccc93e9a4b0b424fa8 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 02:33:35 -0800 Subject: [PATCH 01/38] feat(identity): compute structure, source and name chains --- changelog.d/ITL-1559.md | 3 + docs/dev/design_issues/ITL-1559-TC1.md | 15 + docs/reference/hashing.md | 29 +- src/orcapod/core/identity_chains.py | 237 ++++++++++++++ src/orcapod/core/nodes/function_node.py | 13 + src/orcapod/core/nodes/operator_node.py | 13 + src/orcapod/core/nodes/source_node.py | 53 +-- .../core/operators/static_output_pod.py | 25 ++ .../core/streams/arrow_table_stream.py | 4 + src/orcapod/core/streams/base.py | 30 +- src/orcapod/pipeline/pod_invocation.py | 32 +- .../protocols/core_protocols/streams.py | 9 +- src/orcapod/protocols/hashing_protocols.py | 45 +++ tests/test_core/test_order_invariance.py | 4 + tests/test_hashing/hash_site_trace.py | 15 + tests/test_hashing/test_hash_grammar.py | 5 + tests/test_hashing/test_hash_label_rule.py | 5 + tests/test_hashing/test_identity_chains.py | 304 ++++++++++++++++++ 18 files changed, 810 insertions(+), 31 deletions(-) create mode 100644 changelog.d/ITL-1559.md create mode 100644 docs/dev/design_issues/ITL-1559-TC1.md create mode 100644 src/orcapod/core/identity_chains.py create mode 100644 tests/test_hashing/test_identity_chains.py diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md new file mode 100644 index 000000000..573c0f866 --- /dev/null +++ b/changelog.d/ITL-1559.md @@ -0,0 +1,3 @@ +### Added + +- Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. Existing pipeline and content hashes keep their values. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md new file mode 100644 index 000000000..fd35cac39 --- /dev/null +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -0,0 +1,15 @@ +## Pipeline identity + +### TC1 — Graph identity and source binding share one key +**Status:** in progress +**Severity:** high +**Issue:** ITL-1559 + +A graph key derived from bound data cannot distinguish two slots bound to one source. +It also cannot follow a slot through a rebind while identifying the same computation +(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. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 4c9a4af72..f71f5da7b 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -71,7 +71,7 @@ The container cell keeps its element count prefix, so it is self-contained and d depend on the cell boundary. `tests/test_hashing/test_hash_grammar.py` fails if any of these stops holding. -The labels of v0.3: +Hash labels: | Label | Names | Defined in | |---|---|---| @@ -93,6 +93,11 @@ The labels of v0.3: | `batch_v1` | the folded source id and record id of `Batch` (site 6b) | `BATCH_FOLD_LABEL`, `core/operators/batch.py` | | `group_v1` | the folded source id and record id of `GroupBy` (site 6b), and the merged source-info token of a data-tag group key | `GROUP_BY_FOLD_LABEL`, `core/operators/group_by.py` | | `join_v1` | the merged source-info token of a key that is a data-tag on several inputs of a `Join` (site 6b) | `JOIN_FOLD_LABEL`, `core/operators/join.py` | +| `slot_name_v1` | SHA-256 of the canonical tuple `("slot", name)` | `SLOT_NAME_HASH_LABEL`, `core/identity_chains.py` | +| `source_chain_v1` | SHA-256 of the canonical tuple of upstream source chains, with any local contribution | `SOURCE_CHAIN_HASH_LABEL`, `core/identity_chains.py` | +| `name_chain_v1` | SHA-256 of the canonical tuple of upstream name chains, with any local contribution | `NAME_CHAIN_HASH_LABEL`, `core/identity_chains.py` | +| `content_hash_v1` | SHA-256 of the canonical tuple of the pipeline hash and source chain | `CONTENT_HASH_LABEL`, `core/identity_chains.py` | +| `node_hash_v1` | SHA-256 of the canonical tuple of the pipeline hash and name chain | `NODE_HASH_LABEL`, `core/identity_chains.py` | | `sha256` | the file content hash: SHA-256 of the file's bytes | the file hasher's `algorithm` | Where a hash appears, and in which form: @@ -291,6 +296,24 @@ reusable as its data changes: a default in-memory source id is the hash of the w key order with `hash_in_key_order=True`), and a position moves when rows are inserted or reordered. +## Structure, source and name chains + +A stream, invocation or job node carries three chains. `pipeline_hash()` describes the +structure. `source_chain()` starts at each slot with the bound source's own content hash. +`name_chain()` starts with the slot's name. A single-input step passes both chains +through unchanged unless the step contributes a term of its own. Multiple inputs are pooled in argument order for an ordered +operator and by pipeline hash for a commutative operator. Within a pipeline-hash tie, +the source and name chains each sort their own values. Repeated inputs contribute +at every position. + +`node_hash()` combines the pipeline hash and the name chain. The chain-based content +hash combines the pipeline hash and the source chain and is undefined while any +contributing slot is unbound. The chain-based content hash is available internally as +`_chain_content_hash()` until the switch to `content_hash()`. Orcapod continues to use +the existing hashes for graph keys and persistence. ITL-1590 tracks cases where the +existing pipeline hash depends on source equality within a commutative input tie. +A read-only operator whose pod cannot be restored uses its saved input order. + ## Hash site inventory Every place Orcapod produces a digest, and every place it reads one, with its class @@ -316,6 +339,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | What is hashed | Algorithm / label | Used as | Call sites | |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | +| three-chain hashes | a slot name, a pool of upstream chains, or the pipeline hash paired with one chain | SHA-256 of canonical JSON, with the corresponding chain or combined-hash label | into a hash for chain pooling and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool`, `core/identity_chains.py:IdentityChainsMixin._identity_chains`, `core/identity_chains.py:IdentityChainsMixin._chain_content_hash`, `core/identity_chains.py:IdentityChainsMixin.node_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | | file hasher | a file's bytes | the configured digest function, label = its name (`sha256` in the data context; others: ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | @@ -375,7 +399,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | function `uri` (output-schema digest) | `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | operator `uri` | `core/operators/static_output_pod.py:StaticOutputOperatorPod.uri` | | `schema:` / `instance:` / `node:` path components | `core/nodes/function_node.py:FunctionNodeBase.node_identity_path`, `core/nodes/operator_node.py:OperatorNodeBase.node_identity_path`, `side_effects.py:SideEffectJobNode.attach_databases`, `core/sources/cached_source.py:CachedSource._unversioned_cache_path` | -| source-node slot names | `core/nodes/source_node.py:SourceNode.from_stream`, `core/nodes/source_node.py:SourceJobNode.from_stream` | +| implicit source-node slot names for streams with no source name | `core/nodes/source_node.py:slot_name_for` | | source system-tag column name (schema digest) | `utils/schema_utils.py:compute_schema_hash` | | system-tag suffixes of `Join`, `MergeJoin`, `Batch`, `GroupBy` | `core/operators/join.py:Join._compute_system_tag_suffixes`, `core/operators/join.py:Join._predict_system_tag_schema`, `core/operators/join.py:Join.static_process`, `core/operators/merge_join.py:MergeJoin._system_tag_suffix`, `core/operators/batch.py:Batch.unary_output_schema`, `core/operators/batch.py:Batch.unary_static_process`, `core/operators/group_by.py:GroupBy.unary_output_schema`, `core/operators/group_by.py:GroupBy.unary_static_process` | | a saved hash shown as a digest | `core/nodes/function_node.py:_bare_digest` | @@ -401,6 +425,7 @@ A record id is the row identifier (rule 8), built from row positions or key valu | 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 for source and name chains (pipeline digest, 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__` | diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py new file mode 100644 index 000000000..5e5eeae7d --- /dev/null +++ b/src/orcapod/core/identity_chains.py @@ -0,0 +1,237 @@ +"""Compute structure, source and name chains for a stream or invocation.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from dataclasses import dataclass +from itertools import groupby +from typing import TYPE_CHECKING, cast, final + +from orcapod.errors import UnboundSourceError +from orcapod.protocols.hashing_protocols import IdentityChains +from orcapod.types import ContentHash + +if TYPE_CHECKING: + from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol + from orcapod.protocols.hashing_protocols import ( + IdentityChainProtocol, + IdentityWalkProtocol, + SemanticHasherProtocol, + ) + +SLOT_NAME_HASH_LABEL = "slot_name_v1" +SOURCE_CHAIN_HASH_LABEL = "source_chain_v1" +NAME_CHAIN_HASH_LABEL = "name_chain_v1" +CONTENT_HASH_LABEL = "content_hash_v1" +NODE_HASH_LABEL = "node_hash_v1" + + +def _hash(label: str, preimage: tuple[object, ...]) -> ContentHash: + """Hash canonical semantic tuples under the label of the chain algorithm.""" + from orcapod.hashing.semantic_hashing.semantic_hasher import ( + SemanticAwarePythonHasher, + ) + + return SemanticAwarePythonHasher(hasher_id=label).hash_object(preimage) + + +@final +class IdentityWalk: + """Memoize by object for one walk, so a diamond visits its shared inputs once.""" + + def __init__(self, hasher: SemanticHasherProtocol) -> None: + self.hasher = hasher + self.unbound_slots: set[str] = set() + self._memo: dict[int, IdentityChains] = {} + + def visit(self, element: IdentityChainProtocol) -> IdentityChains: + """Compute the element's chains or reuse them from this walk.""" + key = id(element) + if key not in self._memo: + self._memo[key] = element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Internal back edge of the identity walk. + return self._memo[key] + + +@final +class _InputOccurrence: + """One position in a pod's input list, with access to the original stream. + + Identity-based equality keeps repetitions even inside a frozenset. + """ + + def __init__(self, stream: StreamProtocol, chains: IdentityChains) -> None: + self._stream = stream + self.chains = chains + + def __getattr__(self, name: str) -> object: + return getattr(self._stream, name) + + +@dataclass(frozen=True, slots=True) +class _GroupChains: + """Chains and a structural sort key for an input or a nested symmetry group.""" + + structure_key: tuple[str, ...] + sources: ContentHash | None + names: ContentHash + + +def _pool( + label: str, inputs: tuple[ContentHash, ...], own_term: object | None = None +) -> ContentHash: + """Pass a lone input through, or hash the pool and any node contribution.""" + pooled = inputs[0] if len(inputs) == 1 else _hash(label, inputs) + if own_term is None: + return pooled + return _hash(label, ("term", pooled, own_term)) + + +def _pool_group( + group: object, + source_term: object | None = None, + name_term: object | None = None, +) -> _GroupChains: + """Pool in structural order, breaking structural ties separately per chain.""" + if isinstance(group, _InputOccurrence): + chains = group.chains + return _GroupChains( + (chains.structure.to_hex(),), + chains.sources, + chains.names, + ) + if not isinstance(group, (tuple, frozenset)): + raise TypeError( + "argument_symmetry must group the input occurrences it receives" + ) + + children = [ + _pool_group(child) + for child in cast("tuple[object, ...] | frozenset[object]", group) + ] + symmetric = isinstance(group, frozenset) + if symmetric: + children.sort(key=lambda child: child.structure_key) + structure_key = ( + "{" if symmetric else "(", + *(part for child in children for part in child.structure_key), + "}" if symmetric else ")", + ) + + names: list[ContentHash] = [] + sources: list[ContentHash] = [] + for _, group_members in groupby(children, key=lambda child: child.structure_key): + members = list(group_members) + group_names = [child.names for child in members] + group_sources = [ + child.sources for child in members if child.sources is not None + ] + if symmetric and len(members) > 1: + group_names.sort(key=ContentHash.to_string) + group_sources.sort(key=ContentHash.to_string) + names.extend(group_names) + sources.extend(group_sources) + return _GroupChains( + structure_key, + _pool(SOURCE_CHAIN_HASH_LABEL, tuple(sources), source_term) + if len(sources) == len(children) + else None, + _pool(NAME_CHAIN_HASH_LABEL, tuple(names), name_term), + ) + + +class IdentityChainsMixin(ABC): + """Compute the new accessors without caching a mutable binding or slot name.""" + + @abstractmethod + def pipeline_hash( + self, hasher: SemanticHasherProtocol | None = None + ) -> ContentHash: + """Return the existing structure hash.""" + + @property + @abstractmethod + def _identity_hasher(self) -> SemanticHasherProtocol: + """Hasher used for the existing pipeline hash.""" + + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Inputs in argument order, including repeated streams.""" + return () + + def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: + """Group inputs according to the producer's argument symmetry.""" + return inputs + + def _identity_leaf(self) -> tuple[str, ContentHash | None] | None: + """Return a leaf's slot name and binding identity, if this is a leaf.""" + return None + + def _identity_terms(self) -> tuple[object | None, object | None]: + """Return any terms this element contributes to the source and name chains.""" + return None, None + + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + leaf = self._identity_leaf() + if leaf is not None: + name, source = leaf + if source is None: + walk.unbound_slots.add(name) + return IdentityChains( + self.pipeline_hash(walk.hasher), + source, + _hash(SLOT_NAME_HASH_LABEL, ("slot", name)), + ) + + inputs = self._identity_inputs() + if len(inputs) == 1: + upstream = walk.visit(inputs[0]) + source_term, name_term = self._identity_terms() + return IdentityChains( + self.pipeline_hash(walk.hasher), + _pool(SOURCE_CHAIN_HASH_LABEL, (upstream.sources,), source_term) + if upstream.sources is not None + else None, + _pool(NAME_CHAIN_HASH_LABEL, (upstream.names,), name_term), + ) + + # Feed occurrences to the same symmetry rule as the legacy pipeline hash. + # The latter still operates on stream objects in step 1. + occurrences = tuple( + cast( + "StreamProtocol", + cast(object, _InputOccurrence(stream, walk.visit(stream))), + ) + for stream in inputs + ) + group = self._identity_symmetry(occurrences) if occurrences else () + pooled = _pool_group(group, *self._identity_terms()) + return IdentityChains( + self.pipeline_hash(walk.hasher), pooled.sources, pooled.names + ) + + def source_chain(self) -> ContentHash | None: + """Return the source chain, absent if any contributing slot is unbound.""" + return IdentityWalk(self._identity_hasher).visit(self).sources + + def name_chain(self) -> ContentHash: + """Return the chain of source-slot names.""" + return IdentityWalk(self._identity_hasher).visit(self).names + + def _chain_content_hash(self) -> ContentHash: + """Combine structure and sources. This becomes ``content_hash()`` at the switch. + + Raises: + UnboundSourceError: If any contributing source slot is unbound. + """ + walk = IdentityWalk(self._identity_hasher) + chains = walk.visit(self) + if chains.sources is None: + names = ", ".join(repr(name) for name in sorted(walk.unbound_slots)) + raise UnboundSourceError( + f"Content identity is undefined for unbound source slots {names}." + ) + return _hash(CONTENT_HASH_LABEL, (chains.structure, chains.sources)) + + def node_hash(self) -> ContentHash: + """Combine structure and slot names, independently of binding.""" + chains = IdentityWalk(self._identity_hasher).visit(self) + return _hash(NODE_HASH_LABEL, (chains.structure, chains.names)) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index 13001da6a..5ca155229 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -988,6 +988,18 @@ class FunctionNode(FunctionNodeBase): and serialized to disk via ``Pipeline.save()``. """ + _saved_identity_inputs: tuple[StreamProtocol, ...] | None = None + + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Retain a restored blueprint node's input for its identity walk.""" + if self._saved_identity_inputs is not None: + return self._saved_identity_inputs + return super()._identity_inputs() + + def _identity_leaf(self) -> None: + """A blueprint function remains a computation when its pod is unavailable.""" + return None + def __init__( self, function_pod: FunctionPodProtocol, @@ -1118,6 +1130,7 @@ def from_descriptor( node._function_pod = None node._data_function = None node._input_stream = None + node._saved_identity_inputs = () if input_stream is None else (input_stream,) node.tracker_manager = DEFAULT_TRACKER_MANAGER # Blueprint-level table caches diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 4f4632f3d..03ea3271a 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -295,6 +295,10 @@ def load_status(self) -> Any: def identity_structure(self) -> Any: return self.pipeline_identity_structure() + def _identity_leaf(self) -> None: + """An operator remains a computation when its pod is unavailable.""" + return None + def pipeline_identity_structure(self) -> Any: return (self._operator, self._operator.argument_symmetry(self._input_streams)) @@ -627,6 +631,14 @@ class OperatorNode(OperatorNodeBase): and serialized to disk via ``Pipeline.save()``. """ + _saved_identity_inputs: tuple[StreamProtocol, ...] | None = None + + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Retain a restored blueprint node's inputs for its identity walk.""" + if self._saved_identity_inputs is not None: + return self._saved_identity_inputs + return super()._identity_inputs() + def iter_data(self) -> Iterator[tuple[TagProtocol, DataProtocol]]: """Raise ``PipelineJobRequiredError`` — blueprint nodes cannot produce data. @@ -782,6 +794,7 @@ def from_descriptor( # From OperatorNodeBase node._operator = None node._input_streams = () + node._saved_identity_inputs = tuple(input_streams) node.tracker_manager = DEFAULT_TRACKER_MANAGER # Descriptor metadata for read-only access diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index b6b8bc0f6..435f642df 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -25,6 +25,7 @@ from orcapod.config import OrcapodConfig from orcapod.core.base import TraceableBase from orcapod.core.datagrams import Data, Tag +from orcapod.core.identity_chains import IdentityChainsMixin from orcapod.core.operators.drop_nulls import _without_none # pyright: ignore[reportPrivateUsage] # DropNulls' rule for removing None from a type, shared, never copied from orcapod.core.sources.base import table_is_rows from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -72,6 +73,7 @@ RecordBatchInput, ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol logger = logging.getLogger(__name__) @@ -509,7 +511,7 @@ def _closed_feed(node: SourceNodeBase) -> CompleteStreamFeed: return feed -class SourceNodeBase(TraceableBase, ABC): +class SourceNodeBase(TraceableBase, IdentityChainsMixin, ABC): """Abstract base for SourceNode and SourceJobNode. Provides schema-based identity (content_hash, pipeline_hash) and @@ -744,6 +746,16 @@ def saved_type_texts(self) -> dict[str, Any]: }, } + @property + def _identity_hasher(self) -> SemanticHasherProtocol: + """Use the slot's structural hasher for the walk.""" + return self.data_context.semantic_hasher + + def _identity_leaf(self) -> tuple[str, ContentHash | None]: + """Use the slot's name and the live binding's own content hash.""" + bound = self._bound_stream() + return self.name, None if bound is None else bound.content_hash() + def _bound_stream(self) -> "StreamProtocol | None": """The concrete stream bound to this slot; a declaration has none.""" return None @@ -1447,6 +1459,21 @@ def _declared_zero_row_table(self) -> "pa.Table | None": return pa.Table.from_batches([], schema=pa.schema(fields)) +def slot_name_for(stream: StreamProtocol, content: ContentHash | None = None) -> str: + """Return the current implicit slot name of a stream. + + Root sources use their source name. Other streams use their label and content + digest, as when captured on their own. + """ + from orcapod.core.sources.base import RootSource + + if isinstance(stream, RootSource): + return stream.source_name + if content is None: + content = stream.content_hash() + return f"{stream.label}:{content.to_hex()}" + + class SourceNode(SourceNodeBase): """Schema-only input-slot declaration for ``Pipeline`` recording. @@ -1521,17 +1548,7 @@ def from_stream( if isinstance(stream, SourceNode): return stream tag_schema, data_schema = stream.output_schema() - if name is not None: - slot_name = name - else: - # Local import avoids a module-level circular dependency between - # core.nodes and core.sources. - from orcapod.core.sources.base import RootSource - - if isinstance(stream, RootSource): - slot_name = stream.source_name - else: - slot_name = f"{stream.label}:{stream.content_hash().to_hex()}" + slot_name = name if name is not None else slot_name_for(stream) if not isinstance(stream, SourceNodeBase): _require_stream_arrow_types(stream, slot_name) node = cls( @@ -2174,17 +2191,7 @@ def from_stream( # 2. stream.source_name for RootSource (its id without the kind part) # 3. label + short hash prefix for any other concrete stream type tag_schema, data_schema = stream.output_schema() - if name is not None: - slot_name = name - else: - # Local import avoids a module-level circular dependency between - # core.nodes and core.sources. - from orcapod.core.sources.base import RootSource - - if isinstance(stream, RootSource): - slot_name = stream.source_name - else: - slot_name = f"{stream.label}:{stream.content_hash().to_hex()}" + slot_name = name if name is not None else slot_name_for(stream) _require_stream_arrow_types(stream, slot_name) return cls( name=slot_name, diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index cae6813fe..0afec1e92 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -74,6 +74,7 @@ logger = logging.getLogger(__name__) if TYPE_CHECKING: + from orcapod.protocols.hashing_protocols import IdentityChains, IdentityWalkProtocol from orcapod.protocols.hashing_protocols import SemanticHasherProtocol @@ -1662,6 +1663,26 @@ def last_modified(self) -> Any: source = self._stream if self._stream is not None else self._node return getattr(source, "last_modified", None) + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + """Use the stream this output describes without building its rows.""" + return walk.visit(self._node) + + def source_chain(self) -> ContentHash | None: + """Return the underlying node's source chain.""" + return self._node.source_chain() + + def name_chain(self) -> ContentHash: + """Return the underlying node's name chain.""" + return self._node.name_chain() + + def _chain_content_hash(self) -> ContentHash: + """Return the underlying node's chain-based content hash.""" + return self._node._chain_content_hash() # pyright: ignore[reportPrivateUsage] # Transparent stream wrapper. + + def node_hash(self) -> ContentHash: + """Return the underlying node's node hash.""" + return self._node.node_hash() + def __getattr__(self, name: str) -> Any: # Every other member (``join``, ``as_polars_df``, ...) is the built stream's. return getattr(self.built(), name) @@ -1773,6 +1794,10 @@ def __init__( ) self._input_pipeline_hash: ContentHash = pipeline_hash + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Preserve the restored node's lineage even without its pod.""" + return self.upstreams + def pipeline_hash( self, hasher: SemanticHasherProtocol | None = None ) -> ContentHash: diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index df49eaff6..9486bddfd 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -273,6 +273,10 @@ def _identity_table(self) -> "pa.Table": table, self._tag_columns, self.data_context.arrow_hasher ) + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """A table without a producer hashes as a root.""" + return self.upstreams if self.producer is not None else () + def pipeline_identity_structure(self) -> Any: if self._producer is None or not isinstance( self._producer, PipelineElementProtocol diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 9f8b731f7..42593c634 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -25,6 +25,7 @@ from orcapod.core.base import TraceableBase from orcapod.core.data_tags import data_tag_names +from orcapod.core.identity_chains import IdentityChainsMixin from orcapod.core.streams.record_batch_input import SOURCE_BATCH_ROWS, InputChannel from orcapod.core.streams.view import ( SCHEMA_NEEDS_POLL_NOTE, @@ -34,6 +35,7 @@ preview_html, ) from orcapod.protocols.core_protocols import ( + ArgumentGroup, DataProtocol, PodProtocol, StreamProtocol, @@ -41,10 +43,11 @@ ) from orcapod.protocols.core_protocols.streams import RecordBatchInput from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, Condition, Schema +from orcapod.types import ColumnConfig, Condition, ContentHash, Schema from orcapod.utils import arrow_utils if TYPE_CHECKING: + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from orcapod.types.explanation import Explanation # TODO: consider using this instead of making copy of dicts @@ -750,7 +753,30 @@ def _rename_map( return {str(old): str(new) for old, new in pairs.items()} -class StreamBase(TraceableBase): +class StreamBase(TraceableBase, IdentityChainsMixin): + @property + def _identity_hasher(self) -> SemanticHasherProtocol: + """Use the stream's structural hasher for the walk.""" + return self.data_context.semantic_hasher + + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Return the stream's upstreams in argument order.""" + return self.upstreams + + def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: + """Respect the producer's symmetry, or the saved order when it is absent.""" + producer = self.producer + return inputs if producer is None else producer.argument_symmetry(inputs) + + def _identity_leaf(self) -> tuple[str, ContentHash] | None: + """Reuse the content hash and slot name of a root stream.""" + if self.producer is not None or self._identity_inputs(): + return None + from orcapod.core.nodes.source_node import slot_name_for + + content = self.content_hash() + return slot_name_for(self, content), content + @property @abstractmethod def producer(self) -> PodProtocol | None: ... diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py index 5569222dc..a6955387f 100644 --- a/src/orcapod/pipeline/pod_invocation.py +++ b/src/orcapod/pipeline/pod_invocation.py @@ -10,18 +10,25 @@ from typing import TYPE_CHECKING, Any -from orcapod.core.base import ContentIdentifiableBase +from orcapod.contexts import resolve_context +from orcapod.core.base import ContentIdentifiableBase, PipelineElementBase +from orcapod.core.identity_chains import IdentityChainsMixin if TYPE_CHECKING: from orcapod.protocols.core_protocols import ( + ArgumentGroup, FunctionPodProtocol, OperatorPodProtocol, SideEffectPodProtocol, StreamProtocol, ) + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol + from orcapod.types import ContentHash -class PodInvocation(ContentIdentifiableBase): +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 @@ -70,6 +77,27 @@ def label(self) -> str | None: # Identity — mirrors StreamBase.identity_structure() # ------------------------------------------------------------------ + @property + def _identity_hasher(self) -> SemanticHasherProtocol: + """Use the same structural hasher as the node for this invocation.""" + return resolve_context(self._pod.data_context_key).semantic_hasher + + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: + """Return the recorded arguments in order.""" + return self.input_streams + + def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: + """Respect the recorded pod's argument symmetry.""" + return self._pod.argument_symmetry(inputs) + + def pipeline_hash( + self, hasher: SemanticHasherProtocol | None = None + ) -> ContentHash: + """Return the structure hash of this invocation.""" + return super().pipeline_hash( + self._identity_hasher if hasher is None else hasher + ) + def identity_structure(self) -> Any: """Return ``(pod, pod.argument_symmetry(input_streams))``. diff --git a/src/orcapod/protocols/core_protocols/streams.py b/src/orcapod/protocols/core_protocols/streams.py index c8c72abd6..e9745d372 100644 --- a/src/orcapod/protocols/core_protocols/streams.py +++ b/src/orcapod/protocols/core_protocols/streams.py @@ -13,7 +13,10 @@ from orcapod.protocols.core_protocols.datagrams import DataProtocol, TagProtocol from orcapod.protocols.core_protocols.traceable import TraceableProtocol -from orcapod.protocols.hashing_protocols import PipelineElementProtocol +from orcapod.protocols.hashing_protocols import ( + IdentityChainProtocol, + PipelineElementProtocol, +) from orcapod.types import ColumnConfig, Condition, Schema if TYPE_CHECKING: @@ -80,7 +83,9 @@ def _repr_html_(self) -> str: @runtime_checkable -class StreamProtocol(TraceableProtocol, PipelineElementProtocol, Protocol): +class StreamProtocol( + TraceableProtocol, PipelineElementProtocol, IdentityChainProtocol, Protocol +): """ Base protocol for all streams in Orcapod. diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 2467a92c1..ef8617b7c 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -3,6 +3,7 @@ from __future__ import annotations from collections.abc import Callable +from dataclasses import dataclass from typing import TYPE_CHECKING, Any, Protocol, TypeVar, runtime_checkable from orcapod.types import ContentHash, PathLike, Schema @@ -11,6 +12,50 @@ import pyarrow as pa +@dataclass(frozen=True, slots=True) +class IdentityChains: + """The three chains of one element. An unbound slot leaves sources absent.""" + + structure: ContentHash + sources: ContentHash | None + names: ContentHash + + +class IdentityWalkProtocol(Protocol): + """One traversal with a common structural hasher and live slot bindings.""" + + hasher: SemanticHasherProtocol + unbound_slots: set[str] + + def visit(self, element: IdentityChainProtocol) -> IdentityChains: + """Compute the element's chains or reuse them from this walk.""" + ... + + +class IdentityChainProtocol(Protocol): + """Identity accessors shared by streams, nodes and recorded invocations.""" + + def source_chain(self) -> ContentHash | None: + """Return the source chain, absent if any contributing slot is unbound.""" + ... + + def name_chain(self) -> ContentHash: + """Return the chain of source-slot names.""" + ... + + def _chain_content_hash(self) -> ContentHash: + """Combine structure and sources, raising for unbound slots.""" + ... + + def node_hash(self) -> ContentHash: + """Combine structure and slot names, independently of binding.""" + ... + + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + """Compute the three chains together in an existing walk.""" + ... + + @runtime_checkable class DataContextAwareProtocol(Protocol): """Protocol for objects aware of their data context.""" diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py index a202e7404..c63e346b4 100644 --- a/tests/test_core/test_order_invariance.py +++ b/tests/test_core/test_order_invariance.py @@ -279,6 +279,8 @@ def identity(stream: Any) -> dict[str, Any]: return { "content_hash": stream.content_hash().to_string(), "pipeline_hash": stream.pipeline_hash().to_string(), + "chain_content_hash": stream._chain_content_hash().to_string(), + "node_hash": stream.node_hash().to_string(), "system_tag_names": sorted(k for k in all_tags if k not in tag_keys), "output_schema": ( sorted((k, repr(t)) for k, t in tag_schema.items()), @@ -1125,6 +1127,8 @@ def _job( out[f"{label}.hashes"] = ( node.content_hash().to_string(), node.pipeline_hash().to_string(), + node._chain_content_hash().to_string(), + node.node_hash().to_string(), ) out[f"{label}.rows"] = row_identity(list(node.iter_data())) derived = job.nodes["pod" if pod else "join"].as_source() diff --git a/tests/test_hashing/hash_site_trace.py b/tests/test_hashing/hash_site_trace.py index 6d83ffe04..624a3048f 100644 --- a/tests/test_hashing/hash_site_trace.py +++ b/tests/test_hashing/hash_site_trace.py @@ -262,6 +262,21 @@ def run_scenario() -> None: from tests.test_hashing.golden import cases _ = cases.compute_all() + from orcapod.operators import Join + from orcapod.sources import DictSource + + left, right = ( + DictSource( + [{"tag": 1}], + tag_columns=["tag"], + tag_only_columns=False, + source_id=name, + ) + for name in ("chain-left", "chain-right") + ) + joined = Join()(left, right) + _ = joined._chain_content_hash() + _ = joined.node_hash() hasher = get_default_context().semantic_hasher with tempfile.TemporaryDirectory() as tmp: root = _Path(tmp) diff --git a/tests/test_hashing/test_hash_grammar.py b/tests/test_hashing/test_hash_grammar.py index 7de011bd1..6cf5d3688 100644 --- a/tests/test_hashing/test_hash_grammar.py +++ b/tests/test_hashing/test_hash_grammar.py @@ -43,6 +43,11 @@ "torch_tensor_v1", "group_v1", "batch_v1", + "slot_name_v1", + "source_chain_v1", + "name_chain_v1", + "content_hash_v1", + "node_hash_v1", } diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 22f4c9d4f..bbf91d8e0 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -818,6 +818,11 @@ def test_identity_does_not_cover_the_derived_content_hash_column(self) -> None: "polars_series_v1": "hashing/semantic_hashing/builtin_handlers.py", "group_v1": "core/operators/group_by.py", "batch_v1": "core/operators/batch.py", + "slot_name_v1": "core/identity_chains.py", + "source_chain_v1": "core/identity_chains.py", + "name_chain_v1": "core/identity_chains.py", + "content_hash_v1": "core/identity_chains.py", + "node_hash_v1": "core/identity_chains.py", } diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py new file mode 100644 index 000000000..201feb6a8 --- /dev/null +++ b/tests/test_hashing/test_identity_chains.py @@ -0,0 +1,304 @@ +"""Three-chain identities are available alongside the legacy hashes.""" + +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING + +import pytest + +from orcapod import Pipeline, PipelineJob, SourceNode, function_pod +from orcapod.core.identity_chains import NAME_CHAIN_HASH_LABEL, SOURCE_CHAIN_HASH_LABEL +from orcapod.databases import InMemoryArrowDatabase +from orcapod.errors import UnboundSourceError +from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher +from orcapod.operators import Index, Join, MergeJoin, Rejoin +from orcapod.sources import DictSource +from orcapod.types import ContentHash + +if TYPE_CHECKING: + from pathlib import Path + + from orcapod.protocols.hashing_protocols import IdentityChainProtocol + + +@function_pod(output_keys="total") +def add(x: int, y: int) -> int: + """Add two data columns.""" + return x + y + + +@function_pod(output_keys="doubled") +def double(total: int) -> int: + """Double the previous step's output.""" + return 2 * total + + +def _source( + name: str, reverse: bool, *, shift: int = 0, right: bool = False +) -> DictSource: + """Build a two-tag, two-data source in either column order.""" + x, y = ("u", "v") if right else ("x", "y") + rows = [ + {"region": "north", "item": 1, x: 5 + shift, y: 7}, + {"region": "south", "item": 2, x: 11 + shift, y: 13}, + ] + tags = ["region", "item"] + if reverse: + rows = [dict(reversed(tuple(row.items()))) for row in rows] + tags.reverse() + return DictSource(rows, tag_columns=tags, tag_only_columns=True, source_id=name) + + +def _hashes(element: IdentityChainProtocol) -> tuple[object, object]: + """Read both combined hashes before the content hash switch.""" + return element._chain_content_hash(), element.node_hash() + + +def _run(job: PipelineJob, run_async: bool) -> None: + """Execute the job on the requested path.""" + if run_async: + asyncio.run(job.run_async()) + else: + job.run() + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_chain_agrees_across_plain_recorded_and_job_forms( + reverse: bool, run_async: bool +) -> None: + source = _source("reading", reverse) + first = add.pod(source) + plain = double.pod(first) + blueprint = Pipeline(name="chain") + with blueprint: + double.pod(add.pod(source, label="first"), label="last") + job = PipelineJob.from_pipeline( + blueprint, + database=InMemoryArrowDatabase(), + sources={"reading": source}, + ) + _run(job, run_async) + # to_invocations() returns the compiled blueprint with *unbound* slots. + # Inspect the actual recording, whose upstreams are the original streams. + recorded = next( + inv for inv in blueprint._invocation_lut.values() if inv.label == "last" + ) + node = job.nodes["last"] + assert plain.pipeline_hash() == recorded.pipeline_hash() == node.pipeline_hash() + assert _hashes(plain) == _hashes(recorded) == _hashes(node) + assert plain.source_chain() == first.source_chain() == source.content_hash() + assert plain.name_chain() == first.name_chain() == source.name_chain() + assert node.source_chain() == job.nodes["first"].source_chain() + assert node.name_chain() == job.nodes["first"].name_chain() + assert plain.node_hash() != first.node_hash() + assert plain._chain_content_hash() != first._chain_content_hash() + assert _hashes(double.pod(first, label="another label")) == _hashes(plain) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_diamond_pools_both_occurrences(reverse: bool, run_async: bool) -> None: + source = _source("diamond", reverse) + x = source.select_data_columns(["x"]) + y = source.select_data_columns(["y"]) + diamond = Rejoin()(x, y) + assert diamond.source_chain() != source.source_chain() + assert diamond.name_chain() != source.name_chain() + assert _hashes(diamond) == _hashes(Rejoin()(y, x)) + + job = PipelineJob(name="diamond", database=InMemoryArrowDatabase()) + with job: + left = source.select_data_columns(["x"], label="left") + right = source.select_data_columns(["y"], label="right") + Rejoin()(left, right, label="diamond_result") + _run(job, run_async) + assert _hashes(job.nodes["diamond_result"]) == _hashes(diamond) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_slots_keep_their_names_across_bindings(reverse: bool, run_async: bool) -> None: + source = _source("reading-one", reverse) + other = _source("reading-two", reverse, shift=100) + x = SourceNode.from_stream(source, name="x_slot") + y = SourceNode.from_stream(source, name="y_slot") + blueprint = Pipeline(name="two_slots") + with blueprint: + double.pod(add.pod(x, label="x_first"), label="x_last") + double.pod(add.pod(y, label="y_first"), label="y_last") + + invocations = blueprint.to_invocations().invocations + assert {inv.label for inv in invocations} == { + "x_first", + "y_first", + "x_last", + "y_last", + } + for invocation in invocations: + assert invocation.label is not None + assert invocation.source_chain() is None + assert invocation.node_hash() == blueprint.nodes[invocation.label].node_hash() + + job = PipelineJob.from_pipeline( + blueprint, + database=InMemoryArrowDatabase(), + sources={"x_slot": source, "y_slot": other}, + ) + _run(job, run_async) + x_node, y_node = job.nodes["x_last"], job.nodes["y_last"] + structure = x_node.pipeline_hash() + x_content, x_name = _hashes(x_node) + y_content, y_name = _hashes(y_node) + assert structure == y_node.pipeline_hash() + assert x_content != y_content + assert x_name != y_name + assert x_name == blueprint.nodes["x_last"].node_hash() + assert y_name == blueprint.nodes["y_last"].node_hash() + + # Step 1 still uses legacy keys. Compare the two chains on the extant + # nodes after the bind, without relying on execution of content-equal nodes. + job.bind(sources={"y_slot": source}) + assert x_node.pipeline_hash() == y_node.pipeline_hash() == structure + assert _hashes(x_node) == (x_content, x_name) + assert _hashes(y_node) == (x_content, y_name) + assert ( + job.nodes["x_first"]._chain_content_hash() + == job.nodes["y_first"]._chain_content_hash() + ) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_ordered_and_commutative_operators(reverse: bool, run_async: bool) -> None: + left = _source("left", reverse) + right = _source("right", reverse, right=True) + assert left.pipeline_hash() != right.pipeline_hash() + ordered = MergeJoin()(left, right) + swapped = MergeJoin()(right, left) + assert ordered.source_chain() != swapped.source_chain() + assert ordered.name_chain() != swapped.name_chain() + assert ordered._chain_content_hash() != swapped._chain_content_hash() + assert ordered.node_hash() != swapped.node_hash() + + commutative = Join()(left, right) + assert _hashes(commutative) == _hashes(Join()(right, left)) + assert commutative.source_chain() == Join()(right, left).source_chain() + assert commutative.name_chain() == Join()(right, left).name_chain() + + job = PipelineJob(name="join_order", database=InMemoryArrowDatabase()) + with job: + MergeJoin()(left, right, label="ordered") + MergeJoin()(right, left, label="swapped") + Join()(right, left, label="commutative") + _run(job, run_async) + assert _hashes(job.nodes["ordered"]) == _hashes(ordered) + assert _hashes(job.nodes["swapped"]) == _hashes(swapped) + assert _hashes(job.nodes["commutative"]) == _hashes(commutative) + + +def test_unbound_blueprint_names_all_upstream_slots() -> None: + source = _source("reading", False) + left = SourceNode.from_stream(source, name="left_slot") + right = SourceNode.from_stream(source, name="right_slot") + pipeline = Pipeline(name="unbound") + with pipeline: + MergeJoin()(left, right, label="result") + invocation = pipeline.to_invocations().invocations[0] + result = pipeline.nodes["result"] + assert result.pipeline_hash() == invocation.pipeline_hash() + assert result.node_hash() == invocation.node_hash() + for element in (invocation, result): + assert element.source_chain() is None + with pytest.raises(UnboundSourceError, match="unbound.*left_slot.*right_slot"): + element._chain_content_hash() + + +@pytest.mark.filterwarnings("ignore:Index is provisional") +def test_loaded_blueprint_computes_names_through_a_missing_pod(tmp_path: Path) -> None: + source = _source("reading", False) + lists = DictSource( + [{"item": 1, "region": "north", "values": [1, 2], "y": 3}], + tag_columns=["item", "region"], + tag_only_columns=True, + source_id="lists", + ) + pipeline = Pipeline(name="saved") + with pipeline: + add.pod(source, label="first") + Index(column="values", i=0)(lists, label="picked") + expected = {label: node.node_hash() for label, node in pipeline.nodes.items()} + path = tmp_path / "blueprint.json" + pipeline.save(path) + loaded = Pipeline.load(path) + for label, slot in (("first", "reading"), ("picked", "lists")): + node = loaded.nodes[label] + assert node.producer is None + assert node.node_hash() == expected[label] + with pytest.raises(UnboundSourceError, match=f"unbound.*{slot}"): + node._chain_content_hash() + + +def _data_tags(name: str, reverse: bool = False) -> DictSource: + """A source on which two inputs with identical structure can be joined.""" + tags = ["region", "item", "x", "y"] + rows = [ + {"region": "north", "item": 1, "x": 3, "y": 5}, + {"region": "south", "item": 2, "x": 7, "y": 11}, + ] + if reverse: + tags.reverse() + rows = [dict(reversed(tuple(row.items()))) for row in rows] + return DictSource( + rows, + tag_columns=tags, + tag_only_columns=["region", "item"], + source_id=name, + ) + + +@pytest.mark.parametrize("reverse", [False, True]) +@pytest.mark.parametrize("run_async", [False, True]) +def test_commutative_equal_structure_sorts_the_chains_independently( + reverse: bool, run_async: bool +) -> None: + left, right = _data_tags("a", reverse), _data_tags("b", reverse) + assert left.pipeline_hash() == right.pipeline_hash() + result = Join()(left, right) + swapped = Join()(right, left) + left_source, right_source = left.source_chain(), right.source_chain() + assert left_source is not None and right_source is not None + sources = tuple(sorted((left_source, right_source), key=ContentHash.to_string)) + names = tuple( + sorted((left.name_chain(), right.name_chain()), key=ContentHash.to_string) + ) + assert ( + result.source_chain() + == swapped.source_chain() + == SemanticAwarePythonHasher(hasher_id=SOURCE_CHAIN_HASH_LABEL).hash_object( + sources + ) + ) + assert ( + result.name_chain() + == swapped.name_chain() + == SemanticAwarePythonHasher(hasher_id=NAME_CHAIN_HASH_LABEL).hash_object(names) + ) + assert _hashes(result) == _hashes(swapped) + repeat = Join()(left, left) + assert repeat.source_chain() != left.source_chain() + assert repeat.name_chain() != left.name_chain() + + job = PipelineJob(name="tie", database=InMemoryArrowDatabase()) + with job: + Join()(right, left, label="joined") + _run(job, run_async) + 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: + 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() From 4b210551450c3a9bd1ca3945f217e55bdff9ea46 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:02:27 -0800 Subject: [PATCH 02/38] fix(identity): preserve chains across binding and persistence --- changelog.d/ITL-1559.md | 2 + docs/reference/hashing.md | 14 +- src/orcapod/core/identity_chains.py | 249 ++++++++++++++---- src/orcapod/core/nodes/function_node.py | 4 +- src/orcapod/core/nodes/operator_node.py | 13 +- src/orcapod/core/nodes/source_node.py | 23 +- src/orcapod/core/operators/base.py | 12 +- src/orcapod/core/operators/batch.py | 10 +- .../core/operators/static_output_pod.py | 34 ++- src/orcapod/core/sources/polling_source.py | 9 +- .../core/streams/arrow_table_stream.py | 14 +- src/orcapod/core/streams/base.py | 17 +- src/orcapod/pipeline/graph.py | 12 + src/orcapod/protocols/hashing_protocols.py | 4 +- tests/test_channels/test_polling_source.py | 38 +++ tests/test_hashing/test_identity_chains.py | 180 +++++++++++++ 16 files changed, 548 insertions(+), 87 deletions(-) diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 573c0f866..b3d205419 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -1,3 +1,5 @@ ### Added - Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. Existing pipeline and content hashes keep their values. + +- Saved operator descriptors can retain input symmetry so a job loaded without its operator implementation reports the same chain-based hashes as the live job. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index f71f5da7b..2d1fa7528 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -300,7 +300,8 @@ reordered. A stream, invocation or job node carries three chains. `pipeline_hash()` describes the structure. `source_chain()` starts at each slot with the bound source's own content hash. -`name_chain()` starts with the slot's name. A single-input step passes both chains +`name_chain()` starts with the slot's name. A raw stream outside a slot contributes +an anonymous name term. Display labels do not participate. A single-input step passes both chains through unchanged unless the step contributes a term of its own. Multiple inputs are pooled in argument order for an ordered operator and by pipeline hash for a commutative operator. Within a pipeline-hash tie, the source and name chains each sort their own values. Repeated inputs contribute @@ -312,7 +313,14 @@ contributing slot is unbound. The chain-based content hash is available internal `_chain_content_hash()` until the switch to `content_hash()`. Orcapod continues to use the existing hashes for graph keys and persistence. ITL-1590 tracks cases where the existing pipeline hash depends on source equality within a commutative input tie. -A read-only operator whose pod cannot be restored uses its saved input order. +An operator descriptor records nondefault input grouping in its optional +`input_symmetry` field. A read-only operator uses that grouping when its pod cannot +be restored. Older descriptors without this field use their saved argument order +when the pod is unavailable. + +A polling source can report its source and name chains before it knows its schema. +Its combined hashes require the pipeline hash, so they raise `ValueError` until +the source declares a schema or commits its first batch. ## Hash site inventory @@ -339,7 +347,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | What is hashed | Algorithm / label | Used as | Call sites | |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | -| three-chain hashes | a slot name, a pool of upstream chains, or the pipeline hash paired with one chain | SHA-256 of canonical JSON, with the corresponding chain or combined-hash label | into a hash for chain pooling and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool`, `core/identity_chains.py:IdentityChainsMixin._identity_chains`, `core/identity_chains.py:IdentityChainsMixin._chain_content_hash`, `core/identity_chains.py:IdentityChainsMixin.node_hash` | +| three-chain hashes | a slot name, a pool of upstream chains, or the pipeline hash paired with one chain | SHA-256 of canonical JSON, with the corresponding chain or combined-hash label | into a hash for chain pooling and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool`, `core/identity_chains.py:IdentityChainsMixin._identity_hash`, `core/identity_chains.py:IdentityChainsMixin._compute_identity_chains..`, `core/identity_chains.py:IdentityChainsMixin._chain_content_hash`, `core/identity_chains.py:IdentityChainsMixin.node_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | | file hasher | a file's bytes | the configured digest function, label = its name (`sha256` in the data context; others: ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 5e5eeae7d..383dd8534 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -3,9 +3,12 @@ from __future__ import annotations from abc import ABC, abstractmethod +from collections.abc import Callable from dataclasses import dataclass +from functools import cached_property from itertools import groupby from typing import TYPE_CHECKING, cast, final +from weakref import WeakValueDictionary from orcapod.errors import UnboundSourceError from orcapod.protocols.hashing_protocols import IdentityChains @@ -37,19 +40,26 @@ def _hash(label: str, preimage: tuple[object, ...]) -> ContentHash: @final class IdentityWalk: - """Memoize by object for one walk, so a diamond visits its shared inputs once.""" + """Walk uncached inputs and connect their caches to their dependents.""" def __init__(self, hasher: SemanticHasherProtocol) -> None: self.hasher = hasher - self.unbound_slots: set[str] = set() - self._memo: dict[int, IdentityChains] = {} + self._consumer: IdentityChainsMixin | None = None def visit(self, element: IdentityChainProtocol) -> IdentityChains: - """Compute the element's chains or reuse them from this walk.""" - key = id(element) - if key not in self._memo: - self._memo[key] = element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Internal back edge of the identity walk. - return self._memo[key] + """Reuse the node's cached chains, recording dependencies through wrappers.""" + if not isinstance(element, IdentityChainsMixin): + return element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Transparent stream wrapper. + + consumer = self._consumer + if consumer is not None: + element._identity_dependents[id(consumer)] = consumer + consumer._identity_dependencies[id(element)] = element + self._consumer = element + try: + return element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Internal back edge of the identity walk. + finally: + self._consumer = consumer @final @@ -59,14 +69,63 @@ class _InputOccurrence: Identity-based equality keeps repetitions even inside a frozenset. """ - def __init__(self, stream: StreamProtocol, chains: IdentityChains) -> None: + def __init__(self, stream: StreamProtocol, index: int) -> None: self._stream = stream - self.chains = chains + self.index = index def __getattr__(self, name: str) -> object: return getattr(self._stream, name) +# JSON needs one explicit marker to distinguish symmetric groups from lists. +INPUT_SYMMETRY_KEY = "input_symmetry" +InputSymmetry = int | list["InputSymmetry"] | dict[str, list["InputSymmetry"]] + + +def encode_input_symmetry( + inputs: tuple[StreamProtocol, ...], + symmetry: Callable[[tuple[StreamProtocol, ...]], ArgumentGroup], +) -> InputSymmetry | None: + """Encode a nondefault grouping by argument position, preserving repetitions.""" + + def encode(group: object) -> InputSymmetry: + if isinstance(group, _InputOccurrence): + return group.index + if isinstance(group, tuple): + return [encode(child) for child in cast("tuple[object, ...]", group)] + if isinstance(group, frozenset): + children = [encode(child) for child in cast("frozenset[object]", group)] + return {"symmetric": sorted(children, key=repr)} + raise TypeError( + "argument_symmetry must group the input occurrences it receives" + ) + + if len(inputs) < 2: + return None + grouped = encode(symmetry(_occurrences(inputs))) + return None if grouped == list(range(len(inputs))) else grouped + + +def decode_input_symmetry( + group: InputSymmetry, inputs: tuple[StreamProtocol, ...] +) -> ArgumentGroup: + """Apply the saved grouping to the current input occurrences.""" + if isinstance(group, int): + return inputs[group] + if isinstance(group, list): + return tuple(decode_input_symmetry(child, inputs) for child in group) + return frozenset( + decode_input_symmetry(child, inputs) for child in group["symmetric"] + ) + + +def _occurrences(inputs: tuple[StreamProtocol, ...]) -> tuple[StreamProtocol, ...]: + return tuple( + cast("StreamProtocol", cast(object, _InputOccurrence(stream, index))) + for index, stream in enumerate(inputs) + ) + + @dataclass(frozen=True, slots=True) class _GroupChains: """Chains and a structural sort key for an input or a nested symmetry group.""" @@ -77,35 +136,35 @@ class _GroupChains: def _pool( - label: str, inputs: tuple[ContentHash, ...], own_term: object | None = None + hash_term: Callable[[str, tuple[object, ...]], ContentHash], + label: str, + inputs: tuple[ContentHash, ...], + own_term: object | None = None, ) -> ContentHash: """Pass a lone input through, or hash the pool and any node contribution.""" - pooled = inputs[0] if len(inputs) == 1 else _hash(label, inputs) + pooled = inputs[0] if len(inputs) == 1 else hash_term(label, inputs) if own_term is None: return pooled - return _hash(label, ("term", pooled, own_term)) + return hash_term(label, ("term", pooled, own_term)) def _pool_group( group: object, + inputs: tuple[_GroupChains, ...], + hash_term: Callable[[str, tuple[object, ...]], ContentHash], source_term: object | None = None, name_term: object | None = None, ) -> _GroupChains: """Pool in structural order, breaking structural ties separately per chain.""" if isinstance(group, _InputOccurrence): - chains = group.chains - return _GroupChains( - (chains.structure.to_hex(),), - chains.sources, - chains.names, - ) + return inputs[group.index] if not isinstance(group, (tuple, frozenset)): raise TypeError( "argument_symmetry must group the input occurrences it receives" ) children = [ - _pool_group(child) + _pool_group(child, inputs, hash_term) for child in cast("tuple[object, ...] | frozenset[object]", group) ] symmetric = isinstance(group, frozenset) @@ -132,15 +191,72 @@ def _pool_group( sources.extend(group_sources) return _GroupChains( structure_key, - _pool(SOURCE_CHAIN_HASH_LABEL, tuple(sources), source_term) + _pool(hash_term, SOURCE_CHAIN_HASH_LABEL, tuple(sources), source_term) if len(sources) == len(children) else None, - _pool(NAME_CHAIN_HASH_LABEL, tuple(names), name_term), + _pool(hash_term, NAME_CHAIN_HASH_LABEL, tuple(names), name_term), ) class IdentityChainsMixin(ABC): - """Compute the new accessors without caching a mutable binding or slot name.""" + """Memoize chains per node and invalidate descendants of a changed slot.""" + + # Defaults cover loaded stubs constructed without __init__. + _identity_cache: dict[str, IdentityChains] | None = None + _identity_name_hashes: dict[tuple[str, tuple[object, ...]], ContentHash] | None = ( + None + ) + _identity_source_hashes: ( + dict[tuple[str, tuple[object, ...]], ContentHash] | None + ) = None + + @cached_property + def _identity_dependents(self) -> WeakValueDictionary[int, IdentityChainsMixin]: + """Weak inverse edges of the computed identity graph.""" + return WeakValueDictionary() + + @cached_property + def _identity_dependencies(self) -> WeakValueDictionary[int, IdentityChainsMixin]: + """Inputs used by the cached chains, including a slot's current binding.""" + return WeakValueDictionary() + + def _invalidate_identity_chains(self, *, names: bool = False) -> None: + """Invalidate cached chains below this node, keeping name hashes on bind.""" + pending: list[IdentityChainsMixin] = [self] + seen: set[int] = set() + while pending: + node = pending.pop() + key = id(node) + if key in seen: + continue + seen.add(key) + node._identity_cache = None + node._identity_source_hashes = None + if names: + node._identity_name_hashes = None + pending.extend(node._identity_dependents.values()) + for dependency in list(node._identity_dependencies.values()): + dependency._identity_dependents.pop(key, None) + node._identity_dependencies.clear() + + def _identity_hash(self, label: str, preimage: tuple[object, ...]) -> ContentHash: + """Reuse canonical hash terms across chain reads and unchanged name inputs.""" + if label in (SOURCE_CHAIN_HASH_LABEL, CONTENT_HASH_LABEL): + if self._identity_source_hashes is None: + self._identity_source_hashes = {} + hashes = self._identity_source_hashes + else: + if self._identity_name_hashes is None: + self._identity_name_hashes = {} + hashes = self._identity_name_hashes + key = (label, preimage) + if key not in hashes: + hashes[key] = _hash(label, preimage) + return hashes[key] + + def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: + """Use the legacy structure, evaluated only when a consumer needs it.""" + return self.pipeline_hash(hasher) @abstractmethod def pipeline_hash( @@ -161,7 +277,9 @@ def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGrou """Group inputs according to the producer's argument symmetry.""" return inputs - def _identity_leaf(self) -> tuple[str, ContentHash | None] | None: + def _identity_leaf( + self, walk: IdentityWalkProtocol + ) -> tuple[str | None, ContentHash | None] | None: """Return a leaf's slot name and binding identity, if this is a leaf.""" return None @@ -170,42 +288,70 @@ def _identity_terms(self) -> tuple[object | None, object | None]: return None, None def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: - leaf = self._identity_leaf() + if self._identity_cache is None: + self._identity_cache = {} + key = walk.hasher.hasher_id + if key not in self._identity_cache: + self._identity_cache[key] = self._compute_identity_chains(walk) + return self._identity_cache[key] + + def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + leaf = self._identity_leaf(walk) if leaf is not None: name, source = leaf - if source is None: - walk.unbound_slots.add(name) return IdentityChains( - self.pipeline_hash(walk.hasher), + self._identity_pipeline_hash, source, - _hash(SLOT_NAME_HASH_LABEL, ("slot", name)), + self._identity_hash(SLOT_NAME_HASH_LABEL, ("slot", name)), + frozenset((name,)) + if name is not None and source is None + else frozenset(), ) inputs = self._identity_inputs() - if len(inputs) == 1: - upstream = walk.visit(inputs[0]) - source_term, name_term = self._identity_terms() + source_term, name_term = self._identity_terms() + upstreams = tuple(walk.visit(stream) for stream in inputs) + if len(upstreams) == 1: + upstream = upstreams[0] return IdentityChains( - self.pipeline_hash(walk.hasher), - _pool(SOURCE_CHAIN_HASH_LABEL, (upstream.sources,), source_term) + self._identity_pipeline_hash, + _pool( + self._identity_hash, + SOURCE_CHAIN_HASH_LABEL, + (upstream.sources,), + source_term, + ) if upstream.sources is not None else None, - _pool(NAME_CHAIN_HASH_LABEL, (upstream.names,), name_term), + _pool( + self._identity_hash, + NAME_CHAIN_HASH_LABEL, + (upstream.names,), + name_term, + ), + upstream.unbound_slots, ) - # Feed occurrences to the same symmetry rule as the legacy pipeline hash. - # The latter still operates on stream objects in step 1. - occurrences = tuple( - cast( - "StreamProtocol", - cast(object, _InputOccurrence(stream, walk.visit(stream))), + # Symmetric groups use structural ordering. Occurrences keep repeats. + group = self._identity_symmetry(_occurrences(inputs)) if inputs else () + children = tuple( + _GroupChains( + (upstream.pipeline_hash(walk.hasher).to_hex(),), + upstream.sources, + upstream.names, ) - for stream in inputs + for upstream in upstreams + ) + pooled = _pool_group( + group, children, self._identity_hash, source_term, name_term ) - group = self._identity_symmetry(occurrences) if occurrences else () - pooled = _pool_group(group, *self._identity_terms()) return IdentityChains( - self.pipeline_hash(walk.hasher), pooled.sources, pooled.names + self._identity_pipeline_hash, + pooled.sources, + pooled.names, + frozenset( + name for upstream in upstreams for name in upstream.unbound_slots + ), ) def source_chain(self) -> ContentHash | None: @@ -225,13 +371,18 @@ def _chain_content_hash(self) -> ContentHash: walk = IdentityWalk(self._identity_hasher) chains = walk.visit(self) if chains.sources is None: - names = ", ".join(repr(name) for name in sorted(walk.unbound_slots)) + names = ", ".join(repr(name) for name in sorted(chains.unbound_slots)) raise UnboundSourceError( f"Content identity is undefined for unbound source slots {names}." ) - return _hash(CONTENT_HASH_LABEL, (chains.structure, chains.sources)) + return self._identity_hash( + CONTENT_HASH_LABEL, (chains.pipeline_hash(walk.hasher), chains.sources) + ) def node_hash(self) -> ContentHash: """Combine structure and slot names, independently of binding.""" - chains = IdentityWalk(self._identity_hasher).visit(self) - return _hash(NODE_HASH_LABEL, (chains.structure, chains.names)) + walk = IdentityWalk(self._identity_hasher) + chains = walk.visit(self) + return self._identity_hash( + NODE_HASH_LABEL, (chains.pipeline_hash(walk.hasher), chains.names) + ) diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py index fa0ae2ea7..687eaccd1 100644 --- a/src/orcapod/core/nodes/function_node.py +++ b/src/orcapod/core/nodes/function_node.py @@ -109,6 +109,7 @@ TrackerManagerProtocol, ) from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.hashing_protocols import IdentityWalkProtocol from orcapod.protocols.observability_protocols import ( DataExecutionLoggerProtocol, ExecutionObserverProtocol, @@ -557,6 +558,7 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: if len(value) != 1: raise ValueError("FunctionPod can only have one upstream") self._input_stream = value[0] + self._invalidate_identity_chains(names=True) self._forget_output_schema() # ------------------------------------------------------------------ @@ -996,7 +998,7 @@ def _identity_inputs(self) -> tuple[StreamProtocol, ...]: return self._saved_identity_inputs return super()._identity_inputs() - def _identity_leaf(self) -> None: + def _identity_leaf(self, walk: IdentityWalkProtocol) -> None: """A blueprint function remains a computation when its pod is unavailable.""" return None diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 03ea3271a..55b469c4b 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -29,6 +29,7 @@ import pyarrow.compute as pc from orcapod import contexts +from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY, decode_input_symmetry from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -84,6 +85,7 @@ with_data_context, ) from orcapod.protocols.core_protocols import ( + ArgumentGroup, DataProtocol, StreamProtocol, TagProtocol, @@ -91,6 +93,7 @@ ) from orcapod.protocols.core_protocols.operator_pod import OperatorPodProtocol from orcapod.protocols.database_protocols import ArrowDatabaseProtocol +from orcapod.protocols.hashing_protocols import IdentityWalkProtocol from orcapod.system_constants import OPERATOR_DB_SCHEMA_VERSION, constants import orcapod.core.row_ids as row_ids from orcapod.types import CacheMode, ColumnConfig, ContentHash, Schema @@ -295,7 +298,7 @@ def load_status(self) -> Any: def identity_structure(self) -> Any: return self.pipeline_identity_structure() - def _identity_leaf(self) -> None: + def _identity_leaf(self, walk: IdentityWalkProtocol) -> None: """An operator remains a computation when its pod is unavailable.""" return None @@ -336,6 +339,13 @@ def pipeline_hash(self, hasher=None) -> ContentHash: # Stream interface # ------------------------------------------------------------------ + def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: + """Recover the grouping of a saved operator when its producer is missing.""" + saved = self._descriptor.get(INPUT_SYMMETRY_KEY) + if self._operator is None and saved is not None: + return decode_input_symmetry(saved, inputs) + return super()._identity_symmetry(inputs) + @property def producer(self) -> OperatorPodProtocol: return self._operator @@ -377,6 +387,7 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None: refuse_restricted_operator_cache(self, self.cache_mode, streams=value) self._input_streams = value + self._invalidate_identity_chains(names=True) self._forget_output_schema() @property diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 435f642df..f0035ed62 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -73,7 +73,10 @@ RecordBatchInput, ) from orcapod.protocols.observability_protocols import ExecutionObserverProtocol - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol + from orcapod.protocols.hashing_protocols import ( + IdentityWalkProtocol, + SemanticHasherProtocol, + ) logger = logging.getLogger(__name__) @@ -751,10 +754,21 @@ def _identity_hasher(self) -> SemanticHasherProtocol: """Use the slot's structural hasher for the walk.""" return self.data_context.semantic_hasher - def _identity_leaf(self) -> tuple[str, ContentHash | None]: - """Use the slot's name and the live binding's own content hash.""" + def _identity_leaf( + self, walk: IdentityWalkProtocol + ) -> tuple[str, ContentHash | None]: + """Use the declared slot name and follow the binding to a concrete source.""" bound = self._bound_stream() - return self.name, None if bound is None else bound.content_hash() + if bound is None: + return self.name, None + from orcapod.core.sources.base import RootSource + + if isinstance(bound, RootSource): + return self.name, bound.content_hash() + sources = walk.visit(bound).sources + if sources is None or isinstance(bound, SourceNodeBase): + return self.name, sources + return self.name, bound.content_hash() def _bound_stream(self) -> "StreamProtocol | None": """The concrete stream bound to this slot; a declaration has none.""" @@ -1723,6 +1737,7 @@ def _bind(self, value: StreamProtocol | None) -> None: self._declared_form = form self._invalidate_content_hash_cache() self._invalidate_pipeline_hash_cache() + self._invalidate_identity_chains() @property def last_modified(self) -> datetime | None: diff --git a/src/orcapod/core/operators/base.py b/src/orcapod/core/operators/base.py index f4baa10f3..e918095a3 100644 --- a/src/orcapod/core/operators/base.py +++ b/src/orcapod/core/operators/base.py @@ -267,7 +267,9 @@ async def async_execute( # The typed empty stream the sync path returns needs a schema the # channel does not carry (ITL-858), so nothing is emitted (ITL-865). return - stream = self._materialize_input_stream(rows, input_pipeline_hashes[0]) + stream = self._materialize_input_stream( + rows, input_pipeline_hashes[0], inputs[0] + ) result = self.static_process(stream) for tag, data in result.iter_data(): await output.send((tag, data)) @@ -385,8 +387,12 @@ async def async_execute( # empty stream needs a schema the channels do not carry (ITL-858), # so nothing is emitted (ITL-865). return - left_stream = self._materialize_input_stream(left_rows, left_hash) - right_stream = self._materialize_input_stream(right_rows, right_hash) + left_stream = self._materialize_input_stream( + left_rows, left_hash, inputs[0] + ) + right_stream = self._materialize_input_stream( + right_rows, right_hash, inputs[1] + ) result = self.static_process(left_stream, right_stream) for tag, data in result.iter_data(): await output.send((tag, data)) diff --git a/src/orcapod/core/operators/batch.py b/src/orcapod/core/operators/batch.py index e7a1969f8..af6b26b6e 100644 --- a/src/orcapod/core/operators/batch.py +++ b/src/orcapod/core/operators/batch.py @@ -280,7 +280,9 @@ async def async_execute( # Must collect all rows — barrier fallback rows = await inputs[0].collect() if rows: - stream = self._materialize_input_stream(rows, pipeline_hash) + stream = self._materialize_input_stream( + rows, pipeline_hash, inputs[0] + ) result = self.unary_static_process(stream) for tag, data in result.iter_data(): await output.send((tag, data)) @@ -290,7 +292,9 @@ async def async_execute( async for tag, data in inputs[0]: batch.append((tag, data)) if len(batch) >= self.batch_size: - stream = self._materialize_input_stream(batch, pipeline_hash) + stream = self._materialize_input_stream( + batch, pipeline_hash, inputs[0] + ) result = self.unary_static_process(stream) for out_tag, out_data in result.iter_data(): await output.send((out_tag, out_data)) @@ -298,7 +302,7 @@ async def async_execute( # Flush partial batch if batch and not self.drop_partial_batch: - stream = self._materialize_input_stream(batch, pipeline_hash) + stream = self._materialize_input_stream(batch, pipeline_hash, inputs[0]) result = self.unary_static_process(stream) for out_tag, out_data in result.iter_data(): await output.send((out_tag, out_data)) diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 0afec1e92..220e77ba0 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -986,7 +986,7 @@ def _as_upstream_stream( # otherwise it would fall back to a root's schema-only hash and an # operator would name its system tags after that. A source's pipeline # hash is that schema-only hash already. - stream: StreamProtocol = _RowsOfStream( + stream = _RowsOfStream( table, tag_columns=tag_keys, pipeline_hash=upstream.pipeline_hash(), @@ -1005,6 +1005,7 @@ def _as_upstream_stream( upstreams=upstream.upstreams, data_context=context, ) + stream._identity_origin = upstream # pyright: ignore[reportPrivateUsage] # This stream is a row representation. # Every complete node output in the row-built form ends here (the rows' # rebuild, F's output, a stored-table output) or, with no row, in # ``_materialize_upstream``'s zero-row input: the places that mark it @@ -1016,6 +1017,7 @@ def _as_upstream_stream( def _materialize_input_stream( rows: Sequence[tuple[TagProtocol, DataProtocol]], pipeline_hash: ContentHash, + reader: ReadableChannel[tuple[TagProtocol, DataProtocol]], ) -> StreamProtocol: """Rebuild an input stream from the rows a barrier ``async_execute`` collected. @@ -1030,6 +1032,7 @@ def _materialize_input_stream( Args: rows: Non-empty sequence of (Tag, Data) pairs. pipeline_hash: The pipeline hash of the stream the rows came from. + reader: The input channel, which carries the original stream in a job. Returns: A stream over the rows, in order. @@ -1037,6 +1040,7 @@ def _materialize_input_stream( Raises: ValueError: If ``rows`` is empty. """ + from orcapod.core.nodes.operator_node import job_input_stream from orcapod.system_constants import constants table, tag_keys, data_tags = StaticOutputOperatorPod._rows_to_table(rows) @@ -1044,13 +1048,15 @@ def _materialize_input_stream( pa.field(constants.CONTEXT_KEY, pa.large_string(), nullable=False), pa.array([data.data_context_key for _, data in rows], pa.large_string()), ) - return _RowsOfStream( + stream = _RowsOfStream( table, tag_columns=tag_keys, pipeline_hash=pipeline_hash, data_tags=data_tags, data_context=contexts.resolve_context(rows[0][1].data_context_key), ) + stream._identity_origin = job_input_stream(reader) # pyright: ignore[reportPrivateUsage] # This stream is a row representation. + return stream async def async_execute( self, @@ -1093,8 +1099,10 @@ async def async_execute( # the channels do not carry (ITL-858), so nothing is emitted (ITL-865). return streams = [ - self._materialize_input_stream(rows, pipeline_hash) - for rows, pipeline_hash in zip(all_rows, input_pipeline_hashes) + self._materialize_input_stream(rows, pipeline_hash, reader) + for rows, pipeline_hash, reader in zip( + all_rows, input_pipeline_hashes, inputs, strict=True + ) ] result = self.static_process(*streams) for tag, data in result.iter_data(): @@ -1942,16 +1950,16 @@ def _typed_zero_row_table(self) -> pa.Table | None: # not (a raw stream's meta columns enter its hash, and its zero-row # table has none): the system-tag names then follow the upstream's # hash, as on the sync path (``_as_upstream_stream``'s rule). - inputs.append( - _RowsOfStream( - table, - tag_columns=upstream.keys()[0], - pipeline_hash=upstream.pipeline_hash(), - data_tags=stream_data_tags(upstream), - upstreams=upstream.upstreams, - data_context=context, - ) + rows = _RowsOfStream( + table, + tag_columns=upstream.keys()[0], + pipeline_hash=upstream.pipeline_hash(), + data_tags=stream_data_tags(upstream), + upstreams=upstream.upstreams, + data_context=context, ) + rows._identity_origin = upstream # pyright: ignore[reportPrivateUsage] # This stream is a row representation. + inputs.append(rows) continue inputs.append( ArrowTableStream( diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 3b4f65398..7e32db092 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -45,7 +45,7 @@ SchemaInconsistencyError, ) from orcapod.system_constants import constants -from orcapod.types import ColumnConfig, Cursor, PollingConfig, Schema +from orcapod.types import ContentHash, ColumnConfig, Cursor, PollingConfig, Schema from orcapod.utils import arrow_utils from orcapod.utils.arrow_utils import system_tag_column_names from orcapod.utils.schema_utils import ( @@ -55,6 +55,7 @@ ) if TYPE_CHECKING: + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol from polars._typing import FrameInitTypes from orcapod.core.streams.arrow_table_stream import ArrowTableStream @@ -427,6 +428,12 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": # Identity # ------------------------------------------------------------------------- + def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: + """The combined hashes require a declared schema or a committed batch.""" + if self._declared_arrow is None and not self._batches: + raise ValueError("Polling source pipeline structure requires a schema.") + return super()._identity_pipeline_hash(hasher) + def identity_structure(self) -> Any: """Identity from the source id, the impl's own identity, tags and key columns. diff --git a/src/orcapod/core/streams/arrow_table_stream.py b/src/orcapod/core/streams/arrow_table_stream.py index 9486bddfd..59a7dd5cf 100644 --- a/src/orcapod/core/streams/arrow_table_stream.py +++ b/src/orcapod/core/streams/arrow_table_stream.py @@ -17,7 +17,11 @@ ) from orcapod.core.streams.view import StreamView from orcapod.protocols.core_protocols import PodProtocol, StreamProtocol, TagProtocol -from orcapod.protocols.hashing_protocols import PipelineElementProtocol +from orcapod.protocols.hashing_protocols import ( + IdentityChains, + IdentityWalkProtocol, + PipelineElementProtocol, +) from orcapod.system_constants import constants from orcapod.types import ColumnConfig, Schema, SourceInfoValue from orcapod.utils import arrow_utils, schema_utils @@ -273,6 +277,14 @@ def _identity_table(self) -> "pa.Table": table, self._tag_columns, self.data_context.arrow_hasher ) + _identity_origin: StreamProtocol | None = None + + def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: + """A row build represents the original stream for the new chains.""" + if self._identity_origin is not None: + return walk.visit(self._identity_origin) + return super()._identity_chains(walk) + def _identity_inputs(self) -> tuple[StreamProtocol, ...]: """A table without a producer hashes as a root.""" return self.upstreams if self.producer is not None else () diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 42593c634..72befb63f 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -47,7 +47,10 @@ from orcapod.utils import arrow_utils if TYPE_CHECKING: - from orcapod.protocols.hashing_protocols import SemanticHasherProtocol + from orcapod.protocols.hashing_protocols import ( + IdentityWalkProtocol, + SemanticHasherProtocol, + ) from orcapod.types.explanation import Explanation # TODO: consider using this instead of making copy of dicts @@ -768,14 +771,16 @@ def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGrou producer = self.producer return inputs if producer is None else producer.argument_symmetry(inputs) - def _identity_leaf(self) -> tuple[str, ContentHash] | None: - """Reuse the content hash and slot name of a root stream.""" + def _identity_leaf( + self, walk: IdentityWalkProtocol + ) -> tuple[str | None, ContentHash] | None: + """A named source stands for its slot; a raw input has no slot name.""" if self.producer is not None or self._identity_inputs(): return None - from orcapod.core.nodes.source_node import slot_name_for + from orcapod.core.sources.base import RootSource - content = self.content_hash() - return slot_name_for(self, content), content + name = self.source_name if isinstance(self, RootSource) else None + return name, self.content_hash() @property @abstractmethod diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index 0b58b8f37..d1dfb6024 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -137,6 +137,10 @@ def save(self, path: str | Path) -> None: serialize_arrow_schemas, serialize_output_schema, ) + from orcapod.core.identity_chains import ( + INPUT_SYMMETRY_KEY, + encode_input_symmetry, + ) from orcapod.core.nodes import OperatorNode, FunctionNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass from orcapod.core.streams.base import shared_zero_row_memo, typed_arrow_schemas @@ -288,6 +292,14 @@ def save(self, path: str | Path) -> None: descriptor["operator_config"] = copy.deepcopy( node._descriptor["operator_config"] ) + if node._operator is not None: + symmetry = encode_input_symmetry( + node.upstreams, node._operator.argument_symmetry + ) + else: + symmetry = node._descriptor.get(INPUT_SYMMETRY_KEY) + if symmetry is not None: + descriptor[INPUT_SYMMETRY_KEY] = symmetry descriptor["table_scope"] = node._table_scope nodes[content_hash_str] = descriptor diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index ef8617b7c..7b847f3c1 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -16,16 +16,16 @@ class IdentityChains: """The three chains of one element. An unbound slot leaves sources absent.""" - structure: ContentHash + pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] sources: ContentHash | None names: ContentHash + unbound_slots: frozenset[str] = frozenset() class IdentityWalkProtocol(Protocol): """One traversal with a common structural hasher and live slot bindings.""" hasher: SemanticHasherProtocol - unbound_slots: set[str] def visit(self, element: IdentityChainProtocol) -> IdentityChains: """Compute the element's chains or reuse them from this walk.""" diff --git a/tests/test_channels/test_polling_source.py b/tests/test_channels/test_polling_source.py index a3b3d2510..68189dff3 100644 --- a/tests/test_channels/test_polling_source.py +++ b/tests/test_channels/test_polling_source.py @@ -1821,3 +1821,41 @@ def test_key_column_order_counts(self): self._source(tags, ["a", "b", "c"]).content_hash() != self._source(tags, ["c", "b", "a"]).content_hash() ) + + +def test_polling_leaf_chains_are_available_before_schema( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Neither leaf chain needs a schema or a polling attempt.""" + source = PollingSource( + NoArgSource(), tag_columns=["id"], source_id="pending", record_id_columns=["id"] + ) + + def unexpected_poll() -> None: + pytest.fail("leaf identities must not poll for a schema") + + monkeypatch.setattr(source, "_sync_poll_and_commit", unexpected_poll) + assert source.source_chain() == source.content_hash() + name_chain = source.name_chain() + source.label = "new label" + assert source.name_chain() == name_chain + with pytest.raises(ValueError, match="requires a schema"): + source.node_hash() + with pytest.raises(ValueError, match="requires a schema"): + source._chain_content_hash() + + +def test_polling_leaf_chains_stay_stable_when_a_batch_supplies_schema() -> None: + """Learning the schema enables combined hashes without changing leaf chains.""" + source = PollingSource( + FakeDynamicSource(batches=[_batch(1, 10)]), + tag_columns="id", + record_id_columns="id", + ) + before = source.source_chain(), source.name_chain() + with pytest.raises(ValueError, match="requires a schema"): + source.node_hash() + assert list(source) + assert (source.source_chain(), source.name_chain()) == before + assert source.node_hash() + assert source._chain_content_hash() diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index 201feb6a8..c11a5258f 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -19,6 +19,7 @@ if TYPE_CHECKING: from pathlib import Path + from orcapod.protocols.core_protocols import StreamProtocol from orcapod.protocols.hashing_protocols import IdentityChainProtocol @@ -302,3 +303,182 @@ def test_equal_structure_join_pipeline_hash_depends_only_on_structure() -> None: 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() + + +@pytest.mark.parametrize("missing_builtin", [False, True]) +def test_loaded_commutative_stub_keeps_chains( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, missing_builtin: bool +) -> None: + """A missing producer must still pool its inputs in symmetric order.""" + from orcapod.pipeline.serialization import OPERATOR_REGISTRY + from orcapod.sources import CSVSource + + class UnregisteredJoin(Join): + """An operator whose config has no registered loader.""" + + inputs = [] + for name, value in (("a", "x"), ("b", "y")): + path = tmp_path / f"{name}.csv" + path.write_text(f"k,{value}\n1,3\n") + inputs.append(CSVSource(str(path), tag_columns=["k"], source_id=name)) + inputs.sort(key=lambda source: source.pipeline_hash().to_hex(), reverse=True) + assert inputs[0].pipeline_hash() != inputs[1].pipeline_hash() + job = PipelineJob(name="saved_symmetry", database=InMemoryArrowDatabase()) + with job: + (Join() if missing_builtin else UnregisteredJoin())(*inputs, label="joined") + job.run() + expected = _hashes(job.nodes["joined"]) + path = tmp_path / "job.json" + job.save(path) + if missing_builtin: + monkeypatch.delitem(OPERATOR_REGISTRY, "Join") + loaded = PipelineJob.load(path, database=job.database) + assert loaded.nodes["joined"].producer is None + assert _hashes(loaded.nodes["joined"]) == expected + loaded.save(path) + assert ( + _hashes(PipelineJob.load(path, database=job.database).nodes["joined"]) + == expected + ) + + +@pytest.mark.parametrize("downstream", [False, True]) +def test_raw_stream_label_never_enters_chains(downstream: bool) -> None: + """Raw inputs and their projections ignore labels.""" + import pyarrow as pa + + from orcapod.core.streams.arrow_table_stream import ArrowTableStream + + table = pa.table({"k": [1], "x": [3]}) + before = ArrowTableStream(table, tag_columns=["k"], label="before") + after = ArrowTableStream(table, tag_columns=["k"], label="after") + left = before.select_data_columns(["x"]) if downstream else before + right = after.select_data_columns(["x"]) if downstream else after + assert left.name_chain() == right.name_chain() + assert _hashes(left) == _hashes(right) + + +def test_chain_hashes_are_memoized_through_a_long_chain( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Reads reuse pooled hashes and rebind invalidates only source hashes.""" + from orcapod.core import identity_chains + + source = _source("reading", False) + job = PipelineJob(name="long_chain", database=InMemoryArrowDatabase()) + with job: + plain = source + for index in range(50): + plain = plain.select_data_columns(["x"], label=f"project_{index}") + result = job.nodes["project_49"] + hashes: list[str] = [] + visits: list[IdentityChainProtocol] = [] + original_hash = identity_chains._hash # pyright: ignore[reportPrivateUsage] # Count hash computations. + original_visit = identity_chains.IdentityWalk.visit + + def count_hash(label: str, preimage: tuple[object, ...]) -> ContentHash: + hashes.append(label) + return original_hash(label, preimage) + + def count_visit( + walk: identity_chains.IdentityWalk, element: IdentityChainProtocol + ) -> identity_chains.IdentityChains: + visits.append(element) + return original_visit(walk, element) + + monkeypatch.setattr(identity_chains, "_hash", count_hash) + monkeypatch.setattr(identity_chains.IdentityWalk, "visit", count_visit) + before = _hashes(result) + assert len({id(element) for element in visits}) == 51 + assert hashes + hashes.clear() + visits.clear() + assert _hashes(result) == before + assert hashes == [] + assert visits == [result, result] + visits.clear() + job.bind(sources={"reading": _source("rebound", False)}) + after = _hashes(result) + assert after[0] != before[0] + assert after[1] == before[1] + assert hashes == [identity_chains.CONTENT_HASH_LABEL] + assert len({id(element) for element in visits}) == 51 + hashes.clear() + assert _hashes(result) == after + assert hashes == [] + + +@pytest.mark.parametrize("inner_job", [False, True]) +def test_unbound_slot_binding_has_no_source_chain(inner_job: bool) -> None: + """A binding cannot turn an unbound slot into a concrete source identity.""" + source = _source("reading", False) + outer = PipelineJob(name="outer", database=InMemoryArrowDatabase()) + with outer: + add.pod(source, label="result") + inner = PipelineJob(name="inner", database=InMemoryArrowDatabase()) + if inner_job: + with inner: + add.pod(source, label="unused") + from orcapod.core.nodes.source_node import SourceJobNode + + slot = inner.nodes["reading"] + assert isinstance(slot, SourceJobNode) + slot.bound_source = None + else: + slot = SourceNode.from_stream(source, name="inner_slot") + outer.bind(sources={"reading": slot}) + result = outer.nodes["result"] + assert result.source_chain() is None + with pytest.raises(UnboundSourceError, match="unbound.*reading"): + result._chain_content_hash() + if inner_job: + inner.bind(sources={"reading": source}) + assert result.source_chain() == source.content_hash() + + +@pytest.mark.parametrize("has_rows", [False, True]) +def test_row_materialization_keeps_both_chains(has_rows: bool) -> None: + """Both empty and nonempty row builds represent the original source.""" + from orcapod.core.operators.static_output_pod import RowsOnRead + + source = _source("reading", False) + wrapped = RowsOnRead(list(source) if has_rows else [], source) + assert _hashes(wrapped.built()) == _hashes(wrapped) == _hashes(source) + wrapped.release_built() + assert _hashes(wrapped.built()) == _hashes(source) + + +def test_async_batch_input_keeps_both_chains() -> None: + """A barrier operator's row-built input reports the original job slot hashes.""" + from orcapod.operators import Batch + + seen: list[tuple[object, object]] = [] + + class InspectBatch(Batch): + """Read the rebuilt input identities when processing the rows.""" + + def unary_static_process(self, stream: StreamProtocol) -> StreamProtocol: + seen.append(_hashes(stream)) + return super().unary_static_process(stream) + + source = _source("reading", False) + job = PipelineJob(name="batch_input_identity", database=InMemoryArrowDatabase()) + with job: + InspectBatch(2)(source) + _run(job, run_async=True) + assert seen == [_hashes(job.nodes["reading"])] + + +def test_copying_a_slot_under_a_new_name_recomputes_the_name_chain() -> None: + """The renamed slot and its descendants use the new declaration's name.""" + from orcapod.core.nodes.source_node import SourceJobNode + + reading = SourceJobNode.from_stream(_source("reading", False)) + original = add.pod(reading) + before = _hashes(original) + renamed = SourceJobNode.from_stream(reading, name="renamed") + result = add.pod(renamed) + after = _hashes(result) + assert after[0] == before[0] + assert after[1] != before[1] + assert _hashes(original) == before From f3930775ab2c324dc9c581ed68baa4dd6a6f2a37 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 03:45:55 -0800 Subject: [PATCH 03/38] fix(identity): address three-chain review findings --- changelog.d/ITL-1559.md | 2 +- docs/dev/design_issues/ITL-1559-TC1.md | 4 + docs/reference/hashing.md | 10 +- src/orcapod/core/identity_chains.py | 211 +++++++++++--------- src/orcapod/core/nodes/operator_node.py | 14 +- src/orcapod/core/nodes/source_node.py | 11 +- src/orcapod/core/sources/polling_source.py | 11 +- src/orcapod/pipeline/graph.py | 12 +- src/orcapod/protocols/hashing_protocols.py | 1 + src/orcapod/protocols/node_protocols.py | 26 ++- tests/test_channels/test_polling_source.py | 17 +- tests/test_hashing/hash_site_trace.py | 5 +- tests/test_hashing/test_identity_chains.py | 157 ++++++++++++++- tests/test_pipeline/test_node_protocols.py | 19 +- tests/test_protocols/test_node_protocols.py | 41 ++++ 15 files changed, 398 insertions(+), 143 deletions(-) diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index b3d205419..99ebf5103 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -1,5 +1,5 @@ ### Added -- Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. Existing pipeline and content hashes keep their values. +- Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. A polling source can report its node hash before its first batch supplies the schema. Existing pipeline and content hashes keep their values. - Saved operator descriptors can retain input symmetry so a job loaded without its operator implementation reports the same chain-based hashes as the live job. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index fd35cac39..de656ea41 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -13,3 +13,7 @@ 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. + +The step 1 follow-up serializes binding and chain reads, and derives optional saved +symmetry from real operator inputs. Schema-less polling sources report a node hash +before their first batch. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 6c00e6ff0..863179a46 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -318,9 +318,11 @@ An operator descriptor records nondefault input grouping in its optional be restored. Older descriptors without this field use their saved argument order when the pod is unavailable. -A polling source can report its source and name chains before it knows its schema. -Its combined hashes require the pipeline hash, so they raise `ValueError` until -the source declares a schema or commits its first batch. +A polling source can report its source chain, name chain, and node hash before it +knows its schema. In this state the node hash combines a pending polling-source +structure term with the name chain, without initiating a poll. Once a batch +supplies the schema, the node hash combines the pipeline hash with the same name +chain. The chain-based content hash requires the schema. ## Hash site inventory @@ -347,7 +349,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | What is hashed | Algorithm / label | Used as | Call sites | |---|---|---|---|---| | structure hasher | a Python value as a tagged JSON tree | SHA-256 of canonical JSON, `semantic_v1` | every `content_hash()` / `pipeline_hash()`, type and function hash; the names built on schema hashes | `hashing/semantic_hashing/semantic_hasher.py:SemanticAwarePythonHasher._hash_to_content_hash` | -| three-chain hashes | a slot name, a pool of upstream chains, or the pipeline hash paired with one chain | SHA-256 of canonical JSON, with the corresponding chain or combined-hash label | into a hash for chain pooling and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool`, `core/identity_chains.py:IdentityChainsMixin._identity_hash`, `core/identity_chains.py:IdentityChainsMixin._compute_identity_chains..`, `core/identity_chains.py:IdentityChainsMixin._chain_content_hash`, `core/identity_chains.py:IdentityChainsMixin.node_hash` | +| three-chain hashes | a slot name, a pool of upstream chains, or the pipeline hash paired with one chain | SHA-256 of canonical JSON, with the corresponding chain or combined-hash label | into a hash for chain pooling and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool`, `core/identity_chains.py:IdentityChainsMixin._identity_hash`, `core/identity_chains.py:IdentityChainsMixin._compute_identity_chains..`, `core/identity_chains.py:IdentityChainsMixin._chain_content_hash`, `core/identity_chains.py:IdentityChainsMixin.node_hash`, `core/sources/polling_source.py:PollingSource._identity_node_pipeline_hash` | | Arrow hasher | a table after the semantic visitor | starfix, `arrow_v1` (a table Orcapod built: float rule on); `hash_table_strict`: `arrow_strict_v1` (a pyarrow table given as a value: every bit counts); `hash_table_ordered`: `arrow_ordered_v1` (a library value's digest: every bit counts); `hash_schema`: `arrow_schema_v1` | row data hashes, entry ids, row keys, default source ids, table values; every schema in an identity | `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_strict`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_table_ordered`, `hashing/arrow_hashers.py:StarfixArrowHasher.hash_schema`, `hashing/arrow_hashers.py:StarfixArrowHasher._digest`, `hashing/starfix_digest.py:_digest_table`, `hashing/starfix_digest.py:digest_schema` | | file hasher | a file's bytes | the configured digest function, label = its name (`sha256` in the data context; others: ITL-1155) | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir` | diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 383dd8534..69b96b1e3 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -4,10 +4,12 @@ from abc import ABC, abstractmethod from collections.abc import Callable +from contextlib import AbstractContextManager from dataclasses import dataclass from functools import cached_property from itertools import groupby -from typing import TYPE_CHECKING, cast, final +from threading import RLock +from typing import TYPE_CHECKING, ClassVar, final from weakref import WeakValueDictionary from orcapod.errors import UnboundSourceError @@ -62,21 +64,6 @@ def visit(self, element: IdentityChainProtocol) -> IdentityChains: self._consumer = consumer -@final -class _InputOccurrence: - """One position in a pod's input list, with access to the original stream. - - Identity-based equality keeps repetitions even inside a frozenset. - """ - - def __init__(self, stream: StreamProtocol, index: int) -> None: - self._stream = stream - self.index = index - - def __getattr__(self, name: str) -> object: - return getattr(self._stream, name) - - # JSON needs one explicit marker to distinguish symmetric groups from lists. INPUT_SYMMETRY_KEY = "input_symmetry" InputSymmetry = int | list["InputSymmetry"] | dict[str, list["InputSymmetry"]] @@ -86,44 +73,56 @@ def encode_input_symmetry( inputs: tuple[StreamProtocol, ...], symmetry: Callable[[tuple[StreamProtocol, ...]], ArgumentGroup], ) -> InputSymmetry | None: - """Encode a nondefault grouping by argument position, preserving repetitions.""" + """Translate a pod's grouping of real streams into argument positions.""" + if len(inputs) < 2: + return None - def encode(group: object) -> InputSymmetry: - if isinstance(group, _InputOccurrence): - return group.index + remaining = dict(enumerate(inputs)) + symmetric: list[tuple[frozenset[ArgumentGroup], list[InputSymmetry]]] = [] + + def encode(group: ArgumentGroup) -> InputSymmetry: if isinstance(group, tuple): - return [encode(child) for child in cast("tuple[object, ...]", group)] + return [encode(child) for child in group] if isinstance(group, frozenset): - children = [encode(child) for child in cast("frozenset[object]", group)] - return {"symmetric": sorted(children, key=repr)} - raise TypeError( - "argument_symmetry must group the input occurrences it receives" - ) - - if len(inputs) < 2: + children = [encode(child) for child in group] + symmetric.append((group, children)) + return {"symmetric": children} + for index, stream in remaining.items(): + if stream is group: + del remaining[index] + return index + raise ValueError("argument_symmetry did not group arguments by occurrence") + + group = symmetry(inputs) + try: + grouped = encode(group) + except ValueError: + # Positions are optional metadata. A legacy descriptor can use input order + # when a custom grouping cannot be expressed with argument positions. return None - grouped = encode(symmetry(_occurrences(inputs))) - return None if grouped == list(range(len(inputs))) else grouped - -def decode_input_symmetry( - group: InputSymmetry, inputs: tuple[StreamProtocol, ...] -) -> ArgumentGroup: - """Apply the saved grouping to the current input occurrences.""" - if isinstance(group, int): - return inputs[group] - if isinstance(group, list): - return tuple(decode_input_symmetry(child, inputs) for child in group) - return frozenset( - decode_input_symmetry(child, inputs) for child in group["symmetric"] + # A frozenset can collapse repeated or content-equal streams. Restore their + # positions after claiming the explicit leaves, including leaves of ordered groups. + symmetric.sort( + key=lambda entry: min(_input_positions(entry[1]), default=len(inputs)) ) + for index, stream in remaining.items(): + for members, children in symmetric: + if stream in members: + children.append(index) + break + + for _, children in symmetric: + children.sort(key=repr) + return None if grouped == list(range(len(inputs))) else grouped -def _occurrences(inputs: tuple[StreamProtocol, ...]) -> tuple[StreamProtocol, ...]: - return tuple( - cast("StreamProtocol", cast(object, _InputOccurrence(stream, index))) - for index, stream in enumerate(inputs) - ) +def _input_positions(group: InputSymmetry) -> tuple[int, ...]: + """Return every explicit position in a grouping.""" + if isinstance(group, int): + return (group,) + children = group if isinstance(group, list) else group["symmetric"] + return tuple(index for child in children for index in _input_positions(child)) @dataclass(frozen=True, slots=True) @@ -149,25 +148,19 @@ def _pool( def _pool_group( - group: object, + group: InputSymmetry, inputs: tuple[_GroupChains, ...], hash_term: Callable[[str, tuple[object, ...]], ContentHash], source_term: object | None = None, name_term: object | None = None, ) -> _GroupChains: """Pool in structural order, breaking structural ties separately per chain.""" - if isinstance(group, _InputOccurrence): - return inputs[group.index] - if not isinstance(group, (tuple, frozenset)): - raise TypeError( - "argument_symmetry must group the input occurrences it receives" - ) + if isinstance(group, int): + return inputs[group] - children = [ - _pool_group(child, inputs, hash_term) - for child in cast("tuple[object, ...] | frozenset[object]", group) - ] - symmetric = isinstance(group, frozenset) + symmetric = isinstance(group, dict) + group_children = group["symmetric"] if isinstance(group, dict) else group + children = [_pool_group(child, inputs, hash_term) for child in group_children] if symmetric: children.sort(key=lambda child: child.structure_key) structure_key = ( @@ -201,6 +194,10 @@ def _pool_group( class IdentityChainsMixin(ABC): """Memoize chains per node and invalidate descendants of a changed slot.""" + # A walk spans arbitrary slots and wrappers, including bindings between jobs. + # Guard its reverse edges and memo publication with the same lock as binding. + _identity_lock: ClassVar[AbstractContextManager[object]] = RLock() + # Defaults cover loaded stubs constructed without __init__. _identity_cache: dict[str, IdentityChains] | None = None _identity_name_hashes: dict[tuple[str, tuple[object, ...]], ContentHash] | None = ( @@ -222,22 +219,23 @@ def _identity_dependencies(self) -> WeakValueDictionary[int, IdentityChainsMixin def _invalidate_identity_chains(self, *, names: bool = False) -> None: """Invalidate cached chains below this node, keeping name hashes on bind.""" - pending: list[IdentityChainsMixin] = [self] - seen: set[int] = set() - while pending: - node = pending.pop() - key = id(node) - if key in seen: - continue - seen.add(key) - node._identity_cache = None - node._identity_source_hashes = None - if names: - node._identity_name_hashes = None - pending.extend(node._identity_dependents.values()) - for dependency in list(node._identity_dependencies.values()): - dependency._identity_dependents.pop(key, None) - node._identity_dependencies.clear() + with self._identity_lock: + pending: list[IdentityChainsMixin] = [self] + seen: set[int] = set() + while pending: + node = pending.pop() + key = id(node) + if key in seen: + continue + seen.add(key) + node._identity_cache = None + node._identity_source_hashes = None + if names: + node._identity_name_hashes = None + pending.extend(node._identity_dependents.values()) + for dependency in list(node._identity_dependencies.values()): + _ = dependency._identity_dependents.pop(key, None) + node._identity_dependencies.clear() def _identity_hash(self, label: str, preimage: tuple[object, ...]) -> ContentHash: """Reuse canonical hash terms across chain reads and unchanged name inputs.""" @@ -250,9 +248,14 @@ def _identity_hash(self, label: str, preimage: tuple[object, ...]) -> ContentHas self._identity_name_hashes = {} hashes = self._identity_name_hashes key = (label, preimage) - if key not in hashes: - hashes[key] = _hash(label, preimage) - return hashes[key] + try: + cached = hashes.get(key) + except TypeError: + # Semantic terms can contain values that Python cannot use as dict keys. + return _hash(label, preimage) + if cached is None: + cached = hashes[key] = _hash(label, preimage) + return cached def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: """Use the legacy structure, evaluated only when a consumer needs it.""" @@ -277,6 +280,18 @@ def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGrou """Group inputs according to the producer's argument symmetry.""" return inputs + def _identity_input_symmetry( + self, inputs: tuple[StreamProtocol, ...] + ) -> InputSymmetry | None: + """Return positional grouping when it differs from argument order.""" + return encode_input_symmetry(inputs, self._identity_symmetry) + + def _identity_node_pipeline_hash( + self, hasher: SemanticHasherProtocol + ) -> ContentHash: + """Return the structure term for a leaf's public node hash.""" + return self._identity_pipeline_hash(hasher) + def _identity_leaf( self, walk: IdentityWalkProtocol ) -> tuple[str | None, ContentHash | None] | None: @@ -306,6 +321,7 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains frozenset((name,)) if name is not None and source is None else frozenset(), + self._identity_node_pipeline_hash, ) inputs = self._identity_inputs() @@ -333,7 +349,9 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains ) # Symmetric groups use structural ordering. Occurrences keep repeats. - group = self._identity_symmetry(_occurrences(inputs)) if inputs else () + group = self._identity_input_symmetry(inputs) if inputs else None + if group is None: + group = list[InputSymmetry](range(len(inputs))) children = tuple( _GroupChains( (upstream.pipeline_hash(walk.hasher).to_hex(),), @@ -356,11 +374,13 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains def source_chain(self) -> ContentHash | None: """Return the source chain, absent if any contributing slot is unbound.""" - return IdentityWalk(self._identity_hasher).visit(self).sources + with self._identity_lock: + return IdentityWalk(self._identity_hasher).visit(self).sources def name_chain(self) -> ContentHash: """Return the chain of source-slot names.""" - return IdentityWalk(self._identity_hasher).visit(self).names + with self._identity_lock: + return IdentityWalk(self._identity_hasher).visit(self).names def _chain_content_hash(self) -> ContentHash: """Combine structure and sources. This becomes ``content_hash()`` at the switch. @@ -368,21 +388,24 @@ def _chain_content_hash(self) -> ContentHash: Raises: UnboundSourceError: If any contributing source slot is unbound. """ - walk = IdentityWalk(self._identity_hasher) - chains = walk.visit(self) - if chains.sources is None: - names = ", ".join(repr(name) for name in sorted(chains.unbound_slots)) - raise UnboundSourceError( - f"Content identity is undefined for unbound source slots {names}." + with self._identity_lock: + walk = IdentityWalk(self._identity_hasher) + chains = walk.visit(self) + if chains.sources is None: + names = ", ".join(repr(name) for name in sorted(chains.unbound_slots)) + raise UnboundSourceError( + f"Content identity is undefined for unbound source slots {names}." + ) + return self._identity_hash( + CONTENT_HASH_LABEL, (chains.pipeline_hash(walk.hasher), chains.sources) ) - return self._identity_hash( - CONTENT_HASH_LABEL, (chains.pipeline_hash(walk.hasher), chains.sources) - ) def node_hash(self) -> ContentHash: """Combine structure and slot names, independently of binding.""" - walk = IdentityWalk(self._identity_hasher) - chains = walk.visit(self) - return self._identity_hash( - NODE_HASH_LABEL, (chains.pipeline_hash(walk.hasher), chains.names) - ) + with self._identity_lock: + walk = IdentityWalk(self._identity_hasher) + chains = walk.visit(self) + 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/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 55b469c4b..74f5ab0be 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -29,7 +29,7 @@ import pyarrow.compute as pc from orcapod import contexts -from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY, decode_input_symmetry +from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY, InputSymmetry from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -85,7 +85,6 @@ with_data_context, ) from orcapod.protocols.core_protocols import ( - ArgumentGroup, DataProtocol, StreamProtocol, TagProtocol, @@ -339,12 +338,13 @@ def pipeline_hash(self, hasher=None) -> ContentHash: # Stream interface # ------------------------------------------------------------------ - def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: + def _identity_input_symmetry( + self, inputs: tuple[StreamProtocol, ...] + ) -> InputSymmetry | None: """Recover the grouping of a saved operator when its producer is missing.""" - saved = self._descriptor.get(INPUT_SYMMETRY_KEY) - if self._operator is None and saved is not None: - return decode_input_symmetry(saved, inputs) - return super()._identity_symmetry(inputs) + if self._operator is None: + return self._descriptor.get(INPUT_SYMMETRY_KEY) + return super()._identity_input_symmetry(inputs) @property def producer(self) -> OperatorPodProtocol: diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 20bfa854a..2d78c9153 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -1761,11 +1761,12 @@ def _bind(self, value: StreamProtocol | None) -> None: SourceSpecMismatchError: If *value* does not fit the declared schema. """ form = None if value is None else self._declared_form_for(value) - self._bound_source = value - self._declared_form = form - self._invalidate_content_hash_cache() - self._invalidate_pipeline_hash_cache() - self._invalidate_identity_chains() + with self._identity_lock: + self._invalidate_identity_chains() + self._bound_source = value + self._declared_form = form + self._invalidate_content_hash_cache() + self._invalidate_pipeline_hash_cache() @property def last_modified(self) -> datetime | None: diff --git a/src/orcapod/core/sources/polling_source.py b/src/orcapod/core/sources/polling_source.py index 7e32db092..ef7aa3f92 100644 --- a/src/orcapod/core/sources/polling_source.py +++ b/src/orcapod/core/sources/polling_source.py @@ -429,11 +429,20 @@ def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": # ------------------------------------------------------------------------- def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: - """The combined hashes require a declared schema or a committed batch.""" + """The source combination requires a declared schema or a committed batch.""" if self._declared_arrow is None and not self._batches: raise ValueError("Polling source pipeline structure requires a schema.") return super()._identity_pipeline_hash(hasher) + def _identity_node_pipeline_hash( + self, hasher: SemanticHasherProtocol + ) -> ContentHash: + """Use a pending-schema structure term until the first batch commits.""" + if self._declared_arrow is None and not self._batches: + self._note_provisional_identity_use() + return hasher.hash_object(("polling_source", None)) + return super()._identity_node_pipeline_hash(hasher) + def identity_structure(self) -> Any: """Identity from the source id, the impl's own identity, tags and key columns. diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index d1dfb6024..db33da27a 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -137,10 +137,7 @@ def save(self, path: str | Path) -> None: serialize_arrow_schemas, serialize_output_schema, ) - from orcapod.core.identity_chains import ( - INPUT_SYMMETRY_KEY, - encode_input_symmetry, - ) + from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY from orcapod.core.nodes import OperatorNode, FunctionNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass from orcapod.core.streams.base import shared_zero_row_memo, typed_arrow_schemas @@ -292,12 +289,7 @@ def save(self, path: str | Path) -> None: descriptor["operator_config"] = copy.deepcopy( node._descriptor["operator_config"] ) - if node._operator is not None: - symmetry = encode_input_symmetry( - node.upstreams, node._operator.argument_symmetry - ) - else: - symmetry = node._descriptor.get(INPUT_SYMMETRY_KEY) + symmetry = node._identity_input_symmetry(node.upstreams) # pyright: ignore[reportPrivateUsage] # Persist the same grouping used by the node's identity chains. if symmetry is not None: descriptor[INPUT_SYMMETRY_KEY] = symmetry descriptor["table_scope"] = node._table_scope diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 7b847f3c1..76e42f59e 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -20,6 +20,7 @@ class IdentityChains: sources: ContentHash | None names: ContentHash unbound_slots: frozenset[str] = frozenset() + node_pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] | None = None class IdentityWalkProtocol(Protocol): diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index cf1080c53..78b96b54f 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -24,11 +24,27 @@ StreamProtocol, TagProtocol, ) - from orcapod.types import NodeConfig + from orcapod.types import ContentHash, NodeConfig + + +class _NodeIdentityProtocol(Protocol): + """Public identities available on every orchestrated node.""" + + def node_hash(self) -> ContentHash: + """Combine structure and slot names.""" + ... + + def source_chain(self) -> ContentHash | None: + """Return the source chain, absent while a contributing slot is unbound.""" + ... + + def name_chain(self) -> ContentHash: + """Return the chain of source-slot names.""" + ... @runtime_checkable -class SourceNodeProtocol(Protocol): +class SourceNodeProtocol(_NodeIdentityProtocol, Protocol): """Protocol for source nodes in orchestrated execution.""" node_type: str @@ -57,7 +73,7 @@ async def async_execute( @runtime_checkable -class FunctionNodeProtocol(Protocol): +class FunctionNodeProtocol(_NodeIdentityProtocol, Protocol): """Protocol for function nodes in orchestrated execution.""" node_type: str @@ -114,7 +130,7 @@ def set_ephemeral_database(self, database: "ArrowDatabaseProtocol | None") -> No @runtime_checkable -class OperatorNodeProtocol(Protocol): +class OperatorNodeProtocol(_NodeIdentityProtocol, Protocol): """Protocol for operator nodes in orchestrated execution.""" node_type: str @@ -150,7 +166,7 @@ def set_ephemeral_database(self, database: "ArrowDatabaseProtocol | None") -> No @runtime_checkable -class SideEffectNodeProtocol(Protocol): +class SideEffectNodeProtocol(_NodeIdentityProtocol, Protocol): """Protocol for side-effect nodes in orchestrated execution.""" node_type: str diff --git a/tests/test_channels/test_polling_source.py b/tests/test_channels/test_polling_source.py index 68189dff3..b43da5775 100644 --- a/tests/test_channels/test_polling_source.py +++ b/tests/test_channels/test_polling_source.py @@ -17,7 +17,7 @@ from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import CursorInvalidatedError from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol -from orcapod.types import Cursor, PollingConfig, Schema +from orcapod.types import ContentHash, Cursor, PollingConfig, Schema # =========================================================================== @@ -1832,30 +1832,31 @@ def test_polling_leaf_chains_are_available_before_schema( ) def unexpected_poll() -> None: - pytest.fail("leaf identities must not poll for a schema") + pytest.fail("pending identities must not poll for a schema") monkeypatch.setattr(source, "_sync_poll_and_commit", unexpected_poll) assert source.source_chain() == source.content_hash() name_chain = source.name_chain() + node_hash = source.node_hash() + assert isinstance(node_hash, ContentHash) source.label = "new label" assert source.name_chain() == name_chain - with pytest.raises(ValueError, match="requires a schema"): - source.node_hash() + assert source.node_hash() == node_hash with pytest.raises(ValueError, match="requires a schema"): source._chain_content_hash() def test_polling_leaf_chains_stay_stable_when_a_batch_supplies_schema() -> None: - """Learning the schema enables combined hashes without changing leaf chains.""" + """Learning the schema enables content identity while leaf chains stay stable.""" source = PollingSource( FakeDynamicSource(batches=[_batch(1, 10)]), tag_columns="id", record_id_columns="id", ) before = source.source_chain(), source.name_chain() - with pytest.raises(ValueError, match="requires a schema"): - source.node_hash() + pending_hash = source.node_hash() + assert isinstance(pending_hash, ContentHash) assert list(source) assert (source.source_chain(), source.name_chain()) == before - assert source.node_hash() + assert source.node_hash() != pending_hash assert source._chain_content_hash() diff --git a/tests/test_hashing/hash_site_trace.py b/tests/test_hashing/hash_site_trace.py index 624a3048f..afba30258 100644 --- a/tests/test_hashing/hash_site_trace.py +++ b/tests/test_hashing/hash_site_trace.py @@ -263,7 +263,8 @@ def run_scenario() -> None: _ = cases.compute_all() from orcapod.operators import Join - from orcapod.sources import DictSource + from orcapod.sources import DictSource, PollingSource + from tests.test_channels.test_polling_source import NoArgSource left, right = ( DictSource( @@ -277,6 +278,8 @@ def run_scenario() -> None: joined = Join()(left, right) _ = joined._chain_content_hash() _ = joined.node_hash() + pending = PollingSource(NoArgSource(), tag_columns=["id"], record_id_columns=["id"]) + _ = pending.node_hash() hasher = get_default_context().semantic_hasher with tempfile.TemporaryDirectory() as tmp: root = _Path(tmp) diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index c11a5258f..c56181187 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -19,8 +19,14 @@ if TYPE_CHECKING: from pathlib import Path - from orcapod.protocols.core_protocols import StreamProtocol - from orcapod.protocols.hashing_protocols import IdentityChainProtocol + from collections.abc import Collection + + from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol + from orcapod.protocols.hashing_protocols import ( + IdentityChainProtocol, + IdentityChains, + IdentityWalkProtocol, + ) @function_pod(output_keys="total") @@ -288,8 +294,14 @@ def test_commutative_equal_structure_sorts_the_chains_independently( ) assert _hashes(result) == _hashes(swapped) repeat = Join()(left, left) - assert repeat.source_chain() != left.source_chain() - assert repeat.name_chain() != left.name_chain() + expected_sources = SemanticAwarePythonHasher( + hasher_id=SOURCE_CHAIN_HASH_LABEL + ).hash_object((left.source_chain(), left.source_chain())) + expected_names = SemanticAwarePythonHasher( + hasher_id=NAME_CHAIN_HASH_LABEL + ).hash_object((left.name_chain(), left.name_chain())) + assert repeat.source_chain() == expected_sources + assert repeat.name_chain() == expected_names job = PipelineJob(name="tie", database=InMemoryArrowDatabase()) with job: @@ -482,3 +494,140 @@ def test_copying_a_slot_under_a_new_name_recomputes_the_name_chain() -> None: assert after[0] == before[0] assert after[1] != before[1] assert _hashes(original) == before + + +def test_custom_operator_symmetry_receives_streams_on_save(tmp_path: Path) -> None: + """A custom operator can require concrete stream objects in its callback.""" + from orcapod.core.nodes.source_node import SourceNodeBase + + class StreamCheckingJoin(Join): + def argument_symmetry( + self, streams: Collection[StreamProtocol] + ) -> ArgumentGroup: + assert all( + isinstance(stream, (DictSource, SourceNodeBase)) for stream in streams + ) + return super().argument_symmetry(streams) + + left = _source("left", False) + right = _source("right", False, right=True) + job = PipelineJob(name="custom_symmetry", database=InMemoryArrowDatabase()) + with job: + StreamCheckingJoin()(left, right, label="joined") + job.run() + path = tmp_path / "job.json" + job.save(path) + assert path.is_file() + assert job.nodes["joined"].node_hash() + + +def test_overlapping_identity_read_cannot_publish_stale_chain( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A cold reader cannot repopulate its memo with the old binding.""" + from concurrent.futures import ThreadPoolExecutor + from threading import Event, get_ident + + source = _source("reading", False) + rebound = _source("rebound", False) + job = PipelineJob(name="overlapping_read", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="projection") + result = job.nodes["projection"] + computed, resume, binding = Event(), Event(), Event() + main_thread = get_ident() + original = result._compute_identity_chains # pyright: ignore[reportPrivateUsage] # Pause immediately before memo publication. + + def pause(walk: IdentityWalkProtocol) -> IdentityChains: + chains = original(walk) + if get_ident() != main_thread: + computed.set() + assert resume.wait(10) + return chains + + def bind() -> None: + binding.set() + job.bind(sources={"reading": rebound}) + + monkeypatch.setattr(result, "_compute_identity_chains", pause) + with ThreadPoolExecutor(2) as executor: + first = executor.submit(result.source_chain) + try: + assert computed.wait(5) + rebinding = executor.submit(bind) + assert binding.wait(5) + # A synchronized bind is allowed to wait for the in-flight reader. + try: + rebinding.result(timeout=1) + except TimeoutError: + pass + else: + assert result.source_chain() == rebound.content_hash() + finally: + resume.set() + first.result(timeout=5) + rebinding.result(timeout=5) + assert result.source_chain() == rebound.content_hash() + + +def test_identity_memo_is_invalidated_before_binding_is_visible( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """The new binding becomes visible after invalidation of dependent chains.""" + from concurrent.futures import ThreadPoolExecutor + from threading import Event + + from orcapod.core.nodes.source_node import SourceJobNode + + source = _source("reading", False) + rebound = _source("rebound", False) + job = PipelineJob(name="binding_visibility", database=InMemoryArrowDatabase()) + with job: + source.select_data_columns(["x"], label="projection") + result = job.nodes["projection"] + slot = job.nodes["reading"] + assert isinstance(slot, SourceJobNode) + assert result.source_chain() == source.content_hash() + original = slot._invalidate_identity_chains # pyright: ignore[reportPrivateUsage] # Inspect the binding at the invalidation boundary. + invalidating, resume = Event(), Event() + + def pause() -> None: + invalidating.set() + assert resume.wait(5) + original() + + monkeypatch.setattr(slot, "_invalidate_identity_chains", pause) + with ThreadPoolExecutor(1) as executor: + bind = executor.submit(job.bind, sources={"reading": rebound}) + try: + assert invalidating.wait(5) + assert slot.bound_source is source + finally: + resume.set() + bind.result(timeout=5) + assert slot.bound_source is rebound + assert result.source_chain() == rebound.content_hash() + + +def test_identity_terms_accept_canonical_semantic_values( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Terms accepted by semantic hashing can include dictionaries and lists.""" + source = _source("reading", False) + result = source.select_data_columns(["x"]) + source_term, name_term = {"mode": "x"}, ["variant"] + monkeypatch.setattr(result, "_identity_terms", lambda: (source_term, name_term)) + for label, upstream, term, chain in ( + ( + SOURCE_CHAIN_HASH_LABEL, + source.source_chain(), + source_term, + result.source_chain, + ), + (NAME_CHAIN_HASH_LABEL, source.name_chain(), name_term, result.name_chain), + ): + expected = SemanticAwarePythonHasher(hasher_id=label).hash_object( + ("term", upstream, term) + ) + assert chain() == expected + assert chain() == expected diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index 23482ce18..b670c5151 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -29,11 +29,24 @@ from orcapod.core.operators import SelectDataColumns +class _NodeIdentities: + """Identity accessors shared by the structural protocol fixtures.""" + + def node_hash(self): + return None + + def source_chain(self): + return None + + def name_chain(self): + return None + + class TestSourceNodeProtocol: def test_requires_execute(self): """SourceNodeProtocol requires execute method.""" - class GoodSource: + class GoodSource(_NodeIdentities): node_type = "source" @property @@ -64,7 +77,7 @@ class TestFunctionNodeProtocol: def test_requires_execute_and_async_execute(self): from orcapod.types import NodeConfig - class GoodFunction: + class GoodFunction(_NodeIdentities): node_type = "function" @property @@ -118,7 +131,7 @@ def execute(self, input_stream): class TestOperatorNodeProtocol: def test_requires_execute_and_async_execute(self): - class GoodOperator: + class GoodOperator(_NodeIdentities): node_type = "operator" @property diff --git a/tests/test_protocols/test_node_protocols.py b/tests/test_protocols/test_node_protocols.py index f3089fe28..8565157e6 100644 --- a/tests/test_protocols/test_node_protocols.py +++ b/tests/test_protocols/test_node_protocols.py @@ -81,3 +81,44 @@ def test_is_operator_node_true(self, operator_node): def test_is_operator_node_false_for_source(self, source_node): assert is_operator_node(source_node) is False + + +@pytest.mark.parametrize("missing", ["node_hash", "source_chain", "name_chain"]) +def test_execution_node_protocols_require_identity_accessors(missing): + """An execution-shaped object must expose all three public identities.""" + from types import SimpleNamespace + + from orcapod.protocols.node_protocols import ( + FunctionNodeProtocol, + OperatorNodeProtocol, + SideEffectNodeProtocol, + SourceNodeProtocol, + ) + + def operation(*args, **kwargs): + pass + + methods = dict( + node_type="source", + node_uri=(), + pipeline_path=(), + node_config=None, + execute=operation, + async_execute=operation, + attach_databases=operation, + set_ephemeral_database=operation, + node_hash=operation, + source_chain=operation, + name_chain=operation, + ) + complete = SimpleNamespace(**methods) + del methods[missing] + incomplete = SimpleNamespace(**methods) + for protocol in ( + SourceNodeProtocol, + FunctionNodeProtocol, + OperatorNodeProtocol, + SideEffectNodeProtocol, + ): + assert isinstance(complete, protocol) + assert not isinstance(incomplete, protocol) From 12c6d38c94c2621b01ed739bb95b03e3fa5490ae Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:18:34 -0800 Subject: [PATCH 04/38] fix(identity): preserve saved job bytes and chain inputs --- changelog.d/ITL-1559.md | 2 +- docs/dev/design_issues/ITL-1559-TC1.md | 7 +- docs/reference/hashing.md | 15 +- src/orcapod/core/identity_chains.py | 106 +++-- src/orcapod/core/nodes/operator_node.py | 16 +- src/orcapod/core/sources/cached_source.py | 22 + src/orcapod/core/streams/base.py | 12 +- src/orcapod/pipeline/graph.py | 4 - tests/test_channels/test_polling_source.py | 31 ++ .../data/three_chain_step_1_saved_job.json | 406 ++++++++++++++++++ tests/test_hashing/test_identity_chains.py | 150 ++++++- 11 files changed, 675 insertions(+), 96 deletions(-) create mode 100644 tests/test_hashing/data/three_chain_step_1_saved_job.json diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 99ebf5103..f26bdd8f2 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -2,4 +2,4 @@ - Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. A polling source can report its node hash before its first batch supplies the schema. Existing pipeline and content hashes keep their values. -- Saved operator descriptors can retain input symmetry so a job loaded without its operator implementation reports the same chain-based hashes as the live job. +- A job loaded without an operator implementation still exposes its saved hashes. Accessing the new chains for that operator raises an error until the saved format carries input symmetry. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index de656ea41..159183c68 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -14,6 +14,7 @@ available even when no source is bound. The graph and persistence still use thei existing hashes. ITL-1590 tracks the remaining structural dependency on source equality when a commutative operator receives equal-structure inputs. -The step 1 follow-up serializes binding and chain reads, and derives optional saved -symmetry from real operator inputs. Schema-less polling sources report a node hash -before their first batch. +The step 1 follow-up serializes binding and chain reads. Saved jobs retain the +existing file format. An operator loaded without its implementation cannot report +the new chains until a later step records input symmetry. Schema-less polling sources +report a node hash before their first batch, including when wrapped in a cache. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 7615a7f76..839cea7cb 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -313,14 +313,13 @@ contributing slot is unbound. The chain-based content hash is available internal `_chain_content_hash()` until the switch to `content_hash()`. Orcapod continues to use the existing hashes for graph keys and persistence. ITL-1590 tracks cases where the existing pipeline hash depends on source equality within a commutative input tie. -An operator descriptor records nondefault input grouping in its optional -`input_symmetry` field. A read-only operator uses that grouping when its pod cannot -be restored. Older descriptors without this field use their saved argument order -when the pod is unavailable. - -A polling source can report its source chain, name chain, and node hash before it -knows its schema. In this state the node hash combines a pending polling-source -structure term with the name chain, without initiating a poll. Once a batch +The saved job format does not carry input symmetry yet. When an operator is +unavailable on load, accessing either chain or combined hash raises an error. +The legacy pipeline and content hashes remain available from the descriptor. + +A polling source, including one wrapped in a cache, can report its source chain, +name chain, and node hash before it knows its schema. The node hash combines a +pending polling-source structure term with the name chain without polling. Once a batch supplies the schema, the node hash combines the pipeline hash with the same name chain. The chain-based content hash requires the schema. diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 69b96b1e3..ee1177819 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -64,9 +64,14 @@ def visit(self, element: IdentityChainProtocol) -> IdentityChains: self._consumer = consumer -# JSON needs one explicit marker to distinguish symmetric groups from lists. -INPUT_SYMMETRY_KEY = "input_symmetry" -InputSymmetry = int | list["InputSymmetry"] | dict[str, list["InputSymmetry"]] +@dataclass(slots=True) +class _SymmetricInputs: + """An unordered group of argument positions and nested groups.""" + + children: list[InputSymmetry] + + +InputSymmetry = int | list["InputSymmetry"] | _SymmetricInputs def encode_input_symmetry( @@ -78,42 +83,61 @@ def encode_input_symmetry( return None remaining = dict(enumerate(inputs)) - symmetric: list[tuple[frozenset[ArgumentGroup], list[InputSymmetry]]] = [] + symmetric: list[tuple[ArgumentGroup, InputSymmetry, list[InputSymmetry]]] = [] - def encode(group: ArgumentGroup) -> InputSymmetry: + def encode( + group: ArgumentGroup, available: dict[int, StreamProtocol], *, repeat: bool + ) -> InputSymmetry: if isinstance(group, tuple): - return [encode(child) for child in group] + return [encode(child, available, repeat=repeat) for child in group] if isinstance(group, frozenset): - children = [encode(child) for child in group] - symmetric.append((group, children)) - return {"symmetric": children} - for index, stream in remaining.items(): - if stream is group: - del remaining[index] - return index + 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") group = symmetry(inputs) try: - grouped = encode(group) + grouped = encode(group, remaining, repeat=False) except ValueError: - # Positions are optional metadata. A legacy descriptor can use input order - # when a custom grouping cannot be expressed with argument positions. + # Use argument order when the callback does not return the input streams. return None - # A frozenset can collapse repeated or content-equal streams. Restore their - # positions after claiming the explicit leaves, including leaves of ordered groups. - symmetric.sort( - key=lambda entry: min(_input_positions(entry[1]), default=len(inputs)) - ) - for index, stream in remaining.items(): - for members, children in symmetric: - if stream in members: - children.append(index) - break - - for _, children in symmetric: - children.sort(key=repr) + # A frozenset can collapse an equal leaf or an entire equal subgroup. + # Claim repeats of larger members first so their leaves stay together. + 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 return None if grouped == list(range(len(inputs))) else grouped @@ -121,7 +145,7 @@ def _input_positions(group: InputSymmetry) -> tuple[int, ...]: """Return every explicit position in a grouping.""" if isinstance(group, int): return (group,) - children = group if isinstance(group, list) else group["symmetric"] + children = group.children if isinstance(group, _SymmetricInputs) else group return tuple(index for child in children for index in _input_positions(child)) @@ -144,7 +168,9 @@ def _pool( pooled = inputs[0] if len(inputs) == 1 else hash_term(label, inputs) if own_term is None: return pooled - return hash_term(label, ("term", pooled, own_term)) + # Extension terms may compare equal in Python while encoding differently. + # The enclosing chain memo already caches their result until invalidation. + return _hash(label, ("term", pooled, own_term)) def _pool_group( @@ -158,8 +184,8 @@ def _pool_group( if isinstance(group, int): return inputs[group] - symmetric = isinstance(group, dict) - group_children = group["symmetric"] if isinstance(group, dict) else group + symmetric = isinstance(group, _SymmetricInputs) + group_children = group.children if isinstance(group, _SymmetricInputs) else group children = [_pool_group(child, inputs, hash_term) for child in group_children] if symmetric: children.sort(key=lambda child: child.structure_key) @@ -248,11 +274,7 @@ def _identity_hash(self, label: str, preimage: tuple[object, ...]) -> ContentHas self._identity_name_hashes = {} hashes = self._identity_name_hashes key = (label, preimage) - try: - cached = hashes.get(key) - except TypeError: - # Semantic terms can contain values that Python cannot use as dict keys. - return _hash(label, preimage) + cached = hashes.get(key) if cached is None: cached = hashes[key] = _hash(label, preimage) return cached @@ -280,12 +302,6 @@ def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGrou """Group inputs according to the producer's argument symmetry.""" return inputs - def _identity_input_symmetry( - self, inputs: tuple[StreamProtocol, ...] - ) -> InputSymmetry | None: - """Return positional grouping when it differs from argument order.""" - return encode_input_symmetry(inputs, self._identity_symmetry) - def _identity_node_pipeline_hash( self, hasher: SemanticHasherProtocol ) -> ContentHash: @@ -349,7 +365,7 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains ) # Symmetric groups use structural ordering. Occurrences keep repeats. - group = self._identity_input_symmetry(inputs) if inputs else None + group = encode_input_symmetry(inputs, self._identity_symmetry) if group is None: group = list[InputSymmetry](range(len(inputs))) children = tuple( diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py index 74f5ab0be..3fd408450 100644 --- a/src/orcapod/core/nodes/operator_node.py +++ b/src/orcapod/core/nodes/operator_node.py @@ -29,7 +29,6 @@ import pyarrow.compute as pc from orcapod import contexts -from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY, InputSymmetry from orcapod.core.nodes.provenance_methods import ProvenanceMethods from orcapod.core.data_tags import ( mark_data_tags, @@ -298,7 +297,12 @@ def identity_structure(self) -> Any: return self.pipeline_identity_structure() def _identity_leaf(self, walk: IdentityWalkProtocol) -> None: - """An operator remains a computation when its pod is unavailable.""" + """Refuse to compute provisional chains without the operator's grouping.""" + if self._operator is None: + raise ValueError( + "Cannot compute operator identity chains because the saved form " + "does not carry input symmetry yet and the operator is unavailable." + ) return None def pipeline_identity_structure(self) -> Any: @@ -338,14 +342,6 @@ def pipeline_hash(self, hasher=None) -> ContentHash: # Stream interface # ------------------------------------------------------------------ - def _identity_input_symmetry( - self, inputs: tuple[StreamProtocol, ...] - ) -> InputSymmetry | None: - """Recover the grouping of a saved operator when its producer is missing.""" - if self._operator is None: - return self._descriptor.get(INPUT_SYMMETRY_KEY) - return super()._identity_input_symmetry(inputs) - @property def producer(self) -> OperatorPodProtocol: return self._operator diff --git a/src/orcapod/core/sources/cached_source.py b/src/orcapod/core/sources/cached_source.py index 15501c76c..2eb8e40cc 100644 --- a/src/orcapod/core/sources/cached_source.py +++ b/src/orcapod/core/sources/cached_source.py @@ -50,6 +50,8 @@ if TYPE_CHECKING: from orcapod.protocols.database_protocols import DatabaseRegistryProtocol + from orcapod.protocols.hashing_protocols import SemanticHasherProtocol + from orcapod.types import ContentHash logger = logging.getLogger(__name__) @@ -268,6 +270,26 @@ def source_name(self) -> str: """The name part of the wrapped source's source id.""" return parse_source_id(self._source.source_id).name + @override + def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: + """Use the wrapped source's schema guard before inspecting cached structure.""" + if isinstance(self._source, RootSource) and schema_requires_io( + self._source, ColumnConfig() + ): + return self._source._identity_pipeline_hash(hasher) + return super()._identity_pipeline_hash(hasher) + + @override + def _identity_node_pipeline_hash( + self, hasher: SemanticHasherProtocol + ) -> ContentHash: + """Use the wrapped source's pending structure until its schema is known.""" + if isinstance(self._source, RootSource) and schema_requires_io( + self._source, ColumnConfig() + ): + return self._source._identity_node_pipeline_hash(hasher) + return super()._identity_node_pipeline_hash(hasher) + def _compute_arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema]": """The wrapped source's Arrow schemas: the cache stores that source's rows.""" schemas = typed_arrow_schemas(self._source) diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py index 72befb63f..adfb80808 100644 --- a/src/orcapod/core/streams/base.py +++ b/src/orcapod/core/streams/base.py @@ -767,7 +767,7 @@ def _identity_inputs(self) -> tuple[StreamProtocol, ...]: return self.upstreams def _identity_symmetry(self, inputs: tuple[StreamProtocol, ...]) -> ArgumentGroup: - """Respect the producer's symmetry, or the saved order when it is absent.""" + """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) @@ -779,7 +779,15 @@ def _identity_leaf( return None from orcapod.core.sources.base import RootSource - name = self.source_name if isinstance(self, RootSource) else None + name = None + if isinstance(self, RootSource): + try: + name = self.source_name + except ValueError: + # The saved-source fallback already names an anonymous source. + if self.source_id != "unknown": + raise + name = "unknown" return name, self.content_hash() @property diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py index db33da27a..0b58b8f37 100644 --- a/src/orcapod/pipeline/graph.py +++ b/src/orcapod/pipeline/graph.py @@ -137,7 +137,6 @@ def save(self, path: str | Path) -> None: serialize_arrow_schemas, serialize_output_schema, ) - from orcapod.core.identity_chains import INPUT_SYMMETRY_KEY from orcapod.core.nodes import OperatorNode, FunctionNode from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass from orcapod.core.streams.base import shared_zero_row_memo, typed_arrow_schemas @@ -289,9 +288,6 @@ def save(self, path: str | Path) -> None: descriptor["operator_config"] = copy.deepcopy( node._descriptor["operator_config"] ) - symmetry = node._identity_input_symmetry(node.upstreams) # pyright: ignore[reportPrivateUsage] # Persist the same grouping used by the node's identity chains. - if symmetry is not None: - descriptor[INPUT_SYMMETRY_KEY] = symmetry descriptor["table_scope"] = node._table_scope nodes[content_hash_str] = descriptor diff --git a/tests/test_channels/test_polling_source.py b/tests/test_channels/test_polling_source.py index b43da5775..ebe0c5f13 100644 --- a/tests/test_channels/test_polling_source.py +++ b/tests/test_channels/test_polling_source.py @@ -1860,3 +1860,34 @@ def test_polling_leaf_chains_stay_stable_when_a_batch_supplies_schema() -> None: assert (source.source_chain(), source.name_chain()) == before assert source.node_hash() != pending_hash assert source._chain_content_hash() + + +def test_cached_polling_source_has_node_hash_without_fetch( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """A cache preserves the pending structure term of a polling source.""" + from orcapod.databases import InMemoryArrowDatabase + from orcapod.sources import CachedSource + + source = PollingSource( + FakeDynamicSource(batches=[_batch(1, 10)]), + tag_columns="id", + source_id="pending", + record_id_columns="id", + ) + cached = CachedSource(source, InMemoryArrowDatabase()) + with monkeypatch.context() as guard: + + def unexpected_fetch() -> None: + pytest.fail("pending identities must not fetch for a schema") + + guard.setattr(source, "_sync_poll_and_commit", unexpected_fetch) + assert cached.source_chain() == source.source_chain() + assert cached.name_chain() == source.name_chain() + pending = cached.node_hash() + assert pending == source.node_hash() + with pytest.raises(ValueError, match="requires a schema"): + _ = cached._chain_content_hash() + assert list(source) + assert cached.node_hash() == source.node_hash() != pending + assert cached._chain_content_hash() == source._chain_content_hash() diff --git a/tests/test_hashing/data/three_chain_step_1_saved_job.json b/tests/test_hashing/data/three_chain_step_1_saved_job.json new file mode 100644 index 000000000..19cc8026c --- /dev/null +++ b/tests/test_hashing/data/three_chain_step_1_saved_job.json @@ -0,0 +1,406 @@ +{ + "orcapod_pipeline_job_version": "0.4.0", + "orcapod_version": "test-version", + "run": { + "run_id": "fixed-run-id", + "status": "complete", + "unbound_sources": [], + "node_job_content_hashes": { + "select_x": "semantic_v1:954cae2b749baf7f1cb1d8adc5a3a55e21ca4448932b7d2117a494cee9b07c42", + "merge": "semantic_v1:245faafe6354085f63afa1812bb597650796f1f081d2560b0e98e5424aec7f01", + "join": "semantic_v1:ec08c2288c86e46db46956ed1115700edaece4bee186cb6dc14175f0feeadc73", + "select_y": "semantic_v1:49e9383590e3f8055ce986712729d34f022fc8d94c56c8815434ef40350b4bb1", + "rejoin": "semantic_v1:e5a6c507d1b38e9a78c423e4e0a50adda0953541ba1a235ccf2bdd80ca7c45c5" + }, + "expected_rows": { + "select_x": 0, + "merge": 0, + "join": 0, + "select_y": 0, + "rejoin": 0 + } + }, + "pipeline": { + "orcapod_pipeline_version": "0.4.0", + "orcapod_version": "test-version", + "pipeline": { + "name": [ + "saved_job_compat" + ] + }, + "nodes": { + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe": { + "node_type": "source", + "label": "left", + "content_hash": "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "pipeline_hash": "semantic_v1:eff5e7f34fbf02243dcc66d68814b1c4c6b8f51993acf6596535fa3f14d9e4aa", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "left" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "left", + "tag_schema": { + "region": "large_string", + "item": "int64" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb": { + "node_type": "source", + "label": "right", + "content_hash": "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb", + "pipeline_hash": "semantic_v1:010a68e7352ee0070ac28e2b0ea6b934080d52d2d9c51ad8c626031c71e40ea4", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "u": "int64", + "v": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "source_node", + "right" + ], + "data_context_key": "std:v1:default", + "config": null, + "source_config": { + "source_type": "node", + "name": "right", + "tag_schema": { + "region": "large_string", + "item": "int64" + }, + "data_schema": { + "u": "int64", + "v": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "reconstructable": true + }, + "semantic_v1:8305b9cbe4c8e4033639fe7fd28976c09df777dd5b88af43cccee1ea9a178c11": { + "node_type": "operator", + "label": "select_x", + "content_hash": "semantic_v1:8305b9cbe4c8e4033639fe7fd28976c09df777dd5b88af43cccee1ea9a178c11", + "pipeline_hash": "semantic_v1:2f2e2c2932ab11b4b8ae12ead822b2d90ac6b5f6f23d020303118ea85b3a85f3", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "x": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "SelectDataColumns", + "6a76fccd6a5401a68d34aa9f8b8fe23eaab30dba75bc061364e2f9ec83b8a302" + ], + "data_context_key": "std:v1:default", + "config": null, + "inputs": [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe" + ], + "operator_config": { + "class_name": "SelectDataColumns", + "module_path": "orcapod.core.operators.column_selection", + "config": { + "columns": [ + "x" + ], + "strict": true + } + }, + "table_scope": "pipeline_hash" + }, + "semantic_v1:a663f199323c30423fdc1d0e368db868e95babc5e34b2167b1ae5a3855bbc86c": { + "node_type": "operator", + "label": "merge", + "content_hash": "semantic_v1:a663f199323c30423fdc1d0e368db868e95babc5e34b2167b1ae5a3855bbc86c", + "pipeline_hash": "semantic_v1:5ab3866d866c7ba40af959906c636d66aa45e54a2b847207cdd3be69da10d5fc", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "x": "int64", + "y": "int64", + "u": "int64", + "v": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "MergeJoin", + "cc4a3c03deacdd328626d12e95ace2f5d8a27ca8f6180a22872addf92cf46627" + ], + "data_context_key": "std:v1:default", + "config": null, + "inputs": [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb" + ], + "operator_config": { + "class_name": "MergeJoin", + "module_path": "orcapod.core.operators.merge_join", + "config": {} + }, + "table_scope": "pipeline_hash" + }, + "semantic_v1:5fdf59d2241101a2e3585cdbe87e7153f334ea1472cac4f697163b29198cceae": { + "node_type": "operator", + "label": "join", + "content_hash": "semantic_v1:5fdf59d2241101a2e3585cdbe87e7153f334ea1472cac4f697163b29198cceae", + "pipeline_hash": "semantic_v1:a39fca094af0ab19137a63bc97731ce2e6e6cf43fe7b724cefbbb37dcd2e7fba", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "u": "int64", + "v": "int64", + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "Join", + "295ca9336dc1935b209d140b0b4cdda1d61024372adfee6f4b746781972e4e83" + ], + "data_context_key": "std:v1:default", + "config": null, + "inputs": [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb" + ], + "operator_config": { + "class_name": "Join", + "module_path": "orcapod.core.operators.join", + "config": {} + }, + "table_scope": "pipeline_hash" + }, + "semantic_v1:ada002923024d25c5d7cb59710fe7ef2689147d2893479a38c50d019c9ea018b": { + "node_type": "operator", + "label": "select_y", + "content_hash": "semantic_v1:ada002923024d25c5d7cb59710fe7ef2689147d2893479a38c50d019c9ea018b", + "pipeline_hash": "semantic_v1:affa4d80f90965b0d90e1badee7e8b54b561c3c86071faf4f18de1e68aba4166", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "SelectDataColumns", + "b825c9b09b01160b3c3c8d7183370f31228977e33eff2f029e349d7c4b75b9f5" + ], + "data_context_key": "std:v1:default", + "config": null, + "inputs": [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe" + ], + "operator_config": { + "class_name": "SelectDataColumns", + "module_path": "orcapod.core.operators.column_selection", + "config": { + "columns": [ + "y" + ], + "strict": true + } + }, + "table_scope": "pipeline_hash" + }, + "semantic_v1:eab9a57fa5b50f86133f392e0f0613c0883200ab44b07562a486cb416e2373b8": { + "node_type": "operator", + "label": "rejoin", + "content_hash": "semantic_v1:eab9a57fa5b50f86133f392e0f0613c0883200ab44b07562a486cb416e2373b8", + "pipeline_hash": "semantic_v1:8394a3f839b83cc529efd8899e5680dd4e7179afcdcc373bf7fe1af7b02e92cb", + "output_schema": { + "tag": { + "region": "large_string", + "item": "int64" + }, + "data": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "node_uri": [ + "Rejoin", + "ac249d197a1dca981ce8ddc10aa5e11d1e969e1aff6130a64c8a810779250335" + ], + "data_context_key": "std:v1:default", + "config": null, + "inputs": [ + "semantic_v1:8305b9cbe4c8e4033639fe7fd28976c09df777dd5b88af43cccee1ea9a178c11", + "semantic_v1:ada002923024d25c5d7cb59710fe7ef2689147d2893479a38c50d019c9ea018b" + ], + "operator_config": { + "class_name": "Rejoin", + "module_path": "orcapod.core.operators.rejoin", + "config": {} + }, + "table_scope": "pipeline_hash" + } + }, + "edges": [ + [ + "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb", + "semantic_v1:5fdf59d2241101a2e3585cdbe87e7153f334ea1472cac4f697163b29198cceae" + ], + [ + "semantic_v1:305832bb36171c9b6d0edd8ba776dbf30e86884b1050d55eeae0da26303057eb", + "semantic_v1:a663f199323c30423fdc1d0e368db868e95babc5e34b2167b1ae5a3855bbc86c" + ], + [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:5fdf59d2241101a2e3585cdbe87e7153f334ea1472cac4f697163b29198cceae" + ], + [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:8305b9cbe4c8e4033639fe7fd28976c09df777dd5b88af43cccee1ea9a178c11" + ], + [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:a663f199323c30423fdc1d0e368db868e95babc5e34b2167b1ae5a3855bbc86c" + ], + [ + "semantic_v1:659e1f6113487e62207c559c4555fad2705b08d8131e76e53392dd2fb4de52fe", + "semantic_v1:ada002923024d25c5d7cb59710fe7ef2689147d2893479a38c50d019c9ea018b" + ], + [ + "semantic_v1:8305b9cbe4c8e4033639fe7fd28976c09df777dd5b88af43cccee1ea9a178c11", + "semantic_v1:eab9a57fa5b50f86133f392e0f0613c0883200ab44b07562a486cb416e2373b8" + ], + [ + "semantic_v1:ada002923024d25c5d7cb59710fe7ef2689147d2893479a38c50d019c9ea018b", + "semantic_v1:eab9a57fa5b50f86133f392e0f0613c0883200ab44b07562a486cb416e2373b8" + ] + ] + }, + "bindings": { + "sources": { + "left": { + "source_type": "dict", + "tag_columns": [ + "region", + "item" + ], + "tag_only_columns": true, + "source_name": "left", + "source_name_given": true, + "source_version": 1, + "full_source_id": "dict_v1:left", + "content_hash": "semantic_v1:6ac99d445997b31f49a4ea089cf02a39b4b6e057a956f3708a1e5479fbe1c822", + "pipeline_hash": "semantic_v1:eff5e7f34fbf02243dcc66d68814b1c4c6b8f51993acf6596535fa3f14d9e4aa", + "tag_schema": { + "region": "large_string", + "item": "int64" + }, + "data_schema": { + "x": "int64", + "y": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + }, + "right": { + "source_type": "dict", + "tag_columns": [ + "region", + "item" + ], + "tag_only_columns": true, + "source_name": "right", + "source_name_given": true, + "source_version": 1, + "full_source_id": "dict_v1:right", + "content_hash": "semantic_v1:8a97b841d50404d1ef29340171b2d0401dce7361d62c43b61465ddc23a695022", + "pipeline_hash": "semantic_v1:010a68e7352ee0070ac28e2b0ea6b934080d52d2d9c51ad8c626031c71e40ea4", + "tag_schema": { + "region": "large_string", + "item": "int64" + }, + "data_schema": { + "u": "int64", + "v": "int64" + }, + "nullable": { + "tag": [], + "data": [] + } + } + }, + "database": { + "type": "in_memory", + "base_path": [], + "max_hierarchy_depth": 10 + }, + "result_database": null + } +} \ No newline at end of file diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index c56181187..6cd8113d1 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -3,22 +3,27 @@ from __future__ import annotations import asyncio +from pathlib import Path from typing import TYPE_CHECKING import pytest +from typing_extensions import override from orcapod import Pipeline, PipelineJob, SourceNode, function_pod -from orcapod.core.identity_chains import NAME_CHAIN_HASH_LABEL, SOURCE_CHAIN_HASH_LABEL +from orcapod.core.identity_chains import ( + NAME_CHAIN_HASH_LABEL, + NODE_HASH_LABEL, + SLOT_NAME_HASH_LABEL, + SOURCE_CHAIN_HASH_LABEL, +) from orcapod.databases import InMemoryArrowDatabase from orcapod.errors import UnboundSourceError from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher from orcapod.operators import Index, Join, MergeJoin, Rejoin -from orcapod.sources import DictSource +from orcapod.sources import DictSource, SourceProxy from orcapod.types import ContentHash if TYPE_CHECKING: - from pathlib import Path - from collections.abc import Collection from orcapod.protocols.core_protocols import ArgumentGroup, StreamProtocol @@ -223,7 +228,7 @@ def test_unbound_blueprint_names_all_upstream_slots() -> None: @pytest.mark.filterwarnings("ignore:Index is provisional") -def test_loaded_blueprint_computes_names_through_a_missing_pod(tmp_path: Path) -> None: +def test_loaded_blueprint_chains_require_the_operator(tmp_path: Path) -> None: source = _source("reading", False) lists = DictSource( [{"item": 1, "region": "north", "values": [1, 2], "y": 3}], @@ -235,16 +240,21 @@ def test_loaded_blueprint_computes_names_through_a_missing_pod(tmp_path: Path) - with pipeline: add.pod(source, label="first") Index(column="values", i=0)(lists, label="picked") - expected = {label: node.node_hash() for label, node in pipeline.nodes.items()} + expected = pipeline.nodes["first"].node_hash() path = tmp_path / "blueprint.json" pipeline.save(path) loaded = Pipeline.load(path) - for label, slot in (("first", "reading"), ("picked", "lists")): - node = loaded.nodes[label] - assert node.producer is None - assert node.node_hash() == expected[label] - with pytest.raises(UnboundSourceError, match=f"unbound.*{slot}"): - node._chain_content_hash() + function = loaded.nodes["first"] + assert function.producer is None + assert function.node_hash() == expected + with pytest.raises(UnboundSourceError, match="unbound.*reading"): + function._chain_content_hash() + + operator = loaded.nodes["picked"] + assert operator.producer is None + assert operator.pipeline_hash() == pipeline.nodes["picked"].pipeline_hash() + with pytest.raises(ValueError, match="saved form does not carry input symmetry"): + operator.node_hash() def _data_tags(name: str, reverse: bool = False) -> DictSource: @@ -318,10 +328,10 @@ def test_equal_structure_join_pipeline_hash_depends_only_on_structure() -> None: @pytest.mark.parametrize("missing_builtin", [False, True]) -def test_loaded_commutative_stub_keeps_chains( +def test_loaded_commutative_stub_requires_unsaved_symmetry( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, missing_builtin: bool ) -> None: - """A missing producer must still pool its inputs in symmetric order.""" + """The saved legacy hashes are available when the new chains are undefined.""" from orcapod.pipeline.serialization import OPERATOR_REGISTRY from orcapod.sources import CSVSource @@ -339,19 +349,92 @@ class UnregisteredJoin(Join): with job: (Join() if missing_builtin else UnregisteredJoin())(*inputs, label="joined") job.run() - expected = _hashes(job.nodes["joined"]) + original = job.nodes["joined"] path = tmp_path / "job.json" job.save(path) if missing_builtin: monkeypatch.delitem(OPERATOR_REGISTRY, "Join") - loaded = PipelineJob.load(path, database=job.database) - assert loaded.nodes["joined"].producer is None - assert _hashes(loaded.nodes["joined"]) == expected - loaded.save(path) - assert ( - _hashes(PipelineJob.load(path, database=job.database).nodes["joined"]) - == expected + for _ in range(2): + loaded = PipelineJob.load(path, database=job.database) + node = loaded.nodes["joined"] + assert node.producer is None + assert node.pipeline_hash() == original.pipeline_hash() + assert node.content_hash() == original.content_hash() + for accessor in ( + node.source_chain, + node.name_chain, + node.node_hash, + node._chain_content_hash, + ): + with pytest.raises( + ValueError, match="saved form does not carry input symmetry" + ): + accessor() + loaded.save(path) + + +def test_saved_job_bytes_match_main( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A completed job writes exactly the bytes produced before the chain change.""" + monkeypatch.setattr("orcapod.__version__", "test-version") + left = _source("left", False) + right = _source("right", False, right=True) + job = PipelineJob(name="saved_job_compat", database=InMemoryArrowDatabase()) + with job: + _ = Join()(left, right, label="join") + _ = MergeJoin()(left, right, label="merge") + x = left.select_data_columns(["x"], label="select_x") + y = left.select_data_columns(["y"], label="select_y") + _ = Rejoin()(x, y, label="rejoin") + _ = job.run() + monkeypatch.setattr(job, "_run_id", "fixed-run-id") + path = tmp_path / "job.json" + job.save(path) + # Captured with this same job on main at 37f784318931. + expected = Path(__file__).with_name("data") / "three_chain_step_1_saved_job.json" + assert path.read_bytes() == expected.read_bytes() + + +def test_nested_symmetry_keeps_repeated_ordered_pairs() -> None: + """Each ordered pair contributes to the enclosing symmetric pool.""" + + class PairJoin(Join): + @override + def argument_symmetry( + self, streams: Collection[StreamProtocol] + ) -> ArgumentGroup: + a, b, c, d = streams + return frozenset(((a, b), (c, d))) + + left, right = _data_tags("a"), _data_tags("b") + result = PairJoin()(left, right, left, right) + pair = MergeJoin()(left, right) + for label, group_chain, result_chain in ( + (SOURCE_CHAIN_HASH_LABEL, pair.source_chain(), result.source_chain()), + (NAME_CHAIN_HASH_LABEL, pair.name_chain(), result.name_chain()), + ): + hasher = SemanticAwarePythonHasher(hasher_id=label) + assert result_chain == hasher.hash_object((group_chain, group_chain)) + + +def test_anonymous_source_proxy_uses_saved_identity_and_slot_name() -> None: + """A proxy's anonymous saved ID is usable as its implicit slot name.""" + source = _source("reading", False) + proxy = SourceProxy( + "unknown", + source.content_hash().to_string(), + source.pipeline_hash().to_string(), + *source.output_schema(), ) + name = SemanticAwarePythonHasher(hasher_id=SLOT_NAME_HASH_LABEL).hash_object( + ("slot", "unknown") + ) + assert proxy.source_chain() == source.content_hash() + assert proxy.name_chain() == name + assert proxy.node_hash() == SemanticAwarePythonHasher( + hasher_id=NODE_HASH_LABEL + ).hash_object((source.pipeline_hash(), name)) @pytest.mark.parametrize("downstream", [False, True]) @@ -496,7 +579,7 @@ def test_copying_a_slot_under_a_new_name_recomputes_the_name_chain() -> None: assert _hashes(original) == before -def test_custom_operator_symmetry_receives_streams_on_save(tmp_path: Path) -> None: +def test_custom_operator_symmetry_receives_streams(tmp_path: Path) -> None: """A custom operator can require concrete stream objects in its callback.""" from orcapod.core.nodes.source_node import SourceNodeBase @@ -631,3 +714,24 @@ def test_identity_terms_accept_canonical_semantic_values( ) assert chain() == expected assert chain() == expected + + +def test_name_term_memo_respects_semantic_types_after_rebind( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Python-equal terms can encode distinct semantic values.""" + source = _source("reading", False) + job = PipelineJob(name="name_terms", database=InMemoryArrowDatabase()) + with job: + _ = source.select_data_columns(["x"], label="result") + result = job.nodes["result"] + term: bool | int = True + monkeypatch.setattr(result, "_identity_terms", lambda: (None, term)) + first = result.name_chain() + term = 1 + job.bind({"reading": _source("rebound", False)}) + expected = SemanticAwarePythonHasher(hasher_id=NAME_CHAIN_HASH_LABEL).hash_object( + ("term", job.nodes["reading"].name_chain(), term) + ) + assert first != expected + assert result.name_chain() == expected From 3bb81bf3a044936f6d4809a603b25b896c43c04e Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:36:37 -0800 Subject: [PATCH 05/38] fix(identity): reject combined hashes for collapsed symmetry --- changelog.d/ITL-1559.md | 4 + docs/dev/design_issues/ITL-1559-TC1.md | 4 + src/orcapod/core/identity_chains.py | 36 ++++-- src/orcapod/protocols/hashing_protocols.py | 7 +- src/orcapod/protocols/node_protocols.py | 6 +- tests/test_hashing/test_identity_chains.py | 116 +++++++++++++++++++- tests/test_pipeline/test_node_protocols.py | 3 + tests/test_protocols/test_node_protocols.py | 7 +- 8 files changed, 169 insertions(+), 14 deletions(-) diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index f26bdd8f2..25a929199 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -3,3 +3,7 @@ - Streams, recorded invocations, and job nodes expose `source_chain()`, `name_chain()`, and `node_hash()`. The node hash identifies a computation by its structure and input slot names, so it is available on an unbound pipeline. A polling source can report its node hash before its first batch supplies the schema. Existing pipeline and content hashes keep their values. - A job loaded without an operator implementation still exposes its saved hashes. Accessing the new chains for that operator raises an error until the saved format carries input symmetry. + +### Known limitations + +- The new combined hashes raise an error when a commutative group drops content-equal inputs from its argument symmetry (ITL-1590). The legacy pipeline and content hashes remain available. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index 159183c68..4a66fac79 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -18,3 +18,7 @@ The step 1 follow-up serializes binding and chain reads. Saved jobs retain the existing file format. An operator loaded without its implementation cannot report the new chains until a later step records input symmetry. Schema-less polling sources report a node hash 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. diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index ee1177819..9530ec8b0 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -77,10 +77,10 @@ class _SymmetricInputs: def encode_input_symmetry( inputs: tuple[StreamProtocol, ...], symmetry: Callable[[tuple[StreamProtocol, ...]], ArgumentGroup], -) -> InputSymmetry | None: - """Translate a pod's grouping of real streams into argument positions.""" +) -> tuple[InputSymmetry | None, bool]: + """Encode argument positions and report whether a symmetric group lost inputs.""" if len(inputs) < 2: - return None + return None, False remaining = dict(enumerate(inputs)) symmetric: list[tuple[ArgumentGroup, InputSymmetry, list[InputSymmetry]]] = [] @@ -116,10 +116,12 @@ def encode( grouped = encode(group, remaining, repeat=False) except ValueError: # Use argument order when the callback does not return the input streams. - return None + return None, False + collapsed = bool(remaining and symmetric) # A frozenset can collapse an equal leaf or an entire equal subgroup. - # Claim repeats of larger members first so their leaves stay together. + # 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)) @@ -137,8 +139,8 @@ def encode( break remaining = available if remaining: - return None - return None if grouped == list(range(len(inputs))) else grouped + return None, collapsed + return (None if grouped == list(range(len(inputs))) else grouped), collapsed def _input_positions(group: InputSymmetry) -> tuple[int, ...]: @@ -217,6 +219,12 @@ 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.""" @@ -362,10 +370,11 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains name_term, ), upstream.unbound_slots, + collapsed_input_symmetry=upstream.collapsed_input_symmetry, ) # Symmetric groups use structural ordering. Occurrences keep repeats. - group = encode_input_symmetry(inputs, self._identity_symmetry) + group, collapsed = encode_input_symmetry(inputs, self._identity_symmetry) if group is None: group = list[InputSymmetry](range(len(inputs))) children = tuple( @@ -386,6 +395,8 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains 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 | None: @@ -403,10 +414,12 @@ def _chain_content_hash(self) -> ContentHash: Raises: UnboundSourceError: If any contributing source slot is unbound. + ValueError: If a commutative group dropped content-equal inputs. """ with self._identity_lock: walk = IdentityWalk(self._identity_hasher) chains = walk.visit(self) + _require_complete_symmetry(chains) if chains.sources is None: names = ", ".join(repr(name) for name in sorted(chains.unbound_slots)) raise UnboundSourceError( @@ -417,10 +430,15 @@ def _chain_content_hash(self) -> ContentHash: ) def node_hash(self) -> ContentHash: - """Combine structure and slot names, independently of binding.""" + """Combine structure and slot names. + + Raises: + ValueError: If a commutative group dropped content-equal inputs. + """ with self._identity_lock: walk = IdentityWalk(self._identity_hasher) chains = walk.visit(self) + _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/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index 76e42f59e..304425ce9 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -14,13 +14,18 @@ @dataclass(frozen=True, slots=True) class IdentityChains: - """The three chains of one element. An unbound slot leaves sources absent.""" + """The three chains of one element. + + An unbound slot leaves sources absent. Collapsed symmetry invalidates the + combined hashes. + """ pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] sources: ContentHash | None names: ContentHash unbound_slots: frozenset[str] = frozenset() node_pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] | None = None + collapsed_input_symmetry: bool = False class IdentityWalkProtocol(Protocol): diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 78b96b54f..60bb7b3a7 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -28,7 +28,7 @@ class _NodeIdentityProtocol(Protocol): - """Public identities available on every orchestrated node.""" + """Identity accessors available on every orchestrated node.""" def node_hash(self) -> ContentHash: """Combine structure and slot names.""" @@ -42,6 +42,10 @@ def name_chain(self) -> ContentHash: """Return the chain of source-slot names.""" ... + def _chain_content_hash(self) -> ContentHash: + """Combine structure and sources for the provisional content identity.""" + ... + @runtime_checkable class SourceNodeProtocol(_NodeIdentityProtocol, Protocol): diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index 6cd8113d1..aaf3e4056 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -3,8 +3,10 @@ from __future__ import annotations import asyncio +from itertools import permutations from pathlib import Path -from typing import TYPE_CHECKING +from random import Random +from typing import TYPE_CHECKING, cast import pytest from typing_extensions import override @@ -418,6 +420,118 @@ def argument_symmetry( assert result_chain == hasher.hash_object((group_chain, group_chain)) +@pytest.fixture +def collapsed_nested_pair() -> tuple[StreamProtocol, StreamProtocol]: + """Build the review's two orderings of content-equal, differently named slots.""" + from orcapod.operators import SelectDataColumns + + class ReversedPairJoin(Join): + @override + def argument_symmetry( + self, streams: Collection[StreamProtocol] + ) -> ArgumentGroup: + a, b, c, d = streams + return frozenset(((a, b), (d, c))) + + source = _data_tags("reading") + job = PipelineJob(name="nested_pairs", database=InMemoryArrowDatabase()) + with job: + for name in "abcd": + _ = SelectDataColumns(["x", "y"])( + SourceNode.from_stream(source, name=name), label=f"out_{name}" + ) + 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 + 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], +) -> None: + """Swapping the commutative groups preserves their ordered name chains.""" + original, swapped = collapsed_nested_pair + assert original.pipeline_hash() == swapped.pipeline_hash() + assert original.source_chain() == swapped.source_chain() + assert original.name_chain() == swapped.name_chain() + assert _hashes(original) == _hashes(swapped) + + +def test_combined_hashes_refuse_collapsed_commutative_groups( + collapsed_nested_pair: tuple[StreamProtocol, StreamProtocol], +) -> None: + """A collapsed group makes both combined hashes undefined, including downstream.""" + from orcapod.operators import SelectDataColumns + + source = _data_tags("reading") + repeated = Join()(source, source) + for result in (repeated, *collapsed_nested_pair): + assert result.pipeline_hash() + assert result.content_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() + with pytest.raises(ValueError, match="commutative.*ITL-1590"): + _ = stream._chain_content_hash() + + +@pytest.mark.parametrize("seed", range(8)) +def test_permutations_in_nested_operator_trees(seed: int) -> None: + """Every commutative permutation keeps identity; an ordered swap changes it.""" + from orcapod.core.nodes.source_node import SourceJobNode + + class OrderedJoin(Join): + @override + def argument_symmetry( + self, streams: Collection[StreamProtocol] + ) -> ArgumentGroup: + return tuple(streams) + + rng = Random(seed) + leaves: list[SourceJobNode] = [] + for index in range(6): + tag = f"tag_{index}" + name = f"slot_{index}" + source = DictSource( + [{"key": 1, tag: index}], tag_columns=["key", tag], source_id=name + ) + leaves.append(SourceJobNode.from_stream(source, name=name)) + + def build_tree(streams: list[SourceJobNode]) -> StreamProtocol: + if len(streams) == 1: + return streams[0] + splits = sorted( + rng.sample(range(1, len(streams)), rng.randint(1, min(2, len(streams) - 1))) + ) + edges = [0, *splits, len(streams)] + children = [ + build_tree(streams[start:stop]) for start, stop in zip(edges, edges[1:]) + ] + commutative = rng.choice([True, False]) + operator = Join() if commutative else OrderedJoin() + original = operator(*children) + hashes = (original.pipeline_hash(), *_hashes(original)) + if commutative: + for order in permutations(children): + result = operator(*order) + assert (result.pipeline_hash(), *_hashes(result)) == hashes + else: + result = operator(children[1], children[0], *children[2:]) + assert result.pipeline_hash() != hashes[0] + assert result._chain_content_hash() != hashes[1] + assert result.node_hash() != hashes[2] + return original + + _ = build_tree(leaves) + + def test_anonymous_source_proxy_uses_saved_identity_and_slot_name() -> None: """A proxy's anonymous saved ID is usable as its implicit slot name.""" source = _source("reading", False) diff --git a/tests/test_pipeline/test_node_protocols.py b/tests/test_pipeline/test_node_protocols.py index b670c5151..b7f633ef5 100644 --- a/tests/test_pipeline/test_node_protocols.py +++ b/tests/test_pipeline/test_node_protocols.py @@ -41,6 +41,9 @@ def source_chain(self): def name_chain(self): return None + def _chain_content_hash(self): + return None + class TestSourceNodeProtocol: def test_requires_execute(self): diff --git a/tests/test_protocols/test_node_protocols.py b/tests/test_protocols/test_node_protocols.py index 8565157e6..13ab0d6b3 100644 --- a/tests/test_protocols/test_node_protocols.py +++ b/tests/test_protocols/test_node_protocols.py @@ -83,9 +83,11 @@ def test_is_operator_node_false_for_source(self, source_node): assert is_operator_node(source_node) is False -@pytest.mark.parametrize("missing", ["node_hash", "source_chain", "name_chain"]) +@pytest.mark.parametrize( + "missing", ["node_hash", "source_chain", "name_chain", "_chain_content_hash"] +) def test_execution_node_protocols_require_identity_accessors(missing): - """An execution-shaped object must expose all three public identities.""" + """An execution-shaped object must expose the public and provisional identities.""" from types import SimpleNamespace from orcapod.protocols.node_protocols import ( @@ -110,6 +112,7 @@ def operation(*args, **kwargs): node_hash=operation, source_chain=operation, name_chain=operation, + _chain_content_hash=operation, ) complete = SimpleNamespace(**methods) del methods[missing] From a3e9a925c61be44b37c754ff1b9c69441c2d3540 Mon Sep 17 00:00:00 2001 From: "Edgar Y. Walker" Date: Sat, 28 Nov 2026 04:58:42 -0800 Subject: [PATCH 06/38] fix(identity): resolve live bindings and canonical chain order --- changelog.d/ITL-1559.md | 4 + docs/dev/design_issues/ITL-1559-TC1.md | 3 + docs/reference/hashing.md | 15 +- src/orcapod/core/base.py | 28 +++- src/orcapod/core/identity_chains.py | 157 ++++++++++++++---- src/orcapod/core/nodes/source_node.py | 9 +- src/orcapod/core/sources/polling_source.py | 8 +- src/orcapod/core/streams/base.py | 4 +- .../semantic_hashing/semantic_hasher.py | 14 +- src/orcapod/protocols/hashing_protocols.py | 5 + tests/test_channels/test_polling_source.py | 31 ++++ tests/test_hashing/test_identity_chains.py | 118 ++++++++++++- 12 files changed, 340 insertions(+), 56 deletions(-) diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 25a929199..01cd7aebd 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -4,6 +4,10 @@ - A job loaded without an operator implementation still exposes its saved hashes. Accessing the new chains for that operator raises an error until the saved format carries input symmetry. +### Fixed + +- Source chains follow rebindings inside composite input bindings. Name chains can be read without fetching a polling source's rows, and downstream identities that need its missing schema report that they are undefined. Nested commutative groups use the pipeline hash's canonical input order. + ### Known limitations - The new combined hashes raise an error when a commutative group drops content-equal inputs from its argument symmetry (ITL-1590). The legacy pipeline and content hashes remain available. diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index 4a66fac79..98a8e92f1 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -22,3 +22,6 @@ report a node hash 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. +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/reference/hashing.md b/docs/reference/hashing.md index 839cea7cb..9dce1cb8a 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -302,10 +302,10 @@ A stream, invocation or job node carries three chains. `pipeline_hash()` describ structure. `source_chain()` starts at each slot with the bound source's own content hash. `name_chain()` starts with the slot's name. A raw stream outside a slot contributes an anonymous name term. Display labels do not participate. A single-input step passes both chains -through unchanged unless the step contributes a term of its own. Multiple inputs are pooled in argument order for an ordered -operator and by pipeline hash for a commutative operator. Within a pipeline-hash tie, -the source and name chains each sort their own values. Repeated inputs contribute -at every position. +through unchanged unless the step contributes a term of its own. Ordered groups pool +inputs in argument order. Commutative groups use the pipeline hash's canonical order, +including when a group contains other groups. Within a tie the source and name chains +each sort their own values. Repeated inputs contribute at every position. `node_hash()` combines the pipeline hash and the name chain. The chain-based content hash combines the pipeline hash and the source chain and is undefined while any @@ -321,7 +321,8 @@ A polling source, including one wrapped in a cache, can report its source chain, name chain, and node hash before it knows its schema. The node hash combines a pending polling-source structure term with the name chain without polling. Once a batch supplies the schema, the node hash combines the pipeline hash with the same name -chain. The chain-based content hash requires the schema. +chain. The chain-based content hash requires the schema. Downstream identities that +need the pipeline hash report that it is undefined until the schema is known. ## Hash site inventory @@ -373,7 +374,7 @@ test session with `-p tests.test_hashing.hash_site_trace`. | Location | Hash consumed | Into | Form | Call sites | |---|---|---|---|---| -| nested hash in a structure | any nested hash: types, schemas, upstream streams, value hashes | the enclosing structure hash | `{"__type__": "hash", "label": ..., "digest": ...}` | `hashing/semantic_hashing/semantic_hasher.py:_nested_hash` | +| nested hash in a structure | any nested hash: types, schemas, upstream streams, value hashes | the enclosing structure hash | `{"__type__": "hash", "label": ..., "digest": ...}` | `hashing/semantic_hashing/semantic_hasher.py:nested_hash` | | schema identity | the `arrow_schema_v1` hashes of a source's or slot's Arrow tag and data schemas, or of a function's output Arrow schema | a source's content and pipeline identity, system-tag column names, the function `uri` | the `ContentHash` objects, nested | `utils/schema_utils.py:arrow_schema_identity`, `utils/schema_utils.py:compute_schema_hash`, `core/data_function.py:DataFunctionBase.output_data_schema_hash` | | union and generic alias arguments | argument type hashes, sorted by digest, then label (ordering only) | the type hash, via the nested form | as above | `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes`, `hashing/semantic_hashing/builtin_handlers.py:_sorted_hashes..` | | logical-type cell, scalar and container | a value-hashed cell's value hash | the Arrow table hash | `::