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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion .zed/rules
Original file line number Diff line number Diff line change
Expand Up @@ -1332,7 +1332,11 @@ these preimages anywhere else.
else: blocks) only for a module `import orcapod` never loads (networkx, deltalake,
pyarrow.fs, pyarrow.dataset, git) and the optional extras (psycopg, ray, spiral);
tests/test_utils/test_lazy_module_use.py checks it.
- Argument symmetry — operators return frozenset (commutative) or tuple (ordered).
- Argument symmetry — `structural_argument_symmetry(streams)` describes the occurrences
in a structural identity. A commutative `SymmetricGroup` sorts hashes and keeps repeats.
A tuple preserves argument order. Content hashes use the resulting pipeline hash
and the source chain. System-tag suffixes use the same structural digest as stored
table paths (ITL-1590).
- StaticOutputPod.process() → DynamicPodStream — wraps static_process() with staleness
detection and automatic recomputation.
- Source delegation — CSVSource, DictSource, etc. create an internal ArrowTableSource.
Expand Down
7 changes: 5 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -1376,8 +1376,11 @@ and `as_table()` methods. `all_info=True` sets everything to True.
`import orcapod` never loads (networkx, deltalake, `pyarrow.fs`, `pyarrow.dataset`, git)
and for the optional extras (psycopg, ray, spiral).
`tests/test_utils/test_lazy_module_use.py` checks it.
- **Argument symmetry** — each operator declares `argument_symmetry(streams)` returning
`frozenset` (commutative) or `tuple` (ordered). Determines how upstream hashes combine.
- **Argument symmetry** — `structural_argument_symmetry(streams)` describes the occurrences
in a structural identity. A commutative `SymmetricGroup` sorts hashes and keeps repeats.
A tuple preserves argument order. Content hashes use the resulting pipeline hash
and the source chain. System-tag suffixes use the same structural digest as stored
table paths (ITL-1590).
- **`StaticOutputPod.process()` → `DynamicPodStream`** — wraps `static_process()` output
with timestamp-based staleness detection and automatic recomputation.
- **Source delegation** — CSVSource, DictSource, etc. all create an internal
Expand Down
33 changes: 33 additions & 0 deletions changelog.d/ITL-1590.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
### Breaking changes and migration

- The pipeline hash now counts every input to a commutative operator. It changes
for a pipeline with a commutative step whose inputs include repeated or
content-equal streams. Its content hash changes with the pipeline hash and
source chain. Stored table paths for that step and its downstream
steps move because those paths include the pipeline hash.
- In a recorded `Join(a, a)` or a Join of two slots bound to the same source,
the stored rows used to have one source-id column and one record-id column
without a Join suffix. They now have both
columns at each of `::<pipeline_hash(a)>:0` and `::<pipeline_hash(a)>:1`,
with the same names as `Join(a, b)` when `a` and `b` have the same
structure. This changes the repeated join's stored entry IDs. Direct table,
row-channel and batch joins already included both positions. Downstream
operators that use the repeated join as an input to a system-tag suffix
now use its two-input hash, changing those names and entry IDs as well.
- Pre-change stores for joins with repeated or content-equal inputs, including
two slots bound to one source, use the old system-tag column names,
entry IDs, and table paths. Runs skip affected
rows in load-only mode and recompute them in normal mode. In a two-row
self-join saved on `main`, `job.run(load_only=True)` reports
`0 loaded, 2 not stored (skipped)`, and `out.as_source()` still returns
both original rows. Jobs written and replayed with the new layout load
their stored rows. This migration affects only pre-release stores.

### Fixed

- The pipeline, source, and name chains retain every occurrence of an input
to a commutative step. Capture preserves the same multiplicity when compiling
the graph. Sync and async execution feed each declared operand, even when
several positions share a graph predecessor. Cold and warm pipeline hashes
share one memo and handle deep pipelines without recursion.
- Capture and execution distinguish invocations whose input repeat counts differ.
8 changes: 3 additions & 5 deletions docs/dev/design_issues/ITL-1559-TC1.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ It also cannot follow a slot through a rebind while identifying the same computa
(ITL-1442, ITL-1427).

Step 1 computes separate structure, source and name chains. The new node hash is
available even when no source is bound. The graph and persistence still use their
existing hashes. ITL-1590 tracks the remaining structural dependency on source equality
when a commutative operator receives equal-structure inputs.
available even when no source is bound. ITL-1590 makes commutative structure
independent of source equality and retains every input occurrence.

