diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md index 49d50a6d5..6004cfe2e 100644 --- a/changelog.d/ITL-1559.md +++ b/changelog.d/ITL-1559.md @@ -32,6 +32,7 @@ - Identity accessors reuse a memoized raw Arrow stream's legacy digest and report an undefined identity when they would have to materialize a lazy upstream or hash Arrow rows. Plain derived sources, including cached bindings, report no source chain while an origin slot is unbound. - Polling source chain reads reuse a memoized legacy content hash from the polling source, a cache at any level of wrapping, or a bound job slot. A plain `DerivedSource` can use that digest without calling the polling implementation. A cold polling identity remains undefined. - Custom operators report an undefined identity for the new accessors without calling their argument symmetry method. +- The source and name chains hash a typed entry at every node, preserving the position of each contribution and the pairing of upstream branches. An unbound slot leaves its node hash available and raises an undefined-identity error when its source chain is requested. ### Known limitations diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md index f411df6b8..0487c0700 100644 --- a/docs/dev/design_issues/ITL-1559-TC1.md +++ b/docs/dev/design_issues/ITL-1559-TC1.md @@ -16,7 +16,7 @@ when a commutative operator receives equal-structure inputs. 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 -and that input's chains. An unavailable operator with multiple inputs needs its input +and hashes that input's chains. An unavailable operator with multiple inputs needs its input symmetry to report the new chains. Schema-less polling sources report a node hash before their first batch, including when wrapped in a cache. @@ -35,3 +35,7 @@ upstream rows or hash cold raw Arrow rows. Custom operators report that the new identities are undefined in this step without calling their symmetry method. Plain derived source chains, including cached bindings, are absent while an origin slot is unbound. + +Step 1b hashes a typed entry at every node in the source and name trees. Moving a +name contribution between otherwise identical steps now changes the node hash. +The source-chain accessor reports an undefined identity for unbound slots. diff --git a/docs/dev/specs/itl-1559-three-chain-hash.md b/docs/dev/specs/itl-1559-three-chain-hash.md index c0538f43c..1229b7898 100644 --- a/docs/dev/specs/itl-1559-three-chain-hash.md +++ b/docs/dev/specs/itl-1559-three-chain-hash.md @@ -36,23 +36,24 @@ the structural order is available without them. Each digest uses SHA-256 over the semantic hasher's canonical tuple, with nested hashes embedded with their labels. The labels are defined in `core/identity_chains.py`. +Step 1b retains the `_v1` suffixes because the chain algorithms have no released +or pinned values. | Digest | Label | Preimage | |---|---|---| -| Name leaf | `slot_name_v1` | `("slot", name)` | -| Multi-input source chain | `source_chain_v1` | Ordered upstream source chains | -| Multi-input name chain | `name_chain_v1` | Ordered upstream name chains | +| Source chain at each node | `source_chain_v1` | `(source_entry, [upstream source chains])` | +| Name chain at each node | `name_chain_v1` | `(name_entry, [upstream name chains])` | | Content hash at the switch | `content_hash_v1` | `(pipeline_hash, source_chain)` | | Node hash | `node_hash_v1` | `(pipeline_hash, name_chain)` | ### 2.2 Leaves and node labels -A slot contributes its declared Arrow schema to `pipeline_hash`, its bound source's -identity to `source_chain`, and its slot name to `name_chain`. PR 633 uses the -source's existing identity digest as the source-chain leaf. The declared slot schema -and the source's own schema can differ, for example when a non-nullable source is bound -to a nullable slot. A change in source schema or key columns can then distinguish two -readings of one dataset. +A slot contributes its declared Arrow schema to `pipeline_hash`, +`("source", bound_source_identity)` to the source chain, and `("slot", slot_name)` +to the name chain. The bound source identity is the existing digest used by PR 633. +The declared slot schema and the source's own schema can differ, for example when a +non-nullable source is bound to a nullable slot. A change in source schema or key +columns can then distinguish two readings of one dataset. | Leaf | Pipeline structure | Source-chain contribution | |---|---|---| @@ -67,10 +68,10 @@ readings of one dataset. | Unbound slot | Declared Arrow schema | Absent | **DQ2.** Outside a slot, the plain stream's name-chain leaf is the source's label. -A follow-up issue will re-evaluate this rule. PR 633 currently uses `RootSource.source_name` -for an uncaptured root source and an anonymous term for a raw Arrow stream. Its +A follow-up issue will re-evaluate this rule. Use `("slot", source_name)` for an +uncaptured root source and `("slot", None)` for a raw Arrow stream. The `slot_name_for()` helper also uses `source_name` for an implicit root slot. -The slot's name, once assigned, is the slot's leaf. +Once assigned, the slot's name is its contribution. A step's display label enters none of its chains. A step node has one label. Declaring the same computation again with a label replaces the earlier label. A declaration that @@ -82,25 +83,42 @@ Slot names are separate from step labels. are numbered in `node_hash` order. Add a sentence documenting that rule. An unbound slot and its downstream nodes have a name chain and a node hash. -`source_chain()` returns `None`. Asking for the combined content hash raises -`UnboundSourceError` naming the unbound slots. A run leaves those branches out. +Asking for the source chain or combined content hash raises `UnboundSourceError`. +The error names the unbound slots where available. A run leaves those branches out. The saved file can represent the absent current content hash as `null`. -### 2.3 One walk and input order +### 2.3 One walk, typed entries, and input order -Compute the chains together in one graph walk. At a single-input node, both upstream -chains pass through unchanged. At a multi-input node, hash the upstream chains in the -order fixed by the pipeline hash. Keep every occurrence, including repeats. +**D34 (a1), closed.** Three trees mirror the pipeline. Each node contributes its +computation role and schema to the structural chain, its sourcing information to the +source chain, and its name information to the name chain. At every node, hash each +auxiliary chain's entry with its own list of upstream chain values, including at a +single-input node. A diamond unfolds as a tree with the same shared node value at +each occurrence. Compute the chains in one graph walk, memoizing each node's chain +values so the work scales with nodes and edges rather than paths. Combine the +pipeline hash with an auxiliary chain only when computing the corresponding final +hash. Step 1b uses the existing structural hash. + +**D36, closed.** An entry is typed. `None` encodes a semantic null when a node +contributes nothing. A contribution uses a tagged pair. The leaf entries use +`"slot"` and `"source"`. A slot named `""` contributes `("slot", "")`, which +encodes differently from a semantic null. A node with an existing name +contribution point uses `("name", name)` when given a name. A given name must be +nonempty. The step 1 implementation has no inner-node name contributions. A +future tag can add a new entry kind without affecting existing hashes. + +Use the order fixed by the pipeline hash. Keep every occurrence, including repeats. | Producer | Input order | |---|---| -| Unary operators, function pods and side-effect pods | Pass through their one input. A function pod over several streams has a separate join node before it | +| Unary operators, function pods and side-effect pods | List containing the single input's chain value. A function pod over several streams has a separate join node before it | | Ordered operators, including `SemiJoin` and `MergeJoin` | Argument order | | Commutative operators, including `Join` and `Rejoin` | Canonical structural order. Within a group of equal pipeline hashes, sort the source chains by their own values and the name chains by theirs | -For nested symmetry, each group uses the rule for its own kind. PR 633 obtains the -grouping from `argument_symmetry` via `encode_input_symmetry()`, retains input -positions, and sorts structural keys in `_pool_group()` by the canonical JSON of +For nested symmetry, each group uses the rule for its own kind and hashes its list +with a null entry. The walk obtains the grouping from `argument_symmetry` via +`encode_input_symmetry()`, retains input positions, and sorts structural keys in +`_pool_group()` by the canonical JSON of the nested pipeline hashes. Inside a structural tie the implementation sorts each chain by its labelled hash value. In step 1 the old pipeline hash remains in use, so a legacy set that collapses equal inputs makes the combined hashes undefined. @@ -112,13 +130,10 @@ column causes both operators to refuse the pair. A shared data-tag acts as a joi `MergeJoin` uses the argument index in system-tag names. `Rejoin` retains the input system-tag names. -A node may contribute its own term to either chain. No node does so today. -`_identity_terms()` supplies those optional terms in PR 633. If supplied, the term -is hashed with the pooled value, including for a single input. Anything that -distinguishes nodes that can coexist in one graph must be represented in -`pipeline_hash` or `name_chain`. A term only in `source_chain` must behave like -a binding, with one value per node at a time and the freedom to change without re-keying -the graph. +Anything that distinguishes nodes that can coexist in one graph belongs in +`pipeline_hash` or `name_chain`. An entry that contributes only to the source chain +behaves like a binding. It has one value per node at a time and can change without +re-keying the graph. ### 2.4 Step 1 limits in PR 633 @@ -133,9 +148,9 @@ the graph. its pipeline hash require the schema. Source-chain access reuses a warm source digest and refuses to call the polling implementation to obtain a missing one. - A loaded built-in operator with one input can use its saved pipeline hash and - pass through both chains even when the implementation is unavailable. An - unavailable operator with several inputs needs its input symmetry to reconstruct - the chains. The step 1 saved form does not carry that symmetry. Custom operators + hash each input chain with a null entry even when the implementation is + unavailable. An unavailable operator with several inputs needs its input symmetry + to reconstruct the chains. The step 1 saved form does not carry that symmetry. Custom operators also leave the new accessors undefined in step 1. - Transparent wrappers and row builds representing an existing stream delegate to the underlying stream for the chains. A plain stream and the job node compiled from @@ -225,8 +240,8 @@ identities, and `f`, `g` and `h` be pods. | Graph | Chain and hash result | |---|---| -| `x -> f -> g`, with `x` bound to `A` | All three nodes share the source leaf for `A` and name leaf for `x`. The pipeline hash distinguishes each step | -| Diamond `x -> (f, h) -> Rejoin` | The join hashes both occurrences of the source leaf for `A` and both occurrences of the name leaf for `x`, in the order of the branches' pipeline hashes | +| `x -> f -> g`, with `x` bound to `A` | At `x`, the source and name chains hash `("source", A)` and `("slot", "x")`, respectively, each with an empty upstream list. For each chain, `f` hashes a null entry with a list containing `x`'s chain value, then `g` hashes a null entry with a list containing `f`'s chain value. Each node combines its own pipeline hash with its name chain for the node hash and with its source chain for the content hash at the switch | +| Diamond `x -> (f, h) -> Rejoin`, with `x` bound to `A` | For each chain, `f` and `h` each hash a null entry with a list containing `x`'s chain value. `Rejoin` hashes its null entry with the list of immediate branch values in canonical pipeline hash order, sorting structural ties by that chain's values. The list keeps both occurrences even when the branch values are equal | | `x -> f -> g` and `y -> f -> g`, both bound to `A` | Each pair of corresponding steps has equal pipeline and content hashes but distinct node hashes. Each pair shares stored rows | | Same branches, `x` bound to `A` and `y` bound to `B` | Each pair still shares a pipeline hash and table path. Their content hashes distinguish the rows. Their node hashes are the same as before | | `Join(x, y)` with equal structural inputs, `x` bound to `B`, `y` to `A` | The pipeline hash includes two equal input hashes. If the source hashes sort as `A, B` and the name hashes as `x, y`, the source chain orders `y` first and the name chain orders `x` first. Swapping the two bindings yields the same pair of chains | @@ -449,6 +464,7 @@ the baseline for the final comparison. |---|---|---| | spec | 632 | This document | | 1 | 633 | Compute `source_chain`, `name_chain` and `node_hash` alongside the old hashes. Graph and storage consumers continue to use the old values. Saved files are byte-identical | +| 1b | 652 | Hash a typed source and name entry at every node and preserve upstream pairings, using the existing structural hash and saved-job format | | 2a | 634 | Give a context-taking function pod its own pipeline hash | | 2b | To be written, on PR 587's work | Compute a commutative operator's pipeline hash from the input list, retaining equal inputs. Fix the tied-join faults in D32 | | 3 | To be written | Key graph state, `job.nodes`, edges and restrictions by `node_hash`. Number steps with the same automatic name by node hash and document the rule | @@ -456,6 +472,8 @@ the baseline for the final comparison. | 5, the switch | To be written, after PR 609 | Switch `content_hash` to `H(pipeline_hash, source_chain)` for storage and record ids, and refresh the content hash after binding. Requires approval of the exact list of golden entries that move | | 6 | To be written | Lift both two-slot refusals. Equal-content nodes write if missing | +**D35, closed.** Land step 1b before step 3. + The bind refresh follows the source chain at every depth, including in a loaded job (ITL-1427). Using stable graph keys also addresses the slot that becomes unreachable in the run graph after a bind (ITL-1204). The positioned inputs from PR 587 supply the @@ -471,10 +489,15 @@ one source (ITL-1554). - Through the public APIs, compare a plain stream, its invocation and its job node. Cover pipelines built before and inside capture, input column permutations, and the sync and async paths. Use the ITL-1470 test from PR 579 where appropriate. -- Verify single-input pass-through and argument order for `SemiJoin` and - `MergeJoin`. Verify canonical structural order and repeat preservation in diamonds - and in two- and three-input commutative operators. Verify independent tie sorting - with the source and slot names ordered differently. +- Verify that single-input nodes hash their own entries. Move a name from B to C + in A → B → C, and add a name to one of two C nodes that share B. In both cases + the C nodes and their D successors have distinct name chains and node hashes. +- Verify argument order for `SemiJoin` and `MergeJoin`. Verify canonical structural + order and repeat preservation in two- and three-input commutative operators. + Verify independent tie sorting with the source and slot names ordered differently. + Swapping sources across two inner joins changes the outer source chain and content + hash. Swapping source bindings at one structural tie retains the content hash. + Count one source and one name hash computation per node through a diamond. - For two all-data-tag inputs of equal pipeline hash, verify identical pipeline hashes whether the two slots hold the same object, equal objects, or distinct sources. Permuting the same two bindings gives the same chains, table, and @@ -484,7 +507,7 @@ one source (ITL-1554). pipeline hashes and graph keys. Verify the additional delivery after upgrading a live job with a prior store, followed by normal completion lookup (D29). - Verify that an unbound slot and its branch have node hashes, and that a request - for their live content hash names the unbound slots in its error. + for their source chain or live content hash names the unbound slots in its error. - Declare one computation with `r1`, then `r2`, then without a label. Verify a single node labelled `r2` in `job.nodes`, the run summary, and a saved and loaded job. Reverse the two labels and expect `r1`. Check that the hashes are independent of @@ -519,10 +542,10 @@ one source (ITL-1554). - **Context-taking pods (D29).** Refusing two pods of the same URI in a graph or adding the context argument to both auxiliary chains would distinguish those operations. Step 2a puts the distinction in pipeline structure. -- **Pooling.** A flat list of leaves grows to one item per root-to-node path. - Twenty consecutive diamonds would give over a million entries. Hashing the - upstream values keeps each pooled result fixed-size while the pipeline hash fixes - the input structure. +- **Flat lists of leaves.** A flat list grows to one item per root-to-node path. + Twenty consecutive diamonds would give over a million entries. Hashing entries + and upstream values preserves each contribution's position and keeps each node's + value fixed-size. - **Leaf hashes and labels.** Alternatives included omitting schema from the source leaf and reusing the general `semantic_v1` label for the new hashes. Step 1 reuses the source's identity preimage and gives the new digests distinct labels. @@ -556,7 +579,7 @@ one source (ITL-1554). ### 12.1 Rebinding and source attribution A bind invalidates the source-chain and content-hash results downstream of the -slot. The graph keeps the same node hashes and the pipeline and name terms stay +slot. The graph keeps the same node hashes and the pipeline and name chains stay the same. At a commutative structural tie, the independently sorted chains cannot recover which slot held which source. Store that association per slot in saved jobs and any future membership table. diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md index 576773423..8bcae8294 100644 --- a/docs/reference/hashing.md +++ b/docs/reference/hashing.md @@ -93,9 +93,8 @@ Hash labels: | `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` | +| `source_chain_v1` | SHA-256 of the canonical tuple `(entry, [upstream source chains])` | `SOURCE_CHAIN_HASH_LABEL`, `core/identity_chains.py` | +| `name_chain_v1` | SHA-256 of the canonical tuple `(entry, [upstream name chains])` | `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 | `SHA256_ALGORITHM`, `hashing/hash_utils.py` | @@ -299,22 +298,26 @@ 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 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. 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. +structure. Each node hashes its typed source or name entry with the list of upstream +values for that chain. A slot uses `("source", bound_source_identity)` and +`("slot", slot_name)` as its entries. An uncaptured root source uses its source name, +and a raw stream uses `("slot", None)`. An entry of `None` marks a step with no local +contribution. Display labels do not participate. + +Ordered groups use argument order. Commutative groups use the pipeline hash's canonical +order, including when a group contains other groups. Each chain sorts its own values +within a structural tie. Repeated inputs contribute at every position, and a shared +upstream is hashed once per chain. `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 +hash combines the pipeline hash and the source chain. Reading either the source chain +or the chain-based content hash raises `UnboundSourceError` while a 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. The saved job format does not carry input symmetry yet. A loaded built-in with one -input uses the saved pipeline hash and passes through that input's chains, even when +input uses the saved pipeline hash and hashes that input's chains, even when its operator implementation is unavailable. An unavailable operator with multiple inputs needs its input symmetry and reports an undefined identity for either chain or combined hash. @@ -337,7 +340,7 @@ schema. The legacy symmetry check uses the inputs' content digests to form a set. The step 1 accessors report an undefined identity when that check needs the polling implementation. -A plain derived source, including one wrapped in a cache, has no source chain while +A plain derived source, including one wrapped in a cache, reports an undefined source chain while a contributing slot of its origin is unbound. Chain accessors report an undefined identity when they would have to build a lazy upstream from rows or hash a raw Arrow stream's rows. A raw Arrow stream can report its node hash from its schema @@ -369,7 +372,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`, `core/sources/polling_source.py:PollingSource._identity_node_pipeline_hash` | +| three-chain hashes | a typed entry with its list 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 construction and combining, or returned by an identity accessor | `core/identity_chains.py:_hash`, `core/identity_chains.py:_pool_group`, `core/identity_chains.py:IdentityChainsMixin._identity_hash`, `core/identity_chains.py:IdentityChainsMixin._identity_chain_hash`, `core/identity_chains.py:IdentityChainsMixin._compute_identity_chains`, `core/identity_chains.py:IdentityChainsMixin._compute_identity_chains..hash_chain`, `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 | SHA-256 of the bytes, label `sha256`. Hashers, cache writes, and data context loading reject other algorithms. Direct cache lookups for other labels miss (ITL-1155). Custom file hasher results are verified against SHA-256 of the file bytes. | `File` value hash | `hashing/hash_utils.py:hash_file`, `hashing/semantic_hashing/builtin_handlers.py:FileHandler.handle`, `hashing/file_hashers.py:verified_file_hash`, `hashing/file_hashers.py:canonical_file_hash`, `hashing/file_hashers.py:_validated_file_digest`, `hashing/hash_cachers.py:InMemoryHashCacher.put`, `hashing/hash_cachers.py:SqliteHashCacher.get`, `hashing/hash_cachers.py:SqliteHashCacher.put`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.get`, `hashing/postgres_hash_cacher.py:PostgresHashCacher.put` | | directory hasher | a directory tree | Merkle tree of SHA-256 entries, `directory_v1`; file leaves taken with their label. The handler verifies custom directory hashes against the library Merkle procedure. | `Directory` value hash | `hashing/directory_hashers.py:BasicDirectoryHasher.hash_directory`, `hashing/directory_hashers.py:_hash_dir`, `hashing/semantic_hashing/builtin_handlers.py:DirectoryHandler.handle`, `hashing/directory_hashers.py:verified_directory_hash`, `hashing/directory_hashers.py:canonical_directory_hash` | diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py index 577a7c517..122f15f28 100644 --- a/src/orcapod/core/identity_chains.py +++ b/src/orcapod/core/identity_chains.py @@ -26,7 +26,6 @@ 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" @@ -148,6 +147,8 @@ class _SymmetricInputs: InputSymmetry = int | list["InputSymmetry"] | _SymmetricInputs +_ChainEntry = tuple[str, object] | None +_ChainHasher = Callable[[str, _ChainEntry, tuple[ContentHash, ...]], ContentHash] def encode_input_symmetry( @@ -244,29 +245,14 @@ class _GroupChains: names: ContentHash -def _pool( - 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_term(label, inputs) - if own_term is None: - return pooled - # 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( group: InputSymmetry, inputs: tuple[_GroupChains, ...], - hash_term: Callable[[str, tuple[object, ...]], ContentHash], - source_term: object | None = None, - name_term: object | None = None, + hash_chain: _ChainHasher, + source_entry: _ChainEntry = None, + name_entry: _ChainEntry = None, ) -> _GroupChains: - """Pool in structural order, breaking structural ties separately per chain.""" + """Hash children in structural order, with null entries for nested groups.""" from orcapod.hashing.semantic_hashing.semantic_hasher import canonical_json if isinstance(group, int): @@ -274,7 +260,7 @@ def _pool_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] + children = [_pool_group(child, inputs, hash_chain) for child in group_children] if symmetric: children.sort(key=lambda child: child.structure_key) structure = None @@ -304,10 +290,10 @@ def _pool_group( return _GroupChains( structure, canonical_json(structure) if structure is not None else "", - _pool(hash_term, SOURCE_CHAIN_HASH_LABEL, tuple(sources), source_term) + hash_chain(SOURCE_CHAIN_HASH_LABEL, source_entry, tuple(sources)) if len(sources) == len(children) else None, - _pool(hash_term, NAME_CHAIN_HASH_LABEL, tuple(names), name_term), + hash_chain(NAME_CHAIN_HASH_LABEL, name_entry, tuple(names)), ) @@ -363,8 +349,14 @@ def _invalidate_identity_chains(self, *, names: bool = False) -> None: _ = 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.""" + def _identity_hash( + self, + label: str, + key_parts: tuple[object, ...], + *, + preimage: tuple[object, ...] | None = None, + ) -> ContentHash: + """Reuse hashes 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 = {} @@ -373,12 +365,22 @@ def _identity_hash(self, label: str, preimage: tuple[object, ...]) -> ContentHas if self._identity_name_hashes is None: self._identity_name_hashes = {} hashes = self._identity_name_hashes - key = (label, preimage) + key = (label, key_parts) cached = hashes.get(key) if cached is None: - cached = hashes[key] = _hash(label, preimage) + cached = hashes[key] = _hash( + label, key_parts if preimage is None else preimage + ) return cached + def _identity_chain_hash( + self, label: str, entry: _ChainEntry, children: tuple[ContentHash, ...] + ) -> ContentHash: + """Hash the entry and ordered children of a node or symmetry group.""" + return self._identity_hash( + label, (entry, children), preimage=(entry, list(children)) + ) + def _identity_pipeline_hash(self, hasher: SemanticHasherProtocol) -> ContentHash: """Use the legacy structure, evaluated only when a consumer needs it.""" return self.pipeline_hash(hasher) @@ -414,8 +416,8 @@ def _identity_leaf( """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.""" + def _identity_entries(self) -> tuple[_ChainEntry, _ChainEntry]: + """Return this element's tagged source and name entries, if any.""" return None, None def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: @@ -435,44 +437,45 @@ def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: return self._identity_cache[key] def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains: - """Compute this element's chains from its leaf or upstream terms.""" + """Compute this element's chains from its entries and upstream chains.""" leaf = self._identity_leaf(walk) if leaf is not None: name, source = leaf return IdentityChains( self._identity_pipeline_hash, - source, - self._identity_hash(SLOT_NAME_HASH_LABEL, ("slot", name)), + self._identity_chain_hash( + SOURCE_CHAIN_HASH_LABEL, ("source", source), () + ) + if source is not None + else None, + self._identity_chain_hash(NAME_CHAIN_HASH_LABEL, ("slot", name), ()), frozenset((name,)) if walk.include_sources and name is not None and source is None else frozenset(), self._identity_node_pipeline_hash, + leaf_source=source, ) inputs = self._identity_inputs() - source_term, name_term = self._identity_terms() + source_entry, name_entry = self._identity_entries() + if ( + name_entry is not None + and name_entry[0] == "name" + and isinstance(name_entry[1], str) + and not name_entry[1] + ): + raise ValueError("A node name cannot be empty.") + + def hash_chain( + label: str, entry: _ChainEntry, children: tuple[ContentHash, ...] + ) -> ContentHash: + if entry is None: + return self._identity_chain_hash(label, entry, children) + # Extension payloads can be unhashable or compare equal in Python while + # encoding differently. The node memo caches the result of this walk. + return _hash(label, (entry, list(children))) + upstreams = tuple(walk.visit(stream) for stream in inputs) - if len(upstreams) == 1: - upstream = upstreams[0] - return IdentityChains( - 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( - self._identity_hash, - NAME_CHAIN_HASH_LABEL, - (upstream.names,), - name_term, - ), - upstream.unbound_slots, - collapsed_input_symmetry=upstream.collapsed_input_symmetry, - ) # Symmetric groups use structural ordering. Occurrences keep repeats. group, collapsed = encode_input_symmetry(inputs, self._identity_symmetry) @@ -500,7 +503,7 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains ) ) pooled = _pool_group( - group, tuple(children), self._identity_hash, source_term, name_term + group, tuple(children), hash_chain, source_entry, name_entry ) return IdentityChains( self._identity_pipeline_hash, @@ -513,14 +516,25 @@ def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains or any(upstream.collapsed_input_symmetry for upstream in upstreams), ) - def source_chain(self) -> ContentHash | None: - """Return the source chain, absent if any contributing slot is unbound.""" + def source_chain(self) -> ContentHash: + """Return the source chain. + + Raises: + UnboundSourceError: If any contributing source slot is unbound. + """ with self._identity_lock, _identity_read(): - return ( - IdentityWalk(self._identity_hasher, include_sources=True) - .visit(self) - .sources + chains = IdentityWalk(self._identity_hasher, include_sources=True).visit( + self ) + if chains.sources is None: + names = ", ".join(repr(name) for name in sorted(chains.unbound_slots)) + detail = ( + f"source slots {names} are unbound" + if names + else "an upstream source is unbound" + ) + raise UnboundSourceError(f"Source chain is undefined because {detail}.") + return chains.sources def name_chain(self) -> ContentHash: """Return the chain of source-slot names. diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py index 856182709..903dd3fd0 100644 --- a/src/orcapod/core/nodes/source_node.py +++ b/src/orcapod/core/nodes/source_node.py @@ -771,9 +771,9 @@ def _identity_leaf( return self.name, None if isinstance(bound, RootSource): return self.name, walk.binding_hash(bound) - sources = walk.visit(bound).sources - if sources is None or isinstance(bound, SourceNodeBase): - return self.name, sources + chains = walk.visit(bound) + if chains.sources is None or isinstance(bound, SourceNodeBase): + return self.name, chains.leaf_source return self.name, walk.binding_hash(bound) def _bound_stream(self) -> "StreamProtocol | None": diff --git a/src/orcapod/core/operators/static_output_pod.py b/src/orcapod/core/operators/static_output_pod.py index 184c2fba5..15e109357 100644 --- a/src/orcapod/core/operators/static_output_pod.py +++ b/src/orcapod/core/operators/static_output_pod.py @@ -1519,7 +1519,7 @@ 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: + def source_chain(self) -> ContentHash: """Return the underlying node's source chain.""" return self._node.source_chain() diff --git a/src/orcapod/protocols/hashing_protocols.py b/src/orcapod/protocols/hashing_protocols.py index a728c9a9e..c3f5eb6e3 100644 --- a/src/orcapod/protocols/hashing_protocols.py +++ b/src/orcapod/protocols/hashing_protocols.py @@ -17,7 +17,7 @@ class IdentityChains: """The three chains of one element. An unbound slot leaves sources absent. Collapsed symmetry invalidates the - combined hashes. + combined hashes. A source leaf also holds its binding digest before chain hashing. """ pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] @@ -26,6 +26,7 @@ class IdentityChains: unbound_slots: frozenset[str] = frozenset() node_pipeline_hash: Callable[[SemanticHasherProtocol], ContentHash] | None = None collapsed_input_symmetry: bool = False + leaf_source: ContentHash | None = None class IdentityWalkProtocol(Protocol): @@ -46,8 +47,8 @@ def binding_hash(self, stream: ContentIdentifiableProtocol) -> ContentHash | Non 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 source_chain(self) -> ContentHash: + """Return the source chain or raise if a contributing slot is unbound.""" ... def name_chain(self) -> ContentHash: diff --git a/src/orcapod/protocols/node_protocols.py b/src/orcapod/protocols/node_protocols.py index 60bb7b3a7..fb0da65e6 100644 --- a/src/orcapod/protocols/node_protocols.py +++ b/src/orcapod/protocols/node_protocols.py @@ -34,8 +34,8 @@ 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 source_chain(self) -> ContentHash: + """Return the source chain or raise if a contributing slot is unbound.""" ... def name_chain(self) -> ContentHash: diff --git a/tests/test_channels/test_polling_source.py b/tests/test_channels/test_polling_source.py index 837e586d2..499b96499 100644 --- a/tests/test_channels/test_polling_source.py +++ b/tests/test_channels/test_polling_source.py @@ -11,11 +11,13 @@ import pytest from orcapod.channels import Channel +from orcapod.core.identity_chains import SOURCE_CHAIN_HASH_LABEL from orcapod.core.nodes.source_node import SourceJobNode from orcapod.core.sources import ArrowTableSource from orcapod.core.sources.polling_source import PollingSource from orcapod.core.streams.arrow_table_stream import ArrowTableStream from orcapod.errors import CursorInvalidatedError +from orcapod.hashing.semantic_hashing.semantic_hasher import SemanticAwarePythonHasher from orcapod.protocols.core_protocols.sources import DynamicSourceProtocol from orcapod.types import ContentHash, Cursor, PollingConfig, Schema @@ -1823,6 +1825,13 @@ def test_key_column_order_counts(self): ) +def _source_leaf(identity: ContentHash) -> ContentHash: + """Compute a leaf's chain from its legacy polling or derived identity.""" + return SemanticAwarePythonHasher(hasher_id=SOURCE_CHAIN_HASH_LABEL).hash_object( + (("source", identity), []) + ) + + @pytest.mark.parametrize("cached", [False, True]) def test_polling_chain_reads_do_not_call_user_code( monkeypatch: pytest.MonkeyPatch, cached: bool @@ -1854,7 +1863,7 @@ def unexpected_callback(*_args: object, **_kwargs: object) -> None: with monkeypatch.context() as guard: for method in ("identity", "schema", "poll", "fetch"): guard.setattr(impl, method, unexpected_callback) - assert stream.source_chain() == expected + assert stream.source_chain() == _source_leaf(expected) assert stream._chain_content_hash() @@ -1934,7 +1943,7 @@ def unexpected_callback(*_args: object, **_kwargs: object) -> None: for method in ("identity", "schema", "poll", "fetch"): monkeypatch.setattr(impl, method, unexpected_callback) - assert cached.source_chain() == expected + assert cached.source_chain() == _source_leaf(expected) assert cached._chain_content_hash() == warm_delegate._chain_content_hash() @@ -1987,18 +1996,18 @@ def unexpected_callback(*_args: object, **_kwargs: object) -> None: for accessor in accessors: with pytest.raises(ValueError, match="undefined.*polling.*identity"): _ = accessor() - assert tagged.source_chain() == tagged.content_hash() + assert tagged.source_chain() == _source_leaf(tagged.content_hash()) assert tagged._chain_content_hash() expected_slot = slot.content_hash() expected_derived = derived.content_hash() - assert expected_derived != before + assert _source_leaf(expected_derived) != before for method in ("identity", "schema", "poll", "fetch"): monkeypatch.setattr(impl, method, unexpected_callback) - assert slot.source_chain() == expected_slot + assert slot.source_chain() == _source_leaf(expected_slot) assert slot._chain_content_hash() assert derived.content_hash() == expected_derived - assert derived.source_chain() == expected_derived + assert derived.source_chain() == _source_leaf(expected_derived) assert derived._chain_content_hash() @@ -2015,7 +2024,7 @@ def unexpected_poll() -> None: expected = source.content_hash() monkeypatch.setattr(source, "_sync_poll_and_commit", unexpected_poll) - assert source.source_chain() == expected + assert source.source_chain() == _source_leaf(expected) name_chain = source.name_chain() node_hash = source.node_hash() assert isinstance(node_hash, ContentHash) diff --git a/tests/test_hashing/test_hash_grammar.py b/tests/test_hashing/test_hash_grammar.py index 6cf5d3688..d2c5f571f 100644 --- a/tests/test_hashing/test_hash_grammar.py +++ b/tests/test_hashing/test_hash_grammar.py @@ -43,7 +43,6 @@ "torch_tensor_v1", "group_v1", "batch_v1", - "slot_name_v1", "source_chain_v1", "name_chain_v1", "content_hash_v1", diff --git a/tests/test_hashing/test_hash_label_rule.py b/tests/test_hashing/test_hash_label_rule.py index 655fe16e5..455dbdedb 100644 --- a/tests/test_hashing/test_hash_label_rule.py +++ b/tests/test_hashing/test_hash_label_rule.py @@ -821,7 +821,6 @@ 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", diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py index 2545f1cc5..334e3e188 100644 --- a/tests/test_hashing/test_identity_chains.py +++ b/tests/test_hashing/test_identity_chains.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +from collections import Counter from itertools import permutations from pathlib import Path from random import Random @@ -15,7 +16,6 @@ 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 @@ -65,6 +65,18 @@ def _source( return DictSource(rows, tag_columns=tags, tag_only_columns=True, source_id=name) +def _chain(label: str, entry: object, *children: ContentHash) -> ContentHash: + """Compute the specified node preimage independently of the identity walk.""" + return SemanticAwarePythonHasher(hasher_id=label).hash_object( + (entry, list(children)) + ) + + +def _source_leaf(identity: ContentHash) -> ContentHash: + """Compute a leaf's source chain from its legacy source identity.""" + return _chain(SOURCE_CHAIN_HASH_LABEL, ("source", identity)) + + def _hashes(element: IdentityChainProtocol) -> tuple[object, object]: """Read both combined hashes before the content hash switch.""" return element._chain_content_hash(), element.node_hash() @@ -104,33 +116,165 @@ def test_chain_agrees_across_plain_recorded_and_job_forms( 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 source.source_chain() == _source_leaf(source.content_hash()) + assert source.name_chain() == _chain(NAME_CHAIN_HASH_LABEL, ("slot", "reading")) + for label, leaf, intermediate, last in ( + ( + SOURCE_CHAIN_HASH_LABEL, + source.source_chain(), + first.source_chain(), + plain.source_chain(), + ), + ( + NAME_CHAIN_HASH_LABEL, + source.name_chain(), + first.name_chain(), + plain.name_chain(), + ), + ): + assert intermediate == _chain(label, None, leaf) + assert last == _chain(label, None, intermediate) + assert len({leaf, intermediate, last}) == 3 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]) +def test_name_entry_belongs_to_the_node_that_contributes_it( + reverse: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """Moving or adding a name at one step distinguishes all downstream nodes.""" + from orcapod.operators import SelectDataColumns + + source = _source("a", reverse) + columns = ["y", "x"] if reverse else ["x", "y"] + b = SelectDataColumns(columns)(source) + named_b = SelectDataColumns(columns)(source) + c = add.pod(b) + named_c = add.pod(b) + c_after_name = add.pod(named_b) + + # Test-only contribution points. Production steps have labels and no names. + for named_node in (named_b, named_c): + monkeypatch.setattr( + named_node, "_identity_entries", lambda: (None, ("name", "x")) + ) + for unnamed, named in ((b, named_b), (c, named_c)): + assert unnamed.name_chain() != named.name_chain() + assert unnamed._chain_content_hash() == named._chain_content_hash() + assert named_c.name_chain() == _chain( + NAME_CHAIN_HASH_LABEL, ("name", "x"), b.name_chain() + ) + + # The collision moved x from B to C. The third case leaves C unnamed on B. + for branches in ( + (c_after_name, named_c, c), + tuple(double.pod(step) for step in (c_after_name, named_c, c)), + ): + assert len({step.pipeline_hash() for step in branches}) == 1 + assert len({step._chain_content_hash() for step in branches}) == 1 + assert len({step.name_chain() for step in branches}) == 3 + assert len({step.node_hash() for step in branches}) == 3 + + +def test_empty_slot_name_can_run_and_save(tmp_path: Path) -> None: + """An explicit empty slot name remains bindable and has a tagged entry.""" + source = _source("a", False) + slot = SourceNode.from_stream(source, name="") + assert slot.name == "" + slot_chain = slot.name_chain() + assert slot_chain == _chain(NAME_CHAIN_HASH_LABEL, ("slot", "")) + assert slot_chain != _chain(NAME_CHAIN_HASH_LABEL, None) + + pipeline = Pipeline(name="empty_slot") + with pipeline: + add.pod(slot, label="add") + job = PipelineJob.from_pipeline( + pipeline, database=InMemoryArrowDatabase(), sources={"": source} + ) + job.run() + node = job.nodes["add"] + assert sorted(node.as_table()["total"].to_pylist()) == [12, 24] + assert node.name_chain() == _chain(NAME_CHAIN_HASH_LABEL, None, slot_chain) + assert node.name_chain() != slot_chain + path = tmp_path / "empty_slot.json" + job.save(path) + assert path.is_file() + + +def test_empty_inner_name_is_refused(monkeypatch: pytest.MonkeyPatch) -> None: + """An inner node's explicit name contribution must be nonempty.""" + source = _source("a", False) + node = add.pod(source) + monkeypatch.setattr(node, "_identity_entries", lambda: (None, ("name", ""))) + with pytest.raises(ValueError, match="node name cannot be empty"): + _ = node.name_chain() + + @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"]) +def test_diamond_pools_both_occurrences( + reverse: bool, run_async: bool, monkeypatch: pytest.MonkeyPatch +) -> None: + """A shared intermediate is hashed once, with one chain value on both paths.""" + from orcapod.core import identity_chains + + source = DictSource( + [ + dict(reversed(tuple(row.items()))) if reverse else row + for row in ( + {"region": "north", "item": 1, "x": 5, "y": 7, "u": 11, "v": 13}, + {"region": "south", "item": 2, "x": 17, "y": 19, "u": 23, "v": 29}, + ) + ], + tag_columns=["item", "region"] if reverse else ["region", "item"], + tag_only_columns=True, + source_id="diamond", + ) + all_data = ["x", "y", "u", "v"] + left, right = ["x", "y"], ["u", "v"] + if reverse: + all_data.reverse() + left.reverse() + right.reverse() + shared = source.select_data_columns(all_data) + x = shared.select_data_columns(left) + y = shared.select_data_columns(right) diamond = Rejoin()(x, y) + + original_hash = identity_chains._hash # pyright: ignore[reportPrivateUsage] # Count chain digests. + counts: Counter[str] = Counter() + + def count_hash(label: str, preimage: tuple[object, ...]) -> ContentHash: + counts[label] += 1 + return original_hash(label, preimage) + + with monkeypatch.context() as guard: + guard.setattr(identity_chains, "_hash", count_hash) + hashes = _hashes(diamond) + assert counts == { + SOURCE_CHAIN_HASH_LABEL: 5, + NAME_CHAIN_HASH_LABEL: 5, + identity_chains.CONTENT_HASH_LABEL: 1, + NODE_HASH_LABEL: 1, + } + counts.clear() + assert _hashes(diamond) == hashes + assert not counts + assert diamond.source_chain() != source.source_chain() assert diamond.name_chain() != source.name_chain() - assert _hashes(diamond) == _hashes(Rejoin()(y, x)) + assert hashes == _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") + base = source.select_data_columns(all_data, label="shared") + x_node = base.select_data_columns(left, label="left") + y_node = base.select_data_columns(right, label="right") + Rejoin()(x_node, y_node, label="diamond_result") _run(job, run_async) - assert _hashes(job.nodes["diamond_result"]) == _hashes(diamond) + assert _hashes(job.nodes["diamond_result"]) == hashes @pytest.mark.parametrize("reverse", [False, True]) @@ -155,7 +299,8 @@ def test_slots_keep_their_names_across_bindings(reverse: bool, run_async: bool) } for invocation in invocations: assert invocation.label is not None - assert invocation.source_chain() is None + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = invocation.source_chain() assert invocation.node_hash() == blueprint.nodes[invocation.label].node_hash() job = PipelineJob.from_pipeline( @@ -229,7 +374,10 @@ def test_unbound_blueprint_names_all_upstream_slots() -> None: 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="undefined.*left_slot.*right_slot" + ): + _ = element.source_chain() with pytest.raises(UnboundSourceError, match="unbound.*left_slot.*right_slot"): element._chain_content_hash() @@ -263,14 +411,15 @@ def test_loaded_blueprint_chains_use_saved_unary_structure(tmp_path: Path) -> No assert operator.pipeline_hash() == pipeline.nodes["picked"].pipeline_hash() assert operator.name_chain() == pipeline.nodes["picked"].name_chain() assert operator.node_hash() == pipeline.nodes["picked"].node_hash() - assert operator.source_chain() is None + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = operator.source_chain() with pytest.raises(UnboundSourceError, match="unbound.*lists"): operator._chain_content_hash() @pytest.mark.filterwarnings("ignore:Index is provisional") def test_loaded_index_job_chains_survive_rebinding(tmp_path: Path) -> None: - """A saved Index passes its input chains through while remaining read-only.""" + """A saved Index hashes its input chains while remaining read-only.""" from orcapod.core.nodes.operator_node import OperatorJobNode source = DictSource( @@ -294,7 +443,8 @@ def test_loaded_index_job_chains_survive_rebinding(tmp_path: Path) -> None: assert restored.content_hash() == original.content_hash() assert restored.name_chain() == original.name_chain() assert restored.node_hash() == original.node_hash() - assert restored.source_chain() is None + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = restored.source_chain() with pytest.raises(UnboundSourceError, match="unbound.*lists"): restored._chain_content_hash() @@ -309,7 +459,9 @@ def test_loaded_index_job_chains_survive_rebinding(tmp_path: Path) -> None: source_id="replacement", ) loaded.bind(sources={"lists": replacement}) - assert restored.source_chain() == replacement.source_chain() + assert restored.source_chain() == _chain( + SOURCE_CHAIN_HASH_LABEL, None, replacement.source_chain() + ) assert restored._chain_content_hash() != original._chain_content_hash() assert restored.node_hash() == original.node_hash() @@ -334,7 +486,8 @@ def test_loaded_pick_job_chains_survive_rebinding(tmp_path: Path) -> None: assert restored.producer is None assert restored.pipeline_hash() == original.pipeline_hash() assert restored.content_hash() == original.content_hash() - assert restored.source_chain() is None + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = restored.source_chain() with pytest.raises(UnboundSourceError, match="unbound.*input"): _ = restored._chain_content_hash() loaded.bind(sources={"input": source}) @@ -361,6 +514,48 @@ def _data_tags(name: str, reverse: bool = False) -> DictSource: ) +@pytest.mark.parametrize("reverse", [False, True]) +def test_nested_joins_keep_source_pairings(reverse: bool) -> None: + """Swapping sources across the inner joins changes the outer content identity.""" + from orcapod.operators import DropNulls, SelectDataColumns + + a, b, c, d = (_data_tags(name, reverse) for name in "abcd") + columns = ["y", "x"] if reverse else ["x", "y"] + f, g = SelectDataColumns(columns), DropNulls(columns) + + def join(left: StreamProtocol, right: StreamProtocol) -> StreamProtocol: + return Join()(*(right, left) if reverse else (left, right)) + + fa, fc, gb, gd = f(a), f(c), g(b), g(d) + assert fa.pipeline_hash() == fc.pipeline_hash() + assert gb.pipeline_hash() == gd.pipeline_hash() + assert fa.pipeline_hash() != gb.pipeline_hash() + original = join(join(fa, gb), join(fc, gd)) + crossed = join(join(fa, gd), join(fc, gb)) + assert original.pipeline_hash() == crossed.pipeline_hash() + assert original.source_chain() != crossed.source_chain() + assert original._chain_content_hash() != crossed._chain_content_hash() + + +@pytest.mark.parametrize("reverse", [False, True]) +def test_swapping_source_bindings_at_one_tied_join(reverse: bool) -> None: + """Equal structural inputs exchange sources without changing either identity.""" + from orcapod.core.nodes.source_node import SourceJobNode + + a, b = _data_tags("a", reverse), _data_tags("b", reverse) + + def joined(left: DictSource, right: DictSource) -> StreamProtocol: + x = SourceJobNode.from_stream(left, name="x") + y = SourceJobNode.from_stream(right, name="y") + assert x.pipeline_hash() == y.pipeline_hash() + return Join()(*(y, x) if reverse else (x, y)) + + original, swapped = joined(a, b), joined(b, a) + assert original.source_chain() == swapped.source_chain() + assert original.name_chain() == swapped.name_chain() + assert _hashes(original) == _hashes(swapped) + + @pytest.mark.parametrize("reverse", [False, True]) @pytest.mark.parametrize("run_async", [False, True]) def test_commutative_equal_structure_sorts_the_chains_independently( @@ -371,32 +566,28 @@ def test_commutative_equal_structure_sorts_the_chains_independently( 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) + sources = sorted( + (left.source_chain(), right.source_chain()), key=ContentHash.to_string ) + names = 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 - ) + == _chain(SOURCE_CHAIN_HASH_LABEL, None, *sources) ) assert ( result.name_chain() == swapped.name_chain() - == SemanticAwarePythonHasher(hasher_id=NAME_CHAIN_HASH_LABEL).hash_object(names) + == _chain(NAME_CHAIN_HASH_LABEL, None, *names) ) assert _hashes(result) == _hashes(swapped) repeat = Join()(left, left) - 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())) + expected_sources = _chain( + SOURCE_CHAIN_HASH_LABEL, None, left.source_chain(), left.source_chain() + ) + expected_names = _chain( + NAME_CHAIN_HASH_LABEL, None, left.name_chain(), left.name_chain() + ) assert repeat.source_chain() == expected_sources assert repeat.name_chain() == expected_names @@ -520,8 +711,7 @@ def argument_symmetry( (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)) + assert result_chain == _chain(label, None, group_chain, group_chain) def test_mixed_nested_symmetry_uses_pipeline_order( @@ -549,8 +739,7 @@ def argument_symmetry( ), (NAME_CHAIN_HASH_LABEL, a.name_chain(), pair.name_chain(), result.name_chain()), ): - hasher = SemanticAwarePythonHasher(hasher_id=label) - assert result_chain == hasher.hash_object((leaf_chain, pair_chain)) + assert result_chain == _chain(label, None, leaf_chain, pair_chain) assert all(_hashes(result)) @@ -687,10 +876,11 @@ def unexpected_delegate_access(*args: object, **kwargs: object) -> None: for method in ("content_hash", "pipeline_hash", "head", "iter_data"): monkeypatch.setattr(source, method, unexpected_delegate_access) - name = SemanticAwarePythonHasher(hasher_id=SLOT_NAME_HASH_LABEL).hash_object( - ("slot", "unknown" if anonymous else source.source_name) + name = _chain( + NAME_CHAIN_HASH_LABEL, ("slot", "unknown" if anonymous else source.source_name) ) - assert proxy.content_hash() == proxy.source_chain() == content_hash + assert proxy.content_hash() == content_hash + assert proxy.source_chain() == _source_leaf(content_hash) assert proxy.pipeline_hash() == pipeline_hash assert proxy.name_chain() == name assert proxy.node_hash() == SemanticAwarePythonHasher( @@ -786,7 +976,8 @@ def unexpected_row_hash(*args: object) -> None: pytest.fail("identity must reuse the warm Arrow digest") monkeypatch.setattr(ArrowTableStream, "_identity_table", unexpected_row_hash) - assert raw.source_chain() == expected + assert raw.source_chain() == _source_leaf(expected) + assert raw.name_chain() == _chain(NAME_CHAIN_HASH_LABEL, ("slot", None)) assert raw._chain_content_hash() @@ -818,9 +1009,9 @@ def test_plain_derived_binding_has_no_content_when_origin_is_unbound( before = result.source_chain(), *_hashes(result) slot.bound_source = None - assert origin.source_chain() is None - assert binding.source_chain() is None - assert result.source_chain() is None + for stream in (origin, binding, result): + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = stream.source_chain() with pytest.raises(UnboundSourceError, match="Content identity is undefined"): _ = result._chain_content_hash() assert result.node_hash() == before[2] @@ -861,7 +1052,12 @@ def count_visit( monkeypatch.setattr(identity_chains.IdentityWalk, "visit", count_visit) before = _hashes(result) assert len({id(element) for element in visits}) == 51 - assert hashes + assert Counter(hashes) == { + SOURCE_CHAIN_HASH_LABEL: 51, + NAME_CHAIN_HASH_LABEL: 51, + identity_chains.CONTENT_HASH_LABEL: 1, + NODE_HASH_LABEL: 1, + } hashes.clear() visits.clear() assert _hashes(result) == before @@ -872,7 +1068,10 @@ def count_visit( after = _hashes(result) assert after[0] != before[0] assert after[1] == before[1] - assert hashes == [identity_chains.CONTENT_HASH_LABEL] + assert Counter(hashes) == { + SOURCE_CHAIN_HASH_LABEL: 51, + identity_chains.CONTENT_HASH_LABEL: 1, + } assert len({id(element) for element in visits}) == 51 hashes.clear() assert _hashes(result) == after @@ -897,11 +1096,12 @@ def test_unbound_slot_binding_has_no_source_chain(inner_job: bool) -> None: slot.bound_source = None with pytest.raises(SourceSpecMismatchError, match="depends on source slot"): outer.bind(sources={"reading": slot}) - assert outer.nodes["result"].source_chain() == source.content_hash() + assert outer.nodes["result"].source_chain() == add.pod(source).source_chain() return outer.bind(sources={"reading": SourceNode.from_stream(source, name="inner_slot")}) result = outer.nodes["result"] - assert result.source_chain() is None + with pytest.raises(UnboundSourceError, match="Source chain is undefined"): + _ = result.source_chain() with pytest.raises(UnboundSourceError, match="unbound.*reading"): result._chain_content_hash() @@ -1134,12 +1334,15 @@ def bind() -> None: except TimeoutError: pass else: - assert result.source_chain() == rebound.content_hash() + assert ( + result.source_chain() + == rebound.select_data_columns(["x"]).source_chain() + ) finally: resume.set() first.result(timeout=5) rebinding.result(timeout=5) - assert result.source_chain() == rebound.content_hash() + assert result.source_chain() == rebound.select_data_columns(["x"]).source_chain() def test_identity_memo_is_invalidated_before_binding_is_visible( @@ -1159,7 +1362,7 @@ def test_identity_memo_is_invalidated_before_binding_is_visible( result = job.nodes["projection"] slot = job.nodes["reading"] assert isinstance(slot, SourceJobNode) - assert result.source_chain() == source.content_hash() + assert result.source_chain() == source.select_data_columns(["x"]).source_chain() original = slot._invalidate_identity_chains # pyright: ignore[reportPrivateUsage] # Inspect the binding at the invalidation boundary. invalidating, resume = Event(), Event() @@ -1178,49 +1381,47 @@ def pause() -> None: resume.set() bind.result(timeout=5) assert slot.bound_source is rebound - assert result.source_chain() == rebound.content_hash() + assert result.source_chain() == rebound.select_data_columns(["x"]).source_chain() -def test_identity_terms_accept_canonical_semantic_values( +def test_identity_entries_accept_canonical_semantic_values( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Terms accepted by semantic hashing can include dictionaries and lists.""" + """Tagged extension payloads 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_entry, name_entry = ("mode", {"mode": "x"}), ("variant", ["variant"]) + monkeypatch.setattr(result, "_identity_entries", lambda: (source_entry, name_entry)) + for label, upstream, entry, chain in ( ( SOURCE_CHAIN_HASH_LABEL, source.source_chain(), - source_term, + source_entry, result.source_chain, ), - (NAME_CHAIN_HASH_LABEL, source.name_chain(), name_term, result.name_chain), + (NAME_CHAIN_HASH_LABEL, source.name_chain(), name_entry, result.name_chain), ): - expected = SemanticAwarePythonHasher(hasher_id=label).hash_object( - ("term", upstream, term) - ) + expected = _chain(label, entry, upstream) assert chain() == expected assert chain() == expected -def test_name_term_memo_respects_semantic_types_after_rebind( +def test_name_entry_memo_respects_semantic_types_after_rebind( monkeypatch: pytest.MonkeyPatch, ) -> None: - """Python-equal terms can encode distinct semantic values.""" + """Python-equal tagged payloads can encode distinct semantic values.""" source = _source("reading", False) - job = PipelineJob(name="name_terms", database=InMemoryArrowDatabase()) + job = PipelineJob(name="name_entrys", 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)) + monkeypatch.setattr(result, "_identity_entries", lambda: (None, ("test", 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) + expected = _chain( + NAME_CHAIN_HASH_LABEL, ("test", term), job.nodes["reading"].name_chain() ) assert first != expected assert result.name_chain() == expected