The step 1 follow-up serializes binding and chain reads. Saved jobs retain the
existing file format. An unavailable built-in with one input uses its saved structure
Expand All @@ -21,8 +20,7 @@ symmetry to report the new chains. Schema-less polling sources report a node has
before their first batch, including when wrapped in a cache.

**Fix:** The execution protocols require both combined identity accessors. The
combined hashes raise when the legacy commutative grouping drops content-equal
arguments, including in downstream nodes. Recovering the lost order remains ITL-1590.
three chains retain content-equal argument occurrences. Row layout uses each input occurrence.
Source chains follow rebindings inside composite bindings and source wrappers.
Downstream chain reads never poll for a missing schema. Mixed nested input groups
use the pipeline hash's canonical ordering.
Expand Down
22 changes: 22 additions & 0 deletions docs/dev/design_issues/ITL-1590-CS1.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
## Pipeline identity

### CS1 — Commutative pipeline hashes lost equal input occurrences
**Status:** resolved
**Severity:** high
**Issue:** ITL-1590

Join's set of streams could collapse operands that compared equal by content.
The resulting pipeline hash depended on source equality and lost an argument.

**Fix:** Carry every argument occurrence through the pipeline, source and name
chains. A commutative structural preimage sorts its input hashes and keeps repeats.
The capture registry keeps repeated occurrences and computes keys bottom-up,
reusing upstream keys across captures. Compilation preserves each recorded
operand. The content hash includes the pipeline hash and source chain, so the
execution graph distinguishes invocations whose input repeat counts differ.

Both job orchestrators feed every declared operand position when equal upstreams
share a graph edge, including distinct slots bound to one source. The declaration
keeps both slots for serialization and rebinding. Join uses the same digest and
positions for table, row-channel and batch system tags. Pipeline hashing resolves cold
dependencies iteratively in the same memo used by the Join input sorter.
21 changes: 17 additions & 4 deletions docs/reference/hashing.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,8 +315,9 @@ combines the pipeline hash and the source chain for streams, invocations and nod
A root source's own content hash remains its address. Reading the source chain or
the combined content hash raises `UnboundSourceError` while a contributing slot is
unbound. Orcapod uses the combined hash for stored node rows and bound graph keys.
Unbound graph declarations use their node hashes. ITL-1590 tracks cases where the
existing pipeline hash depends on source equality within a commutative input tie.
Unbound graph declarations use their node hashes. Pipeline hashes and capture keys
include every commutative input occurrence (ITL-1590). Stored table paths use the
pipeline hash.
The saved job format does not carry input symmetry yet. A loaded built-in with one
input uses the saved pipeline hash and hashes that input's chains, even when
its operator implementation is unavailable. An unavailable operator with multiple
Expand Down Expand Up @@ -457,12 +458,13 @@ A record id is the row identifier (rule 8), built from row positions or key valu
|---|---|
| observer events (`node_hash`) | `core/nodes/function_node.py:FunctionJobNode.execute`, `core/nodes/function_node.py:FunctionJobNode.async_execute`, `core/nodes/function_node.py:FunctionJobNode._execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_load_only`, `core/nodes/function_node.py:FunctionJobNode._async_execute_cache_only`, `core/nodes/operator_node.py:OperatorJobNode.execute`, `core/nodes/operator_node.py:OperatorJobNode.async_execute`, `core/nodes/source_node.py:SourceNodeBase.execute`, `core/nodes/source_node.py:SourceNodeBase.async_execute` |
| hooks (`pod_hash`) | `core/function_pod.py:_FunctionPodBase._build_post_run_payload` |
| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile.<locals>.<lambda>`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations.<locals>.<genexpr>`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) |
| in-memory graph keys and sort keys | `pipeline/base.py:AbstractPipelineBase.compile`, `pipeline/base.py:AbstractPipelineBase.compile.<locals>.<lambda>`, `pipeline/base.py:AbstractPipelineBase._validate_invocation`, `pipeline/base.py:AbstractPipelineBase._input_graph_key`, `pipeline/base.py:AbstractPipelineBase.to_invocations`, `pipeline/base.py:AbstractPipelineBase.from_invocations`, `pipeline/job.py:PipelineJob.compile`, `pipeline/restrictions.py:sources_read` (the source identity a restriction is kept under, ITL-1218) |
| in-memory capture keys (ITL-1590) | `pipeline/pod_invocation.py:PodInvocation.capture_keys` |
| in-memory source registration keys | `pipeline/source_consistency.py:require_consistent_sources` |
| in-memory key for an in-flight function result (ITL-1101) | `core/cached_function_pod.py:CachedFunctionPod._async_process_once` |
| in-memory lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` |
| in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map.<locals>.order_key` |
| canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's identity holds its inputs as a frozenset | `core/operators/join.py:Join.order_input_streams.<locals>.<lambda>` |
| canonical input order (sort by digest). Inputs with equal pipeline hashes (developer decision, November 16, 2026, ITL-1154: kept as it is): system-tag column names follow the stable pipeline-hash sort; each row's values are sorted by (source id, record id) by `sort_system_tag_values`, so the result does not depend on argument order; the operator's structural identity counts all input positions | `core/operators/join.py:Join.order_input_streams.<locals>.<lambda>` |
| canonical input order for source and name chains (pipeline inputs' canonical JSON, then each chain's labelled hash within a tie) | `core/identity_chains.py:_pool_group` |
| in-memory identity and repr | `core/base.py:ContentIdentifiableBase.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__hash__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__eq__`, `hashing/semantic_hashing/content_identifiable_mixin.py:ContentIdentifiableMixin.__repr__` |
| comparing a stored hash with the computed one; comparing two schema hashes (bind, a stored read, a polled batch); error text | `core/nodes/source_node.py:SourceNodeBase._arrow_type_issue`, `core/sources/derived_source.py:DerivedSource._require_origin_types`, `core/sources/polling_source.py:PollingSource._require_declared_types`, `core/nodes/operator_node.py:OperatorJobNode._read_run_records`, `core/sources/source_proxy.py:SourceProxy.bind`, `core/data_function_proxy.py:DataFunctionProxy.bind`, `pipeline/job.py:PipelineJob.bind`, `errors.py:EphemeralResultMissingError.__init__` |
Expand Down Expand Up @@ -637,6 +639,7 @@ How containers expand (canonical JSON: sorted object keys, no whitespace, UTF-8)
| `tuple` | `{"__type__": "tuple", "items": [...]}` | order |
| `set` | `{"__type__": "set", "items": [...]}`, items sorted by their canonical JSON text | membership only; never iteration order or `PYTHONHASHSEED` (ITL-942: before v0.3, items were sorted by `str()`, so `{1, "1"}` hashed differently per process) |
| `frozenset` | `{"__type__": "frozenset", "items": [...]}`, items sorted as for `set` | membership, and that it is a `frozenset`: a frozenset and a set of the same items differ (ITL-1154) |
| `SymmetricGroup` | the historical `frozenset` encoding with all members sorted and repeats preserved | every commutative argument occurrence (ITL-1590) |
| `dict` with only `str` keys, none of them `"__type__"` | JSON object | keys and values, not insertion order |
| any other `dict` | `{"__type__": "dict", "items": [[key, value], ...]}`, pairs sorted by canonical JSON | key types: `{1: "x"}` and `{"1": "x"}` differ (ITL-942: before v0.3, keys went through `str()` and could collapse) |
| namedtuple | `{"__type__": "namedtuple", "name": ..., "fields": [[name, value], ...]}` | class name, field names and values, in declared order (ITL-942: before v0.3 fields were sorted by name, so `Point(x=1, y=2)` and a `Point` declared `(y, x)` holding `y=2, x=1` shared a hash) |
Expand Down Expand Up @@ -1478,6 +1481,16 @@ compares it with every other input's as it arrives. An input that sends no row o
row channel (`Join().async_execute(...)` called directly, outside a job) declares nothing
there; in a job the node knows its inputs' types, and both orchestrators refuse. Carrying the declared types over row channels is ITL-1527.

When calling an operator with raw row channels, pass one `stream.pipeline_hash()`
per input occurrence in `input_pipeline_hashes`. A Join with two or more operands
appends `::<pipeline_hash>:<canonical_position>` to each operand's system-tag
column names. Recorded jobs feed each declared operand in both orchestrators.
For example, a recorded `Join(a, a)` yields the same system-tag columns as
`Join(a, b)` when `a` and `b` have the same pipeline hash.
For a self-join written before both positions were retained, load-only replay
skips affected rows, a normal run recomputes them, and the saved node's
`as_source()` can still read the original rows.

Item fields that differ only in name or metadata between two inputs' declarations are not
refused: both paths give the first input's type (in the join's canonical input order).

Expand Down
71 changes: 60 additions & 11 deletions src/orcapod/core/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from contextlib import contextmanager
from contextvars import ContextVar
from datetime import datetime, timezone
from typing import Any
from typing import Any, ClassVar

import orcapod.contexts as contexts
from orcapod.config import DEFAULT_CONFIG, OrcapodConfig
Expand All @@ -17,6 +17,17 @@
_live_content_hashes: ContextVar[
dict[int, tuple[object, dict[str, ContentHash]]] | None
] = ContextVar("live_content_hashes", default=None)
_pipeline_hash_probe: ContextVar[object] = ContextVar(
"pipeline_hash_probe", default=None
)


class _UncachedPipelineHash(Exception):
"""Suspend a structural hash until its resolver's upstream is hashed."""

def __init__(self, element: PipelineElementBase) -> None:
super().__init__()
self.element = element


@contextmanager
Expand Down Expand Up @@ -131,6 +142,18 @@ class ContentIdentifiableBase(DataContextMixin, ABC):
Two content-identifiable objects are considered equal if their `identity_structure` returns the same value.
"""

_content_hash_generation: ClassVar[object] = object()

@staticmethod
def content_hash_generation() -> object:
"""Return the generation of state used in capture identities."""
return ContentIdentifiableBase._content_hash_generation

@staticmethod
def _invalidate_capture_keys() -> None:
"""Invalidate recorded-stream key memos after a lineage or hash change."""
ContentIdentifiableBase._content_hash_generation = object()

def __init__(
self,
data_context: str | contexts.DataContext | None = None,
Expand Down Expand Up @@ -240,6 +263,7 @@ def _invalidate_content_hash_cache(self) -> None:
accessing ``_content_hash_cache`` directly.
"""
self._content_hash_cache.clear()
self._invalidate_capture_keys()
self._cached_int_hash = None


Expand Down Expand Up @@ -287,7 +311,7 @@ def pipeline_hash(self, hasher=None) -> ContentHash:
Return the pipeline-level hash of this element, computed from
pipeline_identity_structure() and cached by hasher_id.

The hasher is used for the entire recursive computation — all nested
The hasher is used for the entire computation — all nested
objects are resolved using the same hasher, ensuring one consistent
context per hash computation.

Expand All @@ -298,17 +322,42 @@ def pipeline_hash(self, hasher=None) -> ContentHash:
if hasher is None:
hasher = self.data_context.semantic_hasher
cache_key = hasher.hasher_id
if cache_key not in self._pipeline_hash_cache:
from orcapod.protocols.hashing_protocols import PipelineElementProtocol

def pipeline_resolver(obj: Any) -> ContentHash:
if isinstance(obj, PipelineElementProtocol):
cached = self._pipeline_hash_cache.get(cache_key)
if cached is not None:
return cached
if _pipeline_hash_probe.get() is hasher:
raise _UncachedPipelineHash(self)

from orcapod.protocols.hashing_protocols import PipelineElementProtocol

def pipeline_resolver(obj: Any) -> ContentHash:
if isinstance(obj, PipelineElementProtocol):
token = _pipeline_hash_probe.set(hasher)
try:
return obj.pipeline_hash(hasher)
return obj.content_hash(hasher)
finally:
_pipeline_hash_probe.reset(token)
return obj.content_hash(hasher)

self._pipeline_hash_cache[cache_key] = hasher.hash_object(
self.pipeline_identity_structure(), resolver=pipeline_resolver
)
pending: list[tuple[PipelineElementBase, Any]] = [
(self, self.pipeline_identity_structure())
]
active = {id(self)}
while pending:
element, structure = pending[-1]
try:
digest = hasher.hash_object(structure, resolver=pipeline_resolver)
except _UncachedPipelineHash as request:
upstream = request.element
identity = id(upstream)
if identity in active:
raise ValueError("Cycle in pipeline hash dependencies") from None
pending.append((upstream, upstream.pipeline_identity_structure()))
active.add(identity)
else:
element._pipeline_hash_cache[cache_key] = digest
active.remove(id(element))
pending.pop()
return self._pipeline_hash_cache[cache_key]

def _invalidate_pipeline_hash_cache(self) -> None:
Expand Down
Loading
Loading