diff --git a/.zed/rules b/.zed/rules
index 909cc51d5..ae46179fd 100644
--- a/.zed/rules
+++ b/.zed/rules
@@ -971,8 +971,8 @@ Pipeline structure, bound sources, and slot names contribute to three hashes:
2. pipeline_hash() — schema + topology only. Ignores data content. Used for DB path scoping
so that different sources with identical Arrow schemas share database tables.
3. node_hash() — the pipeline hash with its name chain. The name chain still exists
- when a contributing slot is unbound. Bound graph keys use content identity while
- unbound graph declarations use name-based identity.
+ when a contributing slot is unbound. In-memory graph keys use node identity.
+ Saved and execution identities follow the legacy projection.
Base case: RootSource.pipeline_identity_structure() returns the Arrow schema identity of
its tag and data schemas (below, "Schemas are hashed as Arrow schemas").
diff --git a/CLAUDE.md b/CLAUDE.md
index 8c6ad7207..af178dbcd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -991,8 +991,8 @@ Pipeline structure, bound sources, and slot names contribute to three hashes:
2. **`pipeline_hash()`** — schema + topology only. Ignores data content. Used for DB path
scoping so that different sources with identical Arrow schemas share database tables.
3. **`node_hash()`** — the pipeline hash with its name chain. The name chain still
- exists when a contributing slot is unbound. Bound graph keys use content identity
- while unbound graph declarations use name-based identity.
+ exists when a contributing slot is unbound. In-memory graph keys use node identity.
+ Saved and execution identities follow the legacy projection.
Base case: `RootSource.pipeline_identity_structure()` returns the Arrow schema identity of
its tag and data schemas (below, "Schemas are hashed as Arrow schemas").
diff --git a/changelog.d/ITL-1559.md b/changelog.d/ITL-1559.md
index a2b462c8e..071b1f800 100644
--- a/changelog.d/ITL-1559.md
+++ b/changelog.d/ITL-1559.md
@@ -1,5 +1,40 @@
### Breaking changes and migration
+- `Pipeline.graph` and `PipelineJob.graph` are removed. Use `dag` for topology and
+ adjacency, `nodes[label]` for node information, and `diagram()` to display the graph.
+ Use the pipeline API to add vertices or edges.
+- Jobs refuse one source object on two slots at capture, binding or load. Bind
+ the source to one slot and branch from that slot. Step 6 of ITL-1559 will let
+ both slots run (ITL-1442).
+- Capture refuses nodes, slots and invocation streams from other blueprints and
+ jobs, including prebuilt streams over them. Pass the source itself or use
+ `node.as_source()` to read another job's stored results. Rebuild a loaded
+ graph from its original code to add steps.
+- A slot name holds one leaf object. Reuse the same stream or declare the
+ other object under its own name with `SourceNode.from_stream(stream, name=...)`.
+ ITL-1553 will define when separate objects can share a slot.
+- Capture refuses a slot and an unrelated step under the same name. Capture and
+ binding refuse legacy execution identities shared by two slots or by a slot
+ and a step, including slots with different inferred names. Reuse the recorded
+ step's output or bind distinct sources.
+- Jobs refuse bindings to another graph's live invocation streams and compiled
+ nodes. Job-derived blueprints keep their compiled graph and refuse new captures.
+- Compiled blueprint and job steps refuse input replacements. Build a new graph
+ to change its edges, or bind a different source to an existing job slot.
+- To add a downstream step in a later blueprint capture, pass the original
+ invocation stream. Capture from the compiled blueprint step is refused.
+- Capture refuses reuse of a pod and its input objects when rewiring changes
+ their graph key. Create a new descriptor for the rewired inputs.
+- Capture refuses using both an explicit slot declaration and its exact source
+ directly until ITL-1553 defines source and stream equivalence. Choose one capture
+ form and branch from it.
+- The DAG and its vertex listing accept membership queries for their own vertices.
+ A foreign stream, node or invocation raises `UndefinedGraphMembershipError`.
+ Internal graph-key strings are unavailable in public DAG queries.
+ Access nodes by label through `job.nodes[label]` or `pipeline.nodes[label]`.
+ Automatically numbered labels for steps sharing one automatic name follow node-hash order
+ (ITL-1559).
+
- Function pods that receive an invocation context now include the configured parameter
name in their pipeline hash. Their pipeline tables and downstream tables that use the
affected hashes have new `schema:
` paths, and downstream system-tag column names
@@ -41,6 +76,37 @@
### Fixed
+- Reversed captures of a commutative custom operator share one graph vertex and
+ keep the downstream rows visible. (ITL-1559)
+- Ordered custom operators retain both branches when captured with reversed
+ arguments. Rebuilt jobs use ordered identities, and saved jobs can still
+ read results from previous runs. (ITL-1559)
+- Invocation imports refuse foreign output substitutions. Blueprint capture
+ accepts standalone operator descriptors as independent inputs. (ITL-1559)
+- A refused invocation import leaves the caller's declarations and descriptors
+ available for reuse. Standalone DAGs and the NetworkX adapter use the supplied
+ objects as keys, preserving distinct bound jobs' nodes and results in both
+ orchestrators. Standalone DAG adjacency preserves edge operand metadata, and
+ standalone node runs can join differently bound instances of one blueprint.
+ Tracing such a join includes both sources. The standalone vertex mapping
+ exposes live attributes, and async results accept equal aliases and report
+ stale rows after a rebind.
+ (ITL-1559)
+- Stacked trackers run public validation before recording. Capture applies the
+ receiving graph's rules with custom source factories and recognizes foreign
+ inputs inside descriptor wrappers and executed slot outputs. Binding also
+ refuses executed slot outputs. Jobs check descriptor edits while the descriptor
+ is reachable from a live input. (ITL-1559)
+- Blueprints refuse rewires that change captured input identities and
+ recompiles that change a held slot's schema. (ITL-1559)
+
+- Job binding checks whether the proposed databases can store pending steps before updating
+ sources or databases. (ITL-1559)
+
+- Blueprints accept schema-only slots even when the example stream matches a recorded step. Capture checks new execution identities incrementally. Jobs refresh those identities after rewiring, binding, and recompilation so a later capture refuses a collision with a live slot. (ITL-1559)
+
+- Distinct raw Arrow inputs keep their own implicit slots and results. Direct blueprint saves select one legacy descriptor per wire key and write each edge once. (ITL-1559)
+
- Retained outputs from source slots raise `StaleOutputError` after a contributing
slot is rebound. Read the node again for the current binding. This prevents
downstream operator logs from recording old rows under the new binding's hash.
diff --git a/docs/api/errors.md b/docs/api/errors.md
index 860739d66..fe8fac421 100644
--- a/docs/api/errors.md
+++ b/docs/api/errors.md
@@ -68,6 +68,8 @@ These exceptions and warnings report problems running pipelines, processing rows
::: orcapod.errors.PipelineJobRequiredError
+::: orcapod.errors.UndefinedGraphMembershipError
+
::: orcapod.errors.DataFunctionUnavailableError
::: orcapod.errors.OutputTypeError
diff --git a/docs/concepts/identity.md b/docs/concepts/identity.md
index f0a9c4c83..45b00571d 100644
--- a/docs/concepts/identity.md
+++ b/docs/concepts/identity.md
@@ -33,8 +33,9 @@ Most sources use their schema, `source_id` and key columns in their identity (th
matching those fields gives the same content hash even when the rows differ.
`DerivedSource(tags_as_data=...)` also hashes the tag-copy mapping. A derived source
without tag copies takes its identity from the producing node's content hash.
- A pipeline or job registers one source object per content hash at capture, binding,
- loading and execution.
+ A slot name holds one source or stream object. A job reads a source object through
+ one slot. At capture, binding, loading and execution, equal-content root source
+ objects must be reused.
See [source consistency](sources.md#source-ids-name-the-kind-that-reads-the-data).
Two sources that differ only in their key columns name the same rows differently, so they
diff --git a/docs/concepts/pipeline-job.md b/docs/concepts/pipeline-job.md
index 90dde0c30..9e803b110 100644
--- a/docs/concepts/pipeline-job.md
+++ b/docs/concepts/pipeline-job.md
@@ -90,13 +90,13 @@ node:
| Function pod | The `label=` passed when it was applied; otherwise the function's name |
| Operator | The operator's class name (`Join`, `GroupBy`), numbered when there are several (`SelectDataColumns_1`) |
+Steps with the same automatic name are numbered in `node_hash()` order.
+
```python
print(sorted(job.nodes))
# ['bmi', 'mice']
```
-The order in which `job.nodes` lists its names is not meaningful and can differ between
-Python sessions; look nodes up by name.
A node is a stream: `output_schema()`, `keys()`, `iter_data()`, `as_table()` and
`as_pandas_df()` work on it, and show the rows of the job's **current run** in this Python
@@ -455,6 +455,15 @@ print(job_c.nodes["bmi"].as_table().num_rows)
# 1
```
+Access a node by label with `job.nodes[label]` or `job.`. For a blueprint,
+use `pipeline.nodes[label]`. The DAG and its vertex listing contain their own
+compiled nodes. Using `in` with a foreign stream, node or invocation raises
+`UndefinedGraphMembershipError`. Change the topology through the pipeline API.
+
+To add a downstream step in a later blueprint capture, keep and pass the stream
+returned by the original pod call. Using the compiled blueprint step as an
+input raises `InconsistentSourceError`.
+
Every job also carries its blueprint as `job.pipeline`.
## Job graph limitations
@@ -467,6 +476,10 @@ one form in the job.
## Seeing the graph
+Use `job.dag` or `pipeline.dag` for topology and adjacency. Read node metadata through
+`job.nodes[label]` or `pipeline.nodes[label]`, and call `diagram()` to display the graph.
+The `graph` property was removed from `Pipeline` and `PipelineJob`.
+
!!! caution "In development"
`Pipeline.diagram()`, `PipelineJob.diagram()`, `PipelineDiagram` and its methods and
arguments, the look of the picture and the notebook display may change in any release
diff --git a/docs/concepts/sources.md b/docs/concepts/sources.md
index 46c83a745..bfa0b7bcf 100644
--- a/docs/concepts/sources.md
+++ b/docs/concepts/sources.md
@@ -151,11 +151,11 @@ derived source still uses the node's live schema and keys. Restriction checks
stop at the wrapper, and source object registration uses the wrapper itself
and its content hash.
-Capturing into a loaded job or recompiling it can lose its restored graph
-(ITL-1560). Recompilation preserves the loaded job's public `sources` mapping.
+A loaded graph refuses new captures. Rebuild the graph from its original code
+to add steps. Recompiling a loaded job can lose its restored graph (ITL-1560).
-The same rule applies to wrappers. Each of these pairs raises
-`InconsistentSourceError` when the objects share one content hash.
+A slot name identifies one leaf object. A job binds a source object to one slot.
+The table gives the remedy when capture or binding raises `InconsistentSourceError`.
| Sources used together | How to share the source |
| --- | --- |
@@ -164,6 +164,13 @@ The same rule applies to wrappers. Each of these pairs raises
| Two calls to `node.as_source()` on one node | Call `as_source()` once and reuse the result. |
| Two `DerivedSource(tags_as_data=...)` objects with the same hash | Build one derived source and reuse it. |
| A source or its cache paired with a `SourceProxy` restored for it | Choose one source object and reuse it. |
+| One source object on two slots of a job, including in a saved job | Bind it to one slot and branch from that slot. |
+| Two streams or declarations with different leaf objects sharing a slot name | Reuse the original object, or declare one under another name with `SourceNode.from_stream(stream, name=...)`. |
+| An explicit slot and a different root source taking one name | Declare the two leaves under distinct names. |
+| An explicit slot and a direct capture of its exact source | Use one capture form and branch from it until ITL-1553 defines source and stream equivalence. |
+| Two bound slots sharing an execution identity | Bind distinct sources, or read through one slot and branch from it. |
+| A prebuilt stream with the same execution identity as a step in the graph | Reuse the step’s output inside the graph. |
+| A node, slot, or stream recorded by another graph, including through an outside-built projection | Pass the source itself, or use `node.as_source()` to read another job's stored results. |
```python
from orcapod import Pipeline, function_pod
diff --git a/docs/dev/design_issues/ITL-1204-DAG1.md b/docs/dev/design_issues/ITL-1204-DAG1.md
index cf7bbab67..c4ff2a3ad 100644
--- a/docs/dev/design_issues/ITL-1204-DAG1.md
+++ b/docs/dev/design_issues/ITL-1204-DAG1.md
@@ -1,7 +1,7 @@
## `src/orcapod/pipeline/dag.py` — the node DAG of a `PipelineJob`
### DAG1 — a source slot's node is lost from `job.dag` once a source is bound to it
-**Status:** open
+**Status:** resolved
**Severity:** medium
**Issue:** ITL-1204
@@ -18,3 +18,11 @@ and tools that use the public `job.dag` by node break. The notebook diagram (ITL
its adjacency from `edges()` for this reason. Options: key the DAG by a stable key (the
compile-time hash key, or identity), give job nodes an identity-based `__hash__`, or rebuild
the DAG on bind; each needs a check of other places that put job nodes in sets or dict keys.
+
+
+**Fix:** Step 3 of ITL-1559 keys the DAG by a stable graph key and resolves owned objects
+for adjacency. Adjacency keeps working after a binding changes a node's current content
+hash. Membership of a held vertex succeeds by object identity, and foreign stream, node
+and invocation operands raise `UndefinedGraphMembershipError`. Internal graph-key strings
+are absent from public membership and vertex lookups. The compiled DAG rejects topology
+edits. Use the label mapping to access a node.
diff --git a/docs/dev/design_issues/ITL-1559-TC1.md b/docs/dev/design_issues/ITL-1559-TC1.md
index b83c0345c..11c1bfb31 100644
--- a/docs/dev/design_issues/ITL-1559-TC1.md
+++ b/docs/dev/design_issues/ITL-1559-TC1.md
@@ -38,9 +38,89 @@ Step 1b hashes a typed entry at every node in the source and name trees. Moving
name contribution between otherwise identical steps now changes the node hash.
The source-chain accessor reports an undefined identity for unbound slots.
+Step 3 uses the node hash to address supported nodes, including unbound slots.
+Nodes whose name chain is unavailable retain a namespaced legacy key. The saved
+job format and the two source-registration refusals are addressed in later steps.
+
+The live fallback follows the pipeline hash and upstream addresses grouped by
+declared argument symmetry. Reversed captures of a commutative custom operator
+share a graph vertex and preserve downstream rows and saved bytes.
+Reversing a declared ordered operator keeps both branches and their distinct
+results. Existing saved jobs can read the rows they recorded with the previous
+grouping.
+Binding keeps the compiled graph addresses fixed. Observers receive the same
+content digests they received on main. Execution and
+the persisted run URI use the same projection through legacy content equality
+until the storage policy changes in step 6.
+
+The DAG lists the compiled vertices. Blueprint saves retain the legacy keys recorded at capture,
+including when a live upstream slot is rebound.
+
+Capture assigns unnamed raw inputs their existing content-derived slot names before
+keying the graph. Every public DAG view resolves membership and adjacency by graph
+key. Execution and blueprint save select legacy representatives through the same
+projection and leave graph membership intact.
+
+At capture, the receiving graph classifies inputs before computing a key and
+refuses foreign graph objects, including loaded blueprint and job nodes. Public adjacency returns frozensets, and duplicate explicit labels follow
+the same suffix order as on main.
+
+Capture checks names across slots and steps, including labels that the compiler
+numbers. A prebuilt slot that would displace a computed step under a legacy
+execution key is refused before recording. The same provenance checks cover job
+bindings, and a declaration belongs to its graph from its first successful
+capture. Blueprints projected from jobs retain their compiled graph.
+
+Step 3 validates legacy execution identities across slots and steps before
+publishing a capture or binding. Two distinct slots with equal identities are
+refused even when their names were inferred from different prebuilt streams.
+A multi-tracker refusal
+publishes no capture. Automatic step labels sharing the slot they introduce
+follow main’s numbering. Mixing a declaration with a direct capture of its
+source is refused in both orders pending the storage decision in the step 3
+capture specification.
+
+Capture indexes concrete legacy execution identities as it registers slots and
+steps. Checking one capture reads only the added roles. Bindings, rewires and
+recompilation validate the proposed job with the same index check and publish
+the new index only after validation succeeds. Schema-only slots and their
+downstream steps are checked when their bindings establish concrete identities.
+
+The job binding transaction checks both compiled and newly recorded roles before
+applying a batch, including when restoring saved bindings. Binding also validates
+database storage for pending steps before attaching any database or source. The
+public `graph` property was removed by the November 29, 2026 developer decision.
+Use the DAG for topology and adjacency. Membership of a held vertex succeeds, and
+foreign stream, node and invocation operands raise `UndefinedGraphMembershipError`.
+Change the topology through the pipeline API and look up nodes by label.
+
+Capture refuses a repeated call with the same pod and input objects when the
+graph key would change, preserving the association for streams already held.
+Later captures from compiled blueprint steps are refused pending the saved
+topology decision in the step 3 capture specification. The original invocation
+stream remains usable.
+
+Compiled step setters classify introduced inputs and refuse topology changes
+before replacing the upstream tuple. Slot rebinding remains available. The
+standalone DAG and NetworkX adapter preserve the supplied objects as keys.
+Standalone DAG adjacency retains the objects supplied when each edge is
+first inserted. A standalone node's dependency run walks upstream objects
+by identity and builds a temporary DAG with the original content equality,
+including the shared execution of content-equal inputs. Provenance follows
+the original upstream objects so a standalone trace can distinguish matching
+graph keys from different instances. A standalone vertex view exposes live
+attributes, and async result lookup preserves the run's original node even
+when read through an equal alias or after a rebind.
+
+Both orchestrators use those same object keys when running standalone adapters.
+Receiver rules apply to custom node factories and walk through descriptor
+wrappers before deriving source keys. Stacked capture calls each tracker's
+public validation hook before recording. Capture and binding follow executed
+outputs back to their identity origins. A job checks a standalone descriptor's
+proposed inputs while the descriptor remains reachable from its live inputs.
+
Step 5 switches live content identity and stored row attribution to the pipeline
-hash paired with the source chain. Binding invalidates that hash downstream. Bound
-graph keys still use content identity.
+hash paired with the source chain. Binding invalidates that hash downstream.
Materialized outputs record the generation of each slot that feeds them. After
any of those slots is rebound, the output raises `StaleOutputError` on use, so a
diff --git a/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md
index 78ea0c2ab..b433d4606 100644
--- a/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md
+++ b/docs/dev/design_issues/ITL-1767-PJCOLLISION1.md
@@ -13,5 +13,7 @@ unary pods over different slots bound to the same source have the same problem.
**Mitigation:** Job compilation refuses distinct steps that share an execution
vertex, even when no keys match or both steps already hold current results.
-Sharing the source itself still works. The follow-up is to let both steps run
-and read their rows independently.
+Step 3 of ITL-1559 refuses shared slot bindings and mixed direct and declared
+source capture earlier. The ITL-1767 diagnostic still covers distinct steps
+that would share an execution vertex after a job node's inputs change.
+The follow-up is to let both steps run and read their rows independently.
diff --git a/docs/dev/specs/itl-1559-step-3-capture-boundary.md b/docs/dev/specs/itl-1559-step-3-capture-boundary.md
new file mode 100644
index 000000000..bd57b0161
--- /dev/null
+++ b/docs/dev/specs/itl-1559-step-3-capture-boundary.md
@@ -0,0 +1,879 @@
+# Step 3 capture boundary (ITL-1559)
+
+Status: **final**, per the developer's answers of 2026-11-29 (section 11). The implementation
+of step 3 (PR 662) follows this document. It extends `itl-1559-three-chain-hash.md` (the
+three chains, the decisions and the step table). That document decides what happens inside a
+graph. This one decides what happens when something enters a graph, and how a node is
+referred to, keyed, identified and found.
+
+## 1. Why this document exists
+
+Step 3 keys the graph by `node_hash`. Four independent reviews of PR 662 failed it. Three of
+them found a route that gives a wrong result without an error. Each time, something from
+outside the graph (a node of another job, a prebuilt stream, a second slot on one source)
+entered the graph and was merged with a different node. The last implementation round put a
+rule inside the graph: a node's identity is its graph key. The remaining faults are at the
+boundary, where things are captured. This document decides that boundary, as a table of
+every way in and a few rules that produce the table.
+
+Constraints already decided by the developer:
+
+- No stored value moves in step 3. Run URIs, stored rows and saved bytes equal `main`'s,
+ except the BL16 label numbering of section 2.2 of the three-chain document. The most
+ recent explicit label rule waits for step 4 (Q6).
+- D43: an implicit slot of a prebuilt stream is named `:`
+ for now. Content-independent implicit names are ITL-1700.
+- D31, amended on 2026-11-29 (Q4): `main` refuses a second object with an equal content hash
+ (PR 577); step 3 keeps that refusal. One source object on two slots, which `main` accepts,
+ is refused in step 3. Step 6 lifts both.
+- Slot model direction (ITL-1559): `g.pod(source)` derives a slot, registers it, and binds
+ it if unbound; the node label names the slot.
+
+## 2. Reference, key, identity, membership
+
+This section is THE rule. Four questions are asked of a node, and each has its own answer.
+They are never mixed.
+
+**(1) Reference: how a user names a node.** A user refers to a node by its **label**:
+`job.` or `job.nodes[label]` (the run summary's `nodes_by_label` uses the same
+labels). A label exists while a slot below is unbound, and a rebind does not change it.
+
+**(2) Key: how a graph holds a node.** Inside one graph (a `Pipeline` or a `PipelineJob`),
+nodes, edges and labels are held under the **graph key**, the node hash
+(`node_hash_v1:`). The key is an implementation matter. It is fixed at capture and
+never recomputed after a bind, a rebind or a recompile. It is never shown as a public
+answer: `job.nodes` is keyed by label, as on `main`. The developer removed
+`Pipeline.graph` and `PipelineJob.graph` on November 29, 2026. Use the public DAG
+for topology and adjacency. Argument positions belong to the internal graph.
+
+**(3) Identity: when two nodes are equivalent.**
+- A **blueprint** node (a `Pipeline` node) is identified by its **node hash**: the same
+ declaration (structure and slot names).
+- A **job** node is identified by its **content hash**: the same computation over the same
+ data. It is undefined below an unbound slot, it changes on a rebind, and it is what
+ storage uses.
+
+**(4) Membership.** On the public DAG and its vertex listing, `in` returns `True` for a
+held vertex by object identity and raises `UndefinedGraphMembershipError` for a foreign
+stream, node or invocation object. The label mapping accepts labels. DAG adjacency
+resolves the receiving graph's own node objects by identity and raises `KeyError` for an
+object from another graph.
+
+**(5) Total identity: a follow-up, not part of step 3.** A node is pinned completely only by
+three chains together: its structure (the pipeline hash), its source chain (which data) and
+its name chain (which named slots). The **total identity** is
+`H(pipeline_hash, source_chain, name_chain)`. Neither hash used today is enough on its own:
+
+| Case | Content hash | Node hash | Total identity |
+|---|---|---|---|
+| Two slots `x` and `y` on one source, through one pod | Equal | Different | Different |
+| Two instances of one blueprint on different sources | Different | Equal | Different |
+| Two instances of one blueprint on one source | Equal | Equal | Equal |
+
+The total identity is undefined while a slot below is unbound, like the content hash.
+
+Step 3 does **not** introduce it: no new stored or saved hash before the developer decides.
+Proposed design, for the follow-up issue (**issue to be filed by the coordinator**):
+- Name: `total_identity()` on a node, a `ContentHash` labelled `total_identity_v1`, preimage
+ `(pipeline_hash, source_chain, name_chain)`, defined beside the other chains in
+ `core/identity_chains.py`.
+- Uses: the precise "same node" test between two jobs (`a.same_node_as(b)` below), run
+ summaries and observability that must tell two slots on one source apart, probes and
+ restrictions attached per edge (an edge is pinned by the total identities of its two
+ ends), and comparing a loaded job with a live one. Storage keeps the content hash.
+
+## 3. Membership methods
+
+`in`, `==` and `hash()` answer a vague question. Step 3 keeps `==` and `hash()` exactly as on
+`main` and documents what each one compares. A small set of descriptive methods is proposed
+so that callers say what they check. **Step 3 adds nothing public**: each method below is a
+proposal for the developer to approve. The implementation uses private helpers with the same
+meaning.
+
+| Proposed method | Semantics | In step 3 |
+|---|---|---|
+| `graph.holds(node) -> bool` | True if and only if this graph recorded this object (`is`). Another graph's object is never held | Proposal only |
+| `graph.node_for_label(label) -> Node` | The node this graph shows under the label; `KeyError` naming the known labels otherwise | Proposal only; `graph.nodes[label]` and `graph.` already do this |
+| `a.same_declaration_as(b) -> bool` | Equal node hashes: same structure and slot names, whatever is bound | Proposal only |
+| `a.same_computation_as(b) -> bool` | Equal content hashes: same computation over the same data. Raises `UnboundSourceError` when either is undefined | Proposal only |
+| `a.same_node_as(b) -> bool` | Equal total identities (section 2 (5)). Raises `UnboundSourceError` when undefined | Proposal only, with the total identity follow-up |
+
+### 3.1 What `in`, `==` and `hash()` do in step 3
+
+Run on `main` at `813c5110` (rows 43 to 51, section 6):
+
+- `a == b` between nodes: `main` compares identity structures, so two job nodes are equal
+ when their computations over their data are equal (their content hashes agree). Step 3
+ keeps `main`'s answer in every row. The head today answers by node hash (`True` for two
+ instances on different sources, row 43): the implementation restores `main`'s.
+- `hash(node)`: `main` returns the content hash as an integer. Step 3 keeps it. No graph
+ container uses a node's `__eq__` or `__hash__` (R2), so neither answer decides membership.
+- DAG and vertex-list membership follow section 2 (4). The label mapping raises
+ `UndefinedGraphMembershipError` for stream, node and invocation operands. Public
+ vertex collection operations use main's node equality and hashing on demand.
+- Adjacency results are `frozenset` snapshots, as on `main`. Building a public
+ snapshot uses the public node hash. Internal traversal resolves adjacency by graph key.
+- Execution observers receive `main`'s content digest in `on_node_start` and
+ `on_node_end`, including after a rebind and when reading a saved run.
+- `graph.nodes[label]`, `graph.`: unchanged from `main`; always this graph's own node.
+ The head today keys `job.nodes` by graph key (`job.nodes["output"]` raises `KeyError`): the
+ implementation restores `main`'s label keys.
+
+## 4. Terms
+
+- **Graph**: a `Pipeline` (a blueprint) or a `PipelineJob`, while it records steps.
+- **Capture**: recording a step into a graph, `pod(stream)` inside `with graph:`. Every
+ input of the step is either a node this graph already holds or a new **leaf**.
+- **Leaf**: an input the graph does not trace further back. It becomes a slot.
+- **Leaf object**: the object a leaf stands for. For a root source, a source wrapper, a
+ prebuilt stream or a raw stream, the object itself. For an explicit slot declared from a
+ stream (`SourceNode.from_stream(s, name=...)`), the stream `s` it was declared from; the
+ declaration remembers `s` for this comparison only (not bound, not hashed, not saved). For
+ a slot declared from schemas alone, the declaration itself. For a job's slot, its bound
+ source, or the slot itself when unbound.
+- **Slot**: a named input of a graph. An **explicit slot** has a name the user gave
+ (`SourceNode(name=...)`, `SourceNode.from_stream(s, name=...)`). An **implicit slot** gets
+ its name from the leaf: a root source's `source_name`, or `:` for
+ anything else (`slot_name_for` on `main`).
+- **Graph key**: the string under which the graph keeps a node, its edges and its label. In
+ step 3 it is `node_hash_v1:`, the node hash of the pipeline hash and the name chain,
+ or a `legacy:` fallback where the node hash is undefined (custom operators).
+- **Wire key**: the key a saved file writes for a node, its edges and operator inputs. In
+ step 3 it is `main`'s key: the node's content hash (`semantic_v1:`).
+- **Instance**: a job made from a blueprint, `PipelineJob.from_pipeline(blueprint, ...)`.
+ Two instances of one blueprint have equal node hashes, since their slot names are equal.
+- **Foreign object**: a node, slot or stream that another graph recorded, or a stream built
+ over one.
+
+## 5. The rules
+
+Four rules generate the table in section 6.
+
+**R1. The receiving graph names every leaf, at capture, before anything is compared.**
+The name comes only from the leaf and from what the user passed: the explicit name if one
+was given; the `source_name` of a root source or source wrapper; otherwise
+`:`, with `main`'s content hash read once at capture (D43). A name,
+key or label that another graph gave the object is never the leaf's name. Both a `Pipeline` and a `PipelineJob` refuse foreign
+objects (Q1, rows 20–28, 52 and 55–59).
+
+**R2. A slot name has exactly one leaf object, and in a job a source object has exactly one
+slot.** (Q3b, Q4.) Two captures are the same node if and only if the receiving graph
+computes the same graph key for them. For a leaf: the same slot name and the same leaf
+object. A second, different leaf object under a name already taken is refused, whatever its
+content or schema, until source equivalence is defined (ITL-1553). In a job, one source object
+bound to two slots is refused, at capture and at bind, until step 6. Each refusal happens at
+the step that brings the second leaf, or at the `bind` call, before anything is recorded or
+bound. No graph container uses Python `__eq__` or `__hash__` of a node, stream or
+invocation internally. Mixing an explicit declaration and a direct capture of its exact
+leaf is refused in either order, including across compilations. Rows 53–54 cover the same
+slot name and row 66 covers separate names. Separate explicit blueprint slots remain
+declarations and can be bound to distinct objects (row 6).
+
+Built-in and user-defined operators group upstream graph keys according to
+`argument_symmetry`. Tuple groups preserve order, and frozenset groups allow
+permutations of their members. This applies at every level of a nested group and
+also when a node uses a legacy graph key (row 82).
+An inherited commutative grouping cannot override an operator's own tuple
+declaration. Ordered captures at different argument positions retain separate
+execution identities and both branches' rows (row 83).
+
+**Names share one namespace.** The receiving graph checks root names, explicit
+and implicit slot names, and explicit, automatic and numbered step labels at
+capture. Reusing the object that holds a name leaves the existing entry in place.
+A different slot or step that would take the name is refused (row 72). Main's
+suffix allocation still applies to step display labels, including duplicate
+explicit labels (Q6b) and reserving slot names and explicit step labels before
+publishing automatic suffixes. Row 39 keeps main's numbering when a step introduces its
+own input slot with the same name as its explicit or automatic label. BL16 orders
+same-named unlabelled steps by node hash. An independent stream and an in-graph
+computation sharing a legacy execution identity are refused at capture and at bind
+(row 67). Two slots cannot share a legacy execution identity, even when they have
+different inferred names (row 74). Refusal requires a legacy execution key shared
+by two distinct slot records or by a slot and a recorded step. A schema-only slot and
+steps depending on it have no concrete execution identity. The stream used to declare
+the slot supplies schemas and supports leaf-object comparison. A collision that depends
+on bindings is decided using the proposed bindings and their downstream identities (row 75).
+Capture stages only new slot records and the retained step against an index of published
+execution roles. It publishes the index changes together with the graph (row 77).
+A job validates the proposed execution roles when a live descriptor is rewired, when
+bindings change, and when the graph is recompiled. A later capture uses those roles,
+including a prebuilt slot's current digest under its original slot name (rows 67 and 74).
+Capture also refreshes roles when a stored-result source follows a changed upstream job.
+
+**R3. Keys are fixed at capture, and only this graph's keys are used.** A graph key published
+by another graph (a compiled key, another job's node hash) is never used as this graph's
+key, and an object this graph did not record is not one of its members. A key is not
+recomputed after a bind, a rebind or a recompile. The wire key is `main`'s content hash read
+at capture and kept. The saved file, the run URI and the run's stored rows are projected
+from the graph exactly as `main` builds them: the same representative node for each wire
+key, the same edge set, the same execution grouping, and `main`'s label choice (Q6).
+Row 83 records main's erroneous commutative hashes for declared ordered
+operators. Rebuilding those captures uses ordered hashes. Existing saved jobs
+retain their recorded hashes and can still read their prior rows. Row 85
+refuses capture from a held compiled blueprint step pending a decision on
+main's saved blueprint projection. Row 87 refuses an input replacement that
+would change a captured blueprint's wire identity. Recompilation checks the
+held slot's declared schema before publishing the graph. A second call on the
+same pod and input objects still refuses if their graph key changes.
+
+**R4. What this document does not decide is refused.** Where `main` refuses, step 3 keeps
+`main`'s error. The classifier resolves each input before deriving a name or computing a
+key. The kinds are:
+
+- This graph's own recorded invocation stream, compiled job node or slot. A step built
+ inside the receiving graph links to it. An outside-built stream over it follows row 15.
+ A later blueprint capture from its own compiled step is refused under row 85.
+- A foreign node, slot or invocation stream. This includes standalone job slots,
+ bound and unbound job objects, blueprint objects, and nodes and slots restored from
+ either file format. The same refusal applies through a prebuilt stream or a live wrapper.
+- A standalone blueprint slot declaration (from schemas or from a stream), a root source
+ (including a cache or a stored-result source), or an independent raw or prebuilt stream.
+ These are leaf candidates subject to the named-slot rules and the source checks.
+ Reading stored results through `as_source()` ends the live graph walk.
+- Any other input type is refused (row 60).
+
+The same classifications apply to function, operator and side-effect registration, to
+direct record calls and to calls routed through a tracker. An invocation graph exported
+for reconstruction transfers declarations and mapped argument positions from that
+export. An independently constructed graph or a replacement of an export
+follows the normal capture boundary and cannot authorize foreign outputs or
+declarations (row 84). The receiver creates its own slots and nodes.
+The compiled function and operator setters use the same input classifier. A
+replacement would change the published topology, so these setters refuse it
+before changing the node. Reassigning the same objects in the same order is
+allowed. Jobs keep the existing shadowed-step diagnostic for an in-graph
+proposal that would share another step's execution identity. Source overrides
+go through slot binding. A standalone descriptor can still be edited subject
+to its receivers' validation.
+
+The standalone DAG and NetworkX adapter use the caller's objects as keys.
+Blueprint slot declarations preserve main's reserved-column refusal, including
+when a bound source proxy supplies a schema containing system tags.
+
+An in-graph filter and capture from a live node after
+a run are instances of rows 1 and 2. A loaded graph is read-only for capture (61–62).
+An exported blueprint projected from a job is also read-only for capture (70).
+A slot declaration belongs to its receiver as soon as capture succeeds, even
+before compile (71). A tracker call that reaches several receivers validates
+their captures and declaration ownership before publishing to any of them. The
+live-input provenance check also applies when a job
+prepares a binding through instantiation, `bind` or its slot setter (69).
+An executable node constructed independently of any graph is a prebuilt
+stream and can still be bound as such (73). A standalone operator descriptor
+can supply the schema of an implicit blueprint slot, to be bound to a
+compatible concrete stream when the blueprint is instantiated (row 86).
+
+### 5.1 Refusal errors
+
+Every new refusal raises `InconsistentSourceError` before anything is recorded or bound:
+
+| Kind | Rows | Error text |
+|---|---|---|
+| Foreign object | 20–28, 52, 55–59 | `Capturing source slot 'slot' from outside this pipeline is not supported yet (ITL-1559). Pass the source itself, or use node.as_source() to read another job's stored results.` (use "job" for a job receiver, as on `main`. For a node, use the slot reached below it when available.) |
+| Second leaf object under a taken slot name | 12, 19, 35, 37, 38 | `Slot 'x' already holds ; is another object under the same name. A slot holds exactly one source object until source equivalence is defined (ITL-1553). Pass the same object again, or declare the second one under its own slot name with SourceNode.from_stream(stream, name=...).` |
+| One source object on two slots in a job, or mixed explicit and implicit names in a blueprint | 6, 7, 66 | `Source 'dict_v1:a' would be read by slots 'x' and 'y'. One source object on two slots is not supported yet (ITL-1559, step 6). Read it through one slot and branch from that slot.` |
+| Step and slot name clash, or taking an allocated numbered label | 72 | `Name 'x' already holds ; is another object under the same name. Use the original object or choose a distinct name (ITL-1559).` |
+| A slot and a step share a legacy execution identity at capture or bind | 67 | `Slot 'x' and an in-graph step share a legacy execution identity. Capture the step inside the graph and reuse its output (ITL-1559).` |
+| Two slots share a legacy execution identity at capture or bind | 67, 74 | `Slots 'x' and 'y' share a legacy execution identity. Bind distinct sources to the slots, or read through one slot and branch from it (ITL-1559).` |
+| A declaration and a direct capture read the exact same source under one name | 53–54 | `The same source object is already declared under slot 'x'. Use the slot declaration or capture the source directly (ITL-1559).` |
+| Later capture from a compiled blueprint step | 85 | `Capturing compiled blueprint step 'first' is not supported yet (ITL-1559). Pass the original invocation stream to add a downstream step.` |
+| Rewire a descriptor used by a captured blueprint | 87 | `Cannot rewire 'external' because a captured blueprint uses its input identities (ITL-1559). Create a new descriptor for the rewired inputs.` |
+| Recompile a held slot after its schema changes | 87 | `Cannot recompile source slot 'slot' because its captured schema changed (ITL-1559). Restore the original schema or capture the new schema in a new blueprint.` |
+| Same pod and input objects resolve to a different graph key | 87 | `Capturing the same pod and input objects under a different graph key is not supported yet (ITL-1559). Create a new descriptor for the rewired inputs.` |
+
+The unknown-input error is `Capturing an input of type '' is not supported yet
+(ITL-1559). Pass a source or a supported stream.` The loaded graph error is `Capturing into
+a loaded is not supported yet (ITL-1559). Rebuild the
+from its original code before adding steps.`
+
+A leaf is shown as its kind and its name: `source 'dict_v1:a'`, `prebuilt stream
+'double:61a…'`, `declared slot 'x'`. Main's own refusals (rows 8, 9, 15, 16, 20, 30, 31, 33,
+36) keep `main`'s type and text.
+
+## 6. The table
+
+Notation for the snippets: `s = DictSource([...], source_id="a", tag_columns=["id"],
+tag_only_columns=True)`; `D`, `T`, `P` are function pods; `J = PipelineJob("j",
+database=db)`; `B = Pipeline("p")`; `tpl` is a blueprint with slot `slot` feeding step
+`output`; `inst(s) = PipelineJob.from_pipeline(tpl, sources={"slot": s})`, and `inst()` the
+unbound instance. "Leaf key" means `node_hash_v1(pipeline hash, ("slot", name))`.
+
+Rows 1 to 42: "Main today" was run on `origin/main` at `2b4d30dc` through the public API
+(one script per case, outside the repository); "Head today" is PR 662 at `e06ae8f2`. Rows 43
+to 51 were run on `origin/main` at `813c5110` and on PR 662 at `7e393d02`. Section 8 lists
+each snippet with its raw result. In the "Decision" column, **Refuse (change)** marks a row
+`main` accepts.
+
+| # | What enters the graph | Main today (run) | Head today | Slot name (R1) | Same node when (R2) | Saved (R3) | Decision |
+|---|---|---|---|---|---|---|---|
+| 1 | A pod applied to a stream built inside this graph | 3 nodes, rows correct | = main | The root's `source_name` | Same pod and same input keys | = main | Accept |
+| 2 | A node of this job, used in a later capture | 3 nodes, rows correct | = main | No new leaf | The held node's key | = main | Accept |
+| 3 | A root source object, once | Slot `a`, rows correct | = main | `source_name` (`a`) | One leaf | = main | Accept |
+| 4 | One source object, same pod twice, labels `d1`, `d2` | One node, label `d1` | One node, label `d2` | `a` | Equal keys: one node | = main | Accept, one node, label `d1` (Q6) |
+| 5 | One source object, two pods | 3 nodes | = main | `a`, one slot | The two steps differ by pod | = main | Accept |
+| 6 | One source object bound to two declared slots (`bind`) | Accepted. 4 nodes; `rb` reads zero rows after the run (ITL-1442) | = main | `a` and `b`, as declared | One object on two slots | Nothing | **Refuse (change)** at `bind` (Q4); step 6 |
+| 7 | One source object on two explicit slots at capture | Accepted. 4 nodes; `ry` reads zero rows | = main | `x` and `y` | One object on two slots | Nothing | **Refuse (change)** at the step that brings `y` (Q4); step 6 |
+| 8 | Two source objects with equal content hash (also: one `source_id`, other rows) | Refused, `InconsistentSourceError` (PR 577) | = main | `a` for both | Would be one slot | Nothing | Refuse, `main`'s error (D31) |
+| 9 | Two sources with one `source_name` and other key columns, job or blueprint | Refused, `InconsistentSourceError` (ITL-1506) | = main | `a` for both | Would be one slot | Nothing | Refuse, `main`'s error |
+| 10 | A prebuilt stream (built outside any graph), once | Implicit slot `double:` | = main | `:` (D43) | One leaf | = main | Accept |
+| 11 | The same prebuilt stream object, twice | One slot, one step node | = main, label `p2` | `double:` | One leaf object: one node | = main | Accept, label `p1` (Q6) |
+| 12 | Two prebuilt streams, equal pipeline hash, equal content | One slot, one step node | = main, label `p2` | One name (equal digest) | Two leaf objects under one name | Nothing | **Refuse (change)** (Q3b); ITL-1553 |
+| 13 | Two prebuilt streams, equal pipeline hash, other content | Two slots, rows correct | = main | Two names (digests differ) | Different names | = main | Accept |
+| 14 | A prebuilt stream over a root also captured directly | Two slots (`a`, `double:`) | = main | `a`; `double:` | Different names | = main | Accept |
+| 15 | A prebuilt stream over this job's own slot | Refused, `InconsistentSourceError` (ITL-1559 stopgap) | = main | None | - | Nothing | Refuse, `main`'s error |
+| 16 | A raw `ArrowTableStream` without system tags, in a job | Refused at bind, `SourceSpecMismatchError` | = main | `ArrowTableStream:` | - | Nothing | Refuse, `main`'s error |
+| 17 | A raw `ArrowTableStream` with system tags, once | Implicit slot, rows correct | = main | `ArrowTableStream:` | One leaf | = main | Accept |
+| 18 | Two raw streams, other content (job or blueprint) | Two slots, rows 6 and 8 | = main (fixed after the third review) | Two names | Different names | = main | Accept |
+| 19 | Two raw stream objects, equal content | One slot | = main | One name | Two leaf objects under one name | Nothing | **Refuse (change)** (Q3b); ITL-1553 |
+| 20 | A node or slot of another job, captured into a `PipelineJob` (bound or unbound) | Refused, `InconsistentSourceError` (ITL-1559 stopgap) | = main | None | - | Nothing | Refuse, `main`'s error |
+| 21 | A bound node of another job, captured into a blueprint | Implicit slot `output:` | = main | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 22 | An unbound node of another job, into a blueprint | Implicit slot `output:` | = main | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 23 | Nodes of two instances, same binding, into one blueprint | One slot, one step node | = main, label `p2` | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 24 | Nodes of two instances, different bindings, into one blueprint | Two slots, two steps | **Two nodes: one input lost, no error** | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 25 | A bound slot of another job, into a blueprint | Implicit slot `slot:` | = main | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 26 | An unbound slot of another job, into a blueprint | Implicit slot `slot:` | = main | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 27 | Slots of two instances, different bindings, into one blueprint (fourth review) | Two slots; rows `[6, 8]` and `[16, 18]` | **Two nodes; `from_second` runs on the first source, `[6, 8]`, no error** | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 28 | A loaded job's node, into a blueprint | Implicit slot `output:`; same bytes as row 21 | = main | None (foreign) | - | Nothing | **Refuse (change)** (Q1); ITL-1700 |
+| 29 | `node.as_source()` of another job's node | Slot named by the derived source name | = main | `source_name` (`semantic_v1:`) | One leaf | = main | Accept |
+| 30 | Two `as_source()` objects of one node | Refused, `InconsistentSourceError` (PR 577) | = main | One name | Would be one slot | Nothing | Refuse, `main`'s error (D31) |
+| 31 | `as_source()` of a loaded job's node, into a job | Refused, `SourceSpecMismatchError` (pre-existing) | = main | - | - | Nothing | Refuse, `main`'s error; out of scope |
+| 32 | A `CachedSource` | Slot named by the wrapped source | = main | Wrapped `source_name` | One leaf | = main | Accept |
+| 33 | A `CachedSource` and its wrapped source together | Refused, `InconsistentSourceError` (PR 577) | = main | One name | Would be one slot | Nothing | Refuse, `main`'s error (D31) |
+| 34 | An explicit slot name repeated, same leaf object | One slot | = main | `x` | One leaf object: one slot | = main | Accept |
+| 35 | An explicit slot name repeated, other leaf object, same schema (blueprint) | One slot | = main | `x` | Two leaf objects under one name | Nothing | **Refuse (change)** (Q3b); ITL-1553 |
+| 36 | An explicit slot name repeated, other schema | Refused, `InconsistentSourceError` | = main | `x` | Would be one slot | Nothing | Refuse, `main`'s error |
+| 37 | An explicit slot and a root source with the same name, blueprint | **Inconsistent**: 3 graph nodes, 4 saved nodes, two slots named `x` | One slot `x`, 3 saved nodes | `x` for both | Two leaf objects under one name | Nothing | **Refuse (change)** at the step that brings the root (Q3) |
+| 38 | An explicit unbound slot and a bound root source with the same name, job | **Inconsistent**: two slots named `x`, 4 graph nodes, 3 saved | **One unbound slot; `t` reads zero rows, no error** | `x` for both | Two leaf objects under one name | Nothing | **Refuse (change)** at the step that brings the root (Q3) |
+| 39 | A step introduces a slot with the same name as its explicit or automatic label | Main numbers the slot alone for an explicit step label and both labels for an automatic step label | Automatic case was refused | Slot binding name | Own input | = main | Accept and preserve main’s numbering |
+| 40 | One input twice in an ordered operator, `MergeJoin()(s, s)` | One slot, one edge; both argument positions run (#667) | = main, positions `(0, 1)` | `a` | One leaf, two positions | = main | Accept |
+| 41 | One step declared `r1`, then `r2`, then unlabelled | One node, label `r1` | One node, label `r2` | `a` | Equal keys: one node | = main | Accept, label `r1` (Q6) |
+| 42 | A foreign object looked up in a graph (`j2.output in j1.dag`, adjacency) | `False`; adjacency raises `KeyError` | `True`; adjacency answers | - | Not a member (R3) | - | **Refused (developer, 2026-11-29)**. Foreign adjacency raises `KeyError`. |
+| 43 | Two instances of one blueprint on DIFFERENT sources: `==`, `hash`, `in`, label, adjacency | `==` False; hashes differ; `in` False; `j1.nodes["output"]` is `j1`'s; adjacency `KeyError` | `==` True; hashes equal; `in` True; adjacency answers; `j1.nodes["output"]` raises `KeyError` | - | Not a member | - | **Refused (developer, 2026-11-29)**. Different nodes compare unequal and have distinct hashes. Label access and foreign adjacency follow row 42. |
+| 44 | Two instances on the SAME source object | `==` True; hashes equal; `in` False (also for `j1`'s own node); adjacency `KeyError` | `==` True; `in` True; adjacency answers | - | Not a member | - | **Refused (developer, 2026-11-29)**. Equal nodes retain equal hashes. Own adjacency answers and foreign adjacency raises `KeyError`. |
+| 45 | Two instances on two equal source objects | As row 44 | As row 44 | - | Not a member | - | **Refused (developer, 2026-11-29)**. Equality, hashing and adjacency follow row 44. |
+| 46 | Two UNBOUND instances | `==` True; hashes equal; `j2.output in j1.dag` **True**; adjacency answers | = main | - | Not a member | - | **Refused (developer, 2026-11-29)**. Unbound nodes compare equally. Foreign adjacency raises `KeyError`. |
+| 47 | A bound and an unbound instance | `==` False; `in` False; adjacency `KeyError` | `==` True; `in` True | - | Not a member | - | **Refused (developer, 2026-11-29)**. Bound and unbound nodes compare unequally. Foreign adjacency raises `KeyError`. |
+| 48 | A job's OWN node, job made by `from_pipeline(..., sources=...)` | `j.output in j.dag` **False**; adjacency of `j.output` raises `KeyError`; `j.nodes["output"] is j.output` | `in` True; adjacency answers; `j.nodes["output"]` raises `KeyError` | - | A member | - | **Accept** own-node membership and adjacency, including after instantiation binds the source. |
+| 49 | A job's own node, job built by capture | `J.d in J.dag` True; `J.nodes["d"] is J.d` | `J.nodes["d"]` raises `KeyError` | - | A member | - | **Accept** the directly captured node in membership and adjacency queries. |
+| 50 | A job's own node, unbound instance then `bind` | `in` True before and after the bind | = main | - | A member | - | **Accept** own-node membership and adjacency before and after binding. |
+| 51 | A blueprint's own node, and an instance's node, in the blueprint's `dag` | `tpl.output in tpl.dag` True; `inst().output in tpl.dag` **True** | = main | - | Own: member; instance's: not | - | **Accept** the blueprint’s own node in membership and adjacency queries. **Refuse** the instance’s node as in row 42. |
+| 52 | A standalone `SourceJobNode` (built by `SourceJobNode.from_stream`, in no job) captured into a `Pipeline` | Accepted at capture (checked only against other leaves) | = main | None (foreign) | - | Nothing | **Refuse (change)** as row 21 (section 10); ITL-1700 |
+| 53 | Explicit slot from `s` named `a`, then the exact `s` captured implicitly | Declared branch empty with a partial run | Both branches run and storage changes | `a` | One object through two capture routes | Nothing | **Refuse (developer, 2026-11-29)** the second capture, including across compilations. ITL-1553 tracks accepting both routes with one slot. |
+| 54 | Row 53 in reverse order | Same partial run | Same storage change | `a` | One object through two capture routes | Nothing | **Refuse (developer, 2026-11-29)** the second capture. ITL-1553 tracks accepting both routes with one slot. |
+| 55 | Compiled node from another blueprint, captured into a blueprint or a job | Capture succeeds | Capture succeeds | None (foreign) | — | Nothing | **Refuse (change)** |
+| 56 | Compiled slot from another blueprint, captured into a blueprint or a job | Capture succeeds | Capture succeeds | None (foreign) | — | Nothing | **Refuse (change)** |
+| 57 | The invocation stream returned during another blueprint's capture | Capture succeeds | Capture succeeds | None (foreign) | — | Nothing | **Refuse (change)** |
+| 58 | Outside-built projection over another blueprint's node | Capture succeeds | Capture succeeds | None (foreign) | — | Nothing | **Refuse (change)** |
+| 59 | A loaded blueprint's node, slot or prebuilt projection over its node | Capture has no deliberate foreign-object refusal | Same | None (foreign) | — | Nothing | **Refuse (change)** |
+| 60 | An object of unknown kind through a direct record method | No capture diagnostic | No capture diagnostic | None | — | Nothing | **Refuse** with the type and remedy |
+| 61 | Add a step to a loaded blueprint | No working extension route | Graph-key lookup fails | None | — | Nothing | **Refuse** at capture |
+| 62 | Add a step to a loaded job | Loaded jobs cannot compute | Loaded jobs cannot compute | None | — | Nothing | **Refuse** at capture |
+| 63 | Side-effect pod captured over a root source | Delivers both rows | Delivers both rows | Root's `source_name` | Same input and pod use one node | = main | Accept as row 1 |
+| 64 | Stored-result source with `tags_as_data` and a custom source ID | Promoted tag is data downstream | Same | Wrapper's `source_name` | Same wrapped source object | = main | Accept as row 29 |
+| 65 | Two distinct job steps sharing an explicit label | Both run with labels `d_1` and `d_2` | Context exit raises | Each root's `source_name` | Distinct steps | = main | Accept; assign suffixes by main's content-hash order |
+| 66 | Explicit declaration from a leaf with a different name from that leaf's implicit name, in either order | Separate slots | Separate blueprint slots; job refuses | Two names for one object | — | Nothing | **Refuse** with the row 7 diagnostic |
+| 67 | A prebuilt slot shares a legacy execution identity with an in-graph step, at capture or after binding | Prospective collision can fail in sync or succeed with empty rows in async | Late binding succeeds with empty rows | Receiving slot name | Distinct roles, same execution identity | Nothing | **Refuse** capture, instantiation, bind and setter before mutation |
+| 68 | Implicit source capture matches one of two existing explicit names for the same leaf | Capture succeeds | Capture succeeds | Both explicit names already held | Same source, mixed names | Nothing | **Refuse** the implicit capture with the row 7 diagnostic |
+| 69 | Bind another graph's live invocation stream, compiled node or prebuilt wrapper | Accepts some forms and refuses live job-slot dependencies | Same | Receiving slot | Foreign | Nothing | **Refuse** through instantiation, bind and setter. Keep main's error when it already refuses |
+| 70 | Add a step to a job-derived blueprint, using an independent root or the blueprint's own slot | Compile can discard the original branch | The original branch can be discarded or capture raises a graph-key error | — | — | Existing blueprint | **Refuse** at capture and keep the compiled blueprint |
+| 71 | Capture the same declaration in multiple receivers, in sequence or in one tracker call | Accepts stacked capture | Stacked call refuses after publication to one receiver | Declaration’s slot name | One owner | Nothing | **Refuse** the second use and publish nothing to any receiver for a refused tracker call |
+| 72 | An unrelated slot and step claim one name, or a new object claims a numbered label | Labels can be renumbered | Labels can be renumbered | Taken name | Distinct objects | Nothing | **Refuse** the second claim, with the row 39 and 65 numbering behavior |
+| 73 | Bind a standalone executable node over an independent stream | Function bindings keep metadata and load-only runs refuse side-effect delivery | Same | Receiving slot | Independent prebuilt stream | = main | Accept the binding and keep the existing run rules |
+| 74 | Capture equal-content prebuilt streams with different inferred names and branch from both | One legacy input and computation; the downstream output is `[70, 90]` in sync and async | The legacy projection can leave the downstream output empty | `first:` and `second:` | Two slots share one legacy execution identity | Nothing from the refused capture | **Refuse** the second capture, name both slots and preserve the first branch |
+| 75 | Capture a declaration made from a stream with the same digest as a recorded step. Also try a declaration made from schemas alone. Instantiate the blueprint unbound and supply distinct bindings. | Both branches run with outputs `[7, 9]` and `[17, 19]` | Same | Explicit `declared`, implicit `left` | Independent slots after bind | Main's wire keys | **Accept** either capture order and bind route |
+| 76 | Inspect `Pipeline.graph` or `PipelineJob.graph` | Legacy vertices, edges and attributes | Read-only view | — | — | As on main | **Removed (developer, 2026-11-29)**. Use `dag`, `nodes[label]` and `diagram()`. |
+| 77 | Capture independent branches in one graph | Legacy capture checks | Each new slot and retained step visits the execution-role index once | Distinct | Distinct | As on main | **Check incrementally** |
+| 78 | Edit vertices, edges or attributes through `Pipeline.graph` or `PipelineJob.graph` | Edits change the public graph | Read-only view | — | — | As on main | **Removed (developer, 2026-11-29)**. Use the pipeline API to change a pipeline. |
+| 79 | Bind a source and a database that cannot store a pending step’s table | Before compile, the pending source name is refused | The incompatible database is refused before either binding is published | Pending source name | Prospective nodes, including any compiled branches | Nothing | **Validate before publication**. Keep sources, databases, execution context and capture registries intact. |
+| 80 | Use a compiled blueprint or directly captured job DAG as a vertex collection | Iteration, sizing, reversal, comparison, set algebra, disjointness and membership of held vertices work | Some operations raise through their own membership guard | — | Held vertices | = main | **Preserve** main’s collection results and own-vertex queries, including NetworkX membership checks. |
+| 81 | Insert a foreign compiled node or invocation stream through the public DAG, as a vertex or either edge endpoint | Insertion succeeds silently and the invocation stream can subsequently be captured as an implicit source | Insertion succeeds and later capture can raise a bare `KeyError` | — | Foreign | Nothing | **Refuse** topology edits through the public DAG before mutation. Direct capture gives the existing foreign-source diagnostic. |
+| 82 | Capture a user-defined commutative join on `(a, b)` as `first` and on `(b, a)` as `second`. Capture `adjusted` over the second call. | One join, two downstream rows | Before the fix, two join vertices and no visible downstream rows despite two successful computations | `a`, `b` | Declared symmetry groups both calls under `first` | Main's bytes | **Accept** both calls using one graph vertex. Apply the declared argument grouping to built-in and user-defined operators. |
+| 83 | Capture a custom operator declaring a tuple and selecting its first argument, then reverse the arguments. | Silently keeps only the first branch. | Both branches run. | `a`, `b` | Same tuple of upstream keys | Rebuilt jobs write ordered hashes. Each revision reads the other's saved job and rows. | **Accept** both ordered branches. |
+| 84 | Reconstruct a two-step invocation graph with a foreign node substituted for the first output and used as the second input. | Invocation graphs carry no positional outputs. | Refuses the foreign object with the direct-capture diagnostic. | None (foreign) | — | Nothing | **Refuse** the substitution. An intact export reconstructs normally. |
+| 85 | In a later blueprint capture, feed a held compiled step into a new step. | Adds an implicit slot and the new step exposes no rows when only the original source is bound. | Refuses the capture. The original invocation stream works. | None | Held compiled blueprint step | Nothing from the refused capture | **Refuse** pending the developer's decision in §10. Use the original invocation stream. |
+| 86 | Capture a downstream step from a standalone operator descriptor in a blueprint. | Accepts it as an implicit input and runs with a compatible concrete binding. | = main | `:` | One leaf | = main | **Accept** the independent schema descriptor. |
+| 87 | Capture a projection over a standalone descriptor and replace the descriptor's inputs, or recompile after the input schema changes independently. | Can misroute downstream captures or fail to instantiate the resulting blueprint. | Refuses the rewire or recompilation. Earlier and later uses of the first output read the first slot with the original wire keys. | Original slot only | Replacement inputs can change a wire key even when the schema is identical | No change from the refused operation | **Refuse** the operation. Reassigning the same objects in the same positions is a no-op. Create a new descriptor for different inputs. |
+
+Section 7.2 records the public membership decision and adjacency results.
+
+## 7. Behaviour changes against `main` in step 3
+
+### 7.1 Routes `main` accepts and step 3 refuses
+
+| Rows | Route | Remedy | Turned on again by |
+|---|---|---|---|
+| 6, 7 | One source object on two slots of a job | Read the source through one slot and branch from that slot | Step 6 of ITL-1559 (both branches run; ITL-1442) |
+| 21 to 28, 52 | A node or slot of another job (instance, unbound or loaded), or a standalone job slot, captured into a `Pipeline` | Pass the source itself, or `node.as_source()` for another job's stored results | ITL-1700 (consistent slot naming) |
+| 12, 19, 35 | A second leaf object under a slot name already taken (equal prebuilt streams, equal raw streams, a repeated explicit name) | Pass the same object again, or declare the second under its own slot name | ITL-1553 (source equivalence) |
+| 37, 38 | An explicit slot and a root source taking the same name | Give the explicit slot another name, or pass the root source itself | None planned |
+| 55–59 | A node, slot, invocation result or prebuilt projection from another blueprint, including a loaded blueprint | Pass the source itself, or read stored job output through `node.as_source()` | ITL-1700 |
+| 60–62 | Unknown input type or capture into a loaded graph | Pass a supported stream, or rebuild the receiving graph from live code | — |
+| 53–54 | One source object captured both directly and under its declaration | Choose one capture form and branch from it | Developer decision in section 10 |
+| 66, 68 | Mixed explicit and implicit names for the same object | Read the source through one slot and branch from it | Step 6 of ITL-1559 |
+| 67, 74 | Binding or capture would give two slots, or a slot and a step, one legacy execution identity | Use distinct bindings, or capture the step inside the graph and reuse its output | Step 6 of ITL-1559 |
+| 69 | Binding another graph’s live output | Pass the source itself or use `node.as_source()` for stored results | — |
+| 70–72 | Additive capture into a job-derived blueprint, reuse of a foreign declaration, or taking a held name | Rebuild from live code, create a declaration for each receiver, or choose a distinct name | — |
+| 85 | Late capture using a compiled blueprint step | Pass the original invocation stream | Developer decision in section 10 |
+| 87 | Rewire a descriptor used by a captured blueprint or recompile a held slot with a changed schema | Create a new descriptor for different inputs. Restore the original schema or build a new blueprint for the changed schema. | — |
+
+Tests and documentation samples on `main` that use one of these routes, found by running
+`main` at `813c5110` with a probe that records each refused route (every test file that
+builds a pipeline, and `tests/test_docs/test_doc_samples.py`). Each must change in the
+implementation PR:
+
+| Test on `main` | Route (rows) | What changes |
+|---|---|---|
+| `tests/test_hashing/test_identity_chains.py`, fixture `collapsed_nested_pair` (used by `test_combined_hashes_refuse_collapsed_commutative_groups` and the strict xfail `test_nested_symmetry_preserves_order_in_collapsed_pairs`) | One source object on slots `a` to `d` of a job, at capture and at `bind` (6, 7) | Build the four slots from four source objects of distinct content |
+| `tests/test_hashing/test_identity_chains.py::test_slots_keep_their_names_across_bindings` | `job.bind(sources={"y_slot": source})` while `x_slot` holds `source` (6) | Bind `y_slot` to a second source with other rows; the blueprint part (one stream declared under two names) stays |
+| `tests/test_pipeline/test_source_id_conflicts.py::test_bind_checks_all_prospective_slots_atomically` | `job.bind(sources={"right": second})` while `left` holds `second` (6) | Assert the new refusal there |
+| `tests/test_pipeline/test_source_object_registration.py::test_bind_refuses_two_objects_with_one_hash` | `job.bind(sources={"a": first, "b": first})` (6) | Assert the new refusal |
+| `tests/test_pipeline/test_source_object_registration.py::test_load_reuses_one_object_for_identical_saved_configs` | `job.bind(sources=dict.fromkeys(slots, source))`; the load then reuses one object for two slots (6) | The bind is refused; the load of such a file is refused too (section 10) |
+| `tests/test_pipeline/test_source_object_registration.py::test_itl_1554_loading_shared_slots_feeding_the_same_pod` | `job.bind(sources={"a": source, "b": source})` (6) | The bind is refused; the ITL-1554 load failure it records needs another setup or moves to step 6 |
+| `tests/test_pipeline/test_source_object_registration.py::test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows` (setter variant) | Rotating bindings one `bound_source` setter at a time passes through one object on two slots (6) | The setter variant is refused mid-rotation; the one-call `bind` variant stays (the check reads the state after the whole call) |
+| `tests/test_pipeline/test_source_object_registration.py::test_coalesced_captures_release_duplicate_projections` | Eight `source.select_data_columns(...)` objects of equal content captured into one blueprint (12) | Capture one projection object eight times, or assert the refusal |
+| `tests/test_pipeline/test_source_object_registration.py::test_compile_refuses_schema_conflict_introduced_through_live_slot` | A standalone `SourceJobNode` captured into a `Pipeline` (52) | Refused at capture; the compile-time check needs another route or is unreachable from a blueprint |
+| `tests/test_hashing/test_logical_type_forms.py::TestNestedIdentifier::test_a_saved_slot_loads_and_binds` | Loaded blueprint slot captured directly into a job (59) | Instantiate the operator-only blueprint with the source binding. |
+| `tests/test_pipeline/test_source_object_registration.py::test_schema_declaration_gives_each_job_its_own_binding` | Compiled blueprint slot captured directly into a job (56) | Use a standalone declaration with the same name and schemas. |
+| `tests/test_pipeline/test_source_object_registration.py::test_capture_reports_both_uses_of_slots_with_the_same_name` | A standalone `SourceJobNode` captured into a `Pipeline` (52) | The first capture is refused with the foreign-object error; the message test moves to two root sources or two blueprint slots |
+
+No documentation sample uses a refused route (each page's samples were run with the probe).
+Two pages describe source registration in prose and need a line each in the implementation
+PR: `docs/concepts/sources.md` (the table of refused source combinations and their remedies)
+and `docs/concepts/identity.md` ("A pipeline or job registers one source object per content
+hash"): one object per slot name, and in a job one slot per source object.
+
+Tests on `main` that hit a refused route but expect `main`'s own refusal there (rows 8, 9,
+30, 36) keep passing only if `main`'s error is raised first: the implementation runs `main`'s
+checks before the new ones. They are
+`tests/test_core/sources/test_source_id_review_findings.py::TestFinding2SourcesSharingASlotName::test_two_sources_with_one_name_are_refused`,
+`tests/test_core/sources/test_source_id_review_findings.py::TestSecondReview3Claims::test_one_name_with_two_schemas_names_both_full_ids`,
+`tests/test_pipeline/test_source_id_conflicts.py::test_same_name_across_kinds_still_collides_at_capture_but_can_bind_separate_slots`
+and
+`tests/test_pipeline/test_source_id_conflicts.py::test_same_slot_name_describes_distinct_derived_sources_with_equal_rows`.
+
+Method: every test file that builds a `Pipeline` or a `PipelineJob` (each file naming
+`Pipeline(`, `PipelineJob`, `from_pipeline` or `SourceNode`, PostgreSQL and SpiralDB
+integration files excepted) ran in one process on `main` at `813c5110` with a probe that
+recorded each capture or `bind` taking a refused route; then `tests/test_docs/test_doc_samples.py`
+ran with the probe in every page's interpreter. 28,980 tests passed; the one failure,
+`test_coalesced_captures_release_duplicate_projections`, was the probe's own (it holds the
+objects that test expects to be released). The probe is not committed.
+
+### 7.2 Public answers that change
+
+`==`, `hash()` and label access keep main's behavior. The developer's November 29, 2026
+membership decision applies as specified in section 2 (4). Rows 42–51 distinguish held
+vertices from foreign objects. A foreign node's adjacency raises `KeyError`.
+
+On main at `39be606a`, two bound jobs instantiated from one blueprint answered `False`
+for `j2.output in j1.dag` and raised `KeyError` for predecessors and successors of
+`j2.output`. These results held with one shared source, separate sources with equal
+content hashes, and sources with different hashes. Two unbound instances answered
+`True`, with one predecessor and no successors for the foreign output. Main's bound
+answers come from the stale hash-key issue described in row 48.
+
+## 8. Snippets and raw results on `main`
+
+Each line is the case body; the result is what `origin/main` printed (rows 1 to 42 at
+`2b4d30dc`, rows 43 to 51 at `813c5110`). In rows 43 to 51, `src(name, base)` is a
+`DictSource` with rows `base` and `base + 1`, and `tpl` is `with tpl: D.pod(src("slot", 0),
+label="output")`.
+
+| # | Snippet | Main result |
+|---|---|---|
+| 1 | `with J: d = D.pod(s, label="d"); P.pod(d, label="p")` | 3 nodes, 2 edges; `d=[6,8]`, `p=[7,9]` |
+| 2 | `with J: D.pod(s, label="d")`, then `with J: P.pod(J.d, label="p")` | 3 nodes; `p=[7,9]` |
+| 3 | `with J: D.pod(s, label="d")` | slot `a`; `d=[6,8]` |
+| 4 | `with J: D.pod(s, label="d1"); D.pod(s, label="d2")` | 2 nodes, label `d1` |
+| 5 | `with J: D.pod(s, label="d"); T.pod(s, label="t")` | 3 nodes; `d=[6,8]`, `t=[9,12]` |
+| 6 | `with J: D.pod(a, label="ra"); D.pod(b, label="rb")`; `J.bind(sources={"a": s, "b": s})` | 4 nodes; `ra=[6,8]`, `rb=[]` |
+| 7 | `with J: D.pod(SourceNode.from_stream(s, name="x")); D.pod(SourceNode.from_stream(s, name="y"))`; bind both to `s` | 4 nodes; `rx=[6,8]`, `ry=[]` |
+| 8 | `with J: D.pod(src("a", 3)); T.pod(src("a", 3))` (also with other rows) | `InconsistentSourceError` |
+| 9 | as 8, the second source with `record_id_columns=["id"]`, in `J` and in `B` | `InconsistentSourceError` (key columns) |
+| 10 | `p = D.pod(s)`; `with J: P.pod(p)` | slot `double:61a…`; `p=[7,9]` |
+| 11 | `p = D.pod(s)`; `with J: P.pod(p, label="p1"); P.pod(p, label="p2")` | 2 nodes, label `p1` |
+| 12 | `p1, p2 = D.pod(s), D.pod(s)`; `with J: P.pod(p1); P.pod(p2)` | 2 nodes, label `p1` |
+| 13 | `p1, p2 = D.pod(src("a", 3)), D.pod(src("b", 8))`; `with J: P.pod(p1); P.pod(p2)` | 4 nodes; `p1=[7,9]`, `p2=[17,19]` |
+| 14 | `p = D.pod(s)`; `with J: T.pod(s); P.pod(p)` | slots `a`, `double:61a…`; 4 nodes |
+| 15 | `pre = T.pod(J.a)`; `with J: P.pod(pre)` | `InconsistentSourceError` (prebuilt stream over slot `a`) |
+| 16 | `with J: D.pod(ArrowTableStream(table, tag_columns=["id"]))` | `SourceSpecMismatchError` (system-tag columns) |
+| 17 | `r = ArrowTableStream(s.as_table(columns={"system_tags": True}), tag_columns=["id"])`; `with J: D.pod(r)` | 2 nodes; `d=[6,8]` |
+| 18 | two one-row slices of 17; `with J: D.pod(r1, label="d1"); D.pod(r2, label="d2")`; also in `B` without system tags | 4 nodes; `d1=[6]`, `d2=[8]` |
+| 19 | the same slice twice as two objects; `D.pod(r1)`; `T.pod(r2)` | 3 nodes, one slot |
+| 20 | `j1 = inst(s)`; `with PipelineJob("outer", ...): P.pod(j1.output)` (also `j1.slot`, also unbound) | `InconsistentSourceError` (slot from outside this job) |
+| 21 | `j1 = inst(s)`; `with B: P.pod(j1.output)` | slot `output:61a…`, 2 nodes |
+| 22 | `j1 = PipelineJob.from_pipeline(tpl)`; `with B: P.pod(j1.output)` | slot `output:285…`, 2 nodes |
+| 23 | `j1, j2 = inst(s), inst(s)`; `with B: P.pod(j1.output); P.pod(j2.output)` | 2 nodes, label `p1` |
+| 24 | `j1, j2 = inst(src("a", 3)), inst(src("b", 8))`; `with B: P.pod(j1.output); P.pod(j2.output)` | 4 nodes; slots `output:61a…`, `output:685…` |
+| 25 | `j1 = inst(s)`; `with B: T.pod(j1.slot)` | slot `slot:d6645…`, 2 nodes |
+| 26 | `j1 = PipelineJob.from_pipeline(tpl)`; `with B: T.pod(j1.slot)` | slot `slot:c24c9…`, 2 nodes |
+| 27 | `j1, j2 = inst(src("a", 3)), inst(src("b", 8))`; `with B: D.pod(j1.slot); D.pod(j2.slot)`; job from `B` bound by slot name | 4 nodes; `from_first=[6,8]`, `from_second=[16,18]` |
+| 28 | `j1 = inst(s)`; run, save, `loaded = PipelineJob.load(...)`; `with B: P.pod(loaded.output)` | slot `output:61a…`; saved bytes equal row 21's |
+| 29 | `j1 = inst(s)`; run; `with J: P.pod(j1.output.as_source())` | slot `semantic_v1:61a…`; `p=[7,9]` |
+| 30 | `d1, d2 = j1.output.as_source(), j1.output.as_source()`; `with J: P.pod(d1); P.pod(d2)` | `InconsistentSourceError` |
+| 31 | `with J: P.pod(loaded.output.as_source())` | `SourceSpecMismatchError` (system-tag columns) |
+| 32 | `c = CachedSource(s, cache_database=db)`; `with J: D.pod(c)` | slot `a`; `d=[6,8]` |
+| 33 | `with J: D.pod(c); T.pod(s)` | `InconsistentSourceError` |
+| 34 | `with B: D.pod(SourceNode.from_stream(s, name="x")); T.pod(SourceNode.from_stream(s, name="x"))` | 3 nodes, slot `x` |
+| 35 | as 34 with `src("a", 3)` and `src("b", 8)` | 3 nodes, slot `x`; same bytes as 34 |
+| 36 | as 34 with a second source of another schema | `InconsistentSourceError` (different schemas) |
+| 37 | `with B: D.pod(SourceNode.from_stream(src("b", 8), name="x")); T.pod(src("x", 3))` | 3 graph nodes, 4 saved nodes, slots `x`, `x` |
+| 38 | as 37 in `J` | 4 graph nodes, 3 saved nodes, slots `x`, `x`; `d=[]`, `t=[9,12]` |
+| 39 | `with B: D.pod(src("a", 3), label="a")` | labels `a`, `a_1` |
+| 40 | `with J: MergeJoin()(s, s)` | 2 nodes, 1 edge |
+| 41 | `with J: D.pod(s, label="r1"); D.pod(s, label="r2"); D.pod(s)` | one node, label `r1` |
+| 42 | `j1, j2 = inst(src("first", 3)), inst(src("second", 7))`; `j2.output in j1.dag`; `j1.dag.predecessors(j2.output)` | `False` (both forms); `KeyError` |
+| 43 | `a, b = inst(src("first", 3)).output, inst(src("second", 7)).output`; `a == b`, `hash(a) == hash(b)`, `b in j1.dag`, `j1.nodes["output"] is a`, `j1.dag.predecessors(b)`, `j1.dag.successors(j2.slot)` | `False`, `False`, `False`, `True`, `KeyError`, `KeyError`; content hashes differ, pipeline hashes equal |
+| 44 | as 43 with `s = src("same", 3)` for both | `True`, `True`, `False` (and `a in j1.dag` `False`), `True`, `KeyError`, `KeyError`; content hashes equal |
+| 45 | as 43 with two objects `src("same", 3)` | as 44 |
+| 46 | as 43 with `inst()`, `inst()` | `True`, `True`, `True` (and `a in j1.dag` `True`), `True`, 1 predecessor, 1 successor |
+| 47 | as 43 with `inst(src("first", 3))`, `inst()` | `False`, `False`, `False`, `True`, `KeyError`, `KeyError` |
+| 48 | `j = inst(src("first", 3))`; `j.output in j.dag`, `j.slot in j.dag`, `any(n is j.output for n in j.dag.nodes())`, `j.dag.predecessors(j.output)` | `False`, `False`, `True`, `KeyError` |
+| 49 | `with J: D.pod(src("a", 3), label="d")`; `J.d in J.dag`, `J.nodes["d"] is J.d` | `True`, `True` |
+| 50 | `j = inst()`; `j.output in j.dag`; `j.bind(sources={"slot": src("first", 3)})`; `j.output in j.dag` | `True`, `True` |
+| 51 | `tpl.output in tpl.dag`; `inst().output in tpl.dag` | `True`, `True` |
+
+Every row was run for this document. On the head at `7e393d02`, rows 43 to 47 answer `==`
+`True`, `in` `True` and adjacency without error in every case, row 48 answers `True`, and
+`job.nodes[label]` raises `KeyError` (rows 43 to 49), because `job.nodes` is keyed by graph
+key there.
+
+The follow-up examples use the same notation:
+
+| Rows | Example | Result |
+|---|---|---|
+| 53–54 | `D.pod(SourceNode.from_stream(s, name="a"), label="d")` and `T.pod(s, label="t")`, in either order | Main returns `d=[]` and `t=[9,12]` on `[3,4]`. Step 3 refuses the second capture. |
+| 55–59 | In another live graph capture `tpl.output`, `tpl.slot`, the stream returned when declaring `tpl.output`, or a projection over `tpl.output`. Test both node and slot from a loaded blueprint. | The caller gets the foreign-slot error in section 5.1. |
+| 60 | `graph.record_function_pod_invocation(D, object())` | Unknown input type error. |
+| 61–62 | Reopen a loaded graph and capture a step. | Loaded receiver error. |
+| 63 | Capture a side-effect pod over `s`. | Delivers `3` and `4`. |
+| 64 | Read a stored result through `as_source(source_id="derived", tags_as_data={"id": "tag_copy"})` and add one to `tag_copy`. | `[2,3]`. |
+| 65 | Capture distinct steps under `d`, one over `a` and one over a projection of `b`. | Both run and are indexed under their original content-hash-ordered labels `d_1` and `d_2`. |
+| 66 | Repeat 53 or 54 with `name="alias"`. | Both graph types refuse, naming both slot names. |
+| 67 | Use a projection outside the graph and the equivalent step inside it. Create the alias at capture, while binding before or after compile, or while restoring a saved job. | The legacy-identity error precedes recording or binding, inside or outside a recording block. |
+| 68 | Declare the same leaf as `a` and `alias`, then pass the leaf directly as `a`. | Refuses with the two-slot diagnostic before adding the third branch. |
+| 69 | Try each foreign form through instantiation, bind and the setter. | Refuses before changing bindings. |
+| 70 | Capture inside `job.pipeline` from a separate root or its own slot. | Refuses and keeps the original branch on compile. |
+| 71 | Capture one declaration in two receivers sequentially or under stacked contexts. | Sequential capture refuses in the second receiver, before or after compile. Stacked capture refuses without changing either graph. |
+| 72 | Clash a natural implicit slot name against a step label in both orders and try a numbered label. | Refuses the second object and preserves existing entries. |
+| 73 | Bind standalone function and side-effect nodes over independent streams. | Narrower reads keep metadata and load-only runs refuse delivery. |
+| 74 | Capture separately built `double` streams over one source, labelled `first` and `second`. Feed both into `plus` and feed the second result into `finish`. | The second capture raises with both inferred slot names. The first result remains `[7, 9]`. |
+| 75 | Use a matching schema example or schemas alone, capture in either order, and bind distinct inputs together or separately to an unbound instance. | Both branches return main's rows in sync and async. |
+| 76 | Access `Pipeline.graph` or `PipelineJob.graph` before or after compile. | **Removed (developer, 2026-11-29)**. The DAG and label mapping expose the compiled topology and nodes. |
+| 77 | Count the slot and step records offered by successive captures. | One slot and one step per branch. |
+| 78 | Attempt to edit through the former public NetworkX graph. | **Removed (developer, 2026-11-29)**. The pipeline API is the supported way to change a pipeline. |
+| 79 | Bind a replacement source and an incompatible pipeline or result database while a function is still pending. Repeat after compiling an independent branch. | Failure preserves the job’s public state and registries. A subsequent valid binding compiles and runs. |
+| 80 | Use the public vertex collection with main’s `dict_keys` operations, and pass a held vertex to NetworkX’s singleton path check. | Main’s collection results and a successful path check. |
+| 81 | Insert a foreign compiled node or invocation stream with `dag.add_node` or `dag.add_edge`, then offer it to capture. | The edit raises `TypeError` before changing the topology. Capture raises the diagnostic from row 55 or 57. |
+| 82 | Subclass `Join` and capture it over `(a, b)` then `(b, a)` using the same roots. Read `adjusted` from the second call. | The run computes two rows, `adjusted` exposes `[206, 307]` in either mode, and a load-only run exposes the same rows. Main and step 3 save identical bytes. |
+| 83 | Override `argument_symmetry` with a tuple and select its first operand. Reverse the two inputs with distinct values. | Both graph kinds expose `first=[6,8]` and `second=[16,18]` in either mode. Main exposes only `first`. |
+| 84 | Submit the mismapped outputs via a new invocation graph or a replacement of a valid export. | Both receivers reject the foreign output as in row 55. The unmodified export reconstructs all three vertices. |
+| 85 | In a second blueprint capture, compare the held compiled step and the original invocation stream. | The compiled step is refused and the saved blueprint is byte-identical before and after that capture. The original invocation stream saves main's bytes and both revisions expose `[7, 9]`. |
+| 86 | Capture from a standalone join descriptor and bind its implicit slot to a concrete source. | Blueprint topology and saved bytes equal main's. Both modes expose `[8,9]`. |
+| 87 | Hold a projection over a standalone join and attempt a same-schema rewire or a rewire that adds a data column. Separately, refresh the descriptor's schema and exit an empty capture block. | The setter refuses both rewires. The context exit refuses the changed schema. Both errors preserve the saved blueprint. Early and late consumers still read the original slot in sync and async. |
+
+## 9. Which rule would have prevented each review's finding
+
+| Review and finding | Wrong result without an error? | Rule |
+|---|---|---|
+| First, 1: one object bound to two slots doubled the status rows | A stored value moved | R2: refused in step 3 (Q4); R3: the run is grouped as `main` groups it |
+| First, 2: DAG adjacency returned tuples | No (public type) | Property test: listings equal `main`'s |
+| First, 3: a custom operator's key changed after a rebind and recompile | No (addresses moved) | R3: keys fixed at capture |
+| Second, 1: saving a blueprint after a rebind rewrote its wire key | A saved value moved | R3: the wire key is read at capture and kept |
+| Second, 2: the DAG lost a vertex through `dict.fromkeys` over nodes | Listing lost a node | R2: no node `__eq__` or `__hash__` in the graph layer |
+| Third, 1: two raw streams merged before they were named | **Yes** | R1: names first, then comparison |
+| Third, 2: a saved blueprint took the wrong representative and repeated an edge | A saved value moved | R3: saved as `main` projects it |
+| Third, 3: a node of another instance was looked up by content | No (membership) | Section 2 (4): public object membership is refused (Q5) |
+| Fourth: slots of two instances merged; one branch ran on the other source | **Yes** | R1: foreign objects are refused in a `Pipeline` (Q1) |
+| This document, row 38: a bound root source merged into an unbound slot of the same name | **Yes** | R2: one leaf object per slot name (Q3) |
+
+## 10. Decided by the worker, for the developer to check
+
+The developer's answers left these points open; each was decided conservatively:
+
+1. **Q4 applies to jobs only.** One source object declared under two explicit names in a
+ *blueprint* (`SourceNode.from_stream(s, name="x")` and `name="y"`) stays accepted: a
+ blueprint declaration binds nothing, and the defect of rows 6 and 7 is a run reading one
+ bound object through two slots. Binding the instance's two slots to one object is refused
+ at `bind` (row 6). The blueprint part of
+ `tests/test_hashing/test_identity_chains.py::test_slots_keep_their_names_across_bindings`
+ and `test_unbound_blueprint_names_all_upstream_slots` stay valid.
+2. **Where Q4 is checked in a job.** At capture (the step that brings the second slot), at
+ `bind` on the state after the whole call (so a one-call swap or rotation is accepted),
+ at each `bound_source` setter call (so a rotation one setter at a time is refused at the
+ step that puts one object on two slots), at `from_pipeline(..., sources=...)`, and at
+ `PipelineJob.load`: a saved file whose slots hold identical source configs (which `main`
+ rebuilds as one object) is refused with the same error, since two rebuilt objects would
+ be refused by PR 577.
+3. **Standalone job slots and prebuilt streams over a foreign object.** A `SourceJobNode`
+ that belongs to no job (row 52) is refused in a `Pipeline` as another job's slot is, as
+ `main` refuses it in a `PipelineJob`. A stream built outside the graph over another job's
+ node or slot is refused too. This mirrors `main`'s `PipelineJob` stopgap.
+ `node.as_source()` ends the walk and stays accepted (row 29).
+4. **The leaf object of an explicit slot** declared from a stream is that stream (section 4),
+ so row 34 (one stream declared twice under `x`) stays one slot and row 35 (two streams) is
+ refused.
+5. **Foreign object membership is refused** (section 7.2). The developer accepted the
+ breaking change on November 29, 2026.
+6. **Row 4, 11 and 41 labels** follow Q6 (b): `main`'s smallest label in step 3, the most
+ recent explicit label in step 4.
+
+### Decisions for the developer
+
+**Rows 53–54.** The developer confirmed the refusal in either order on November 29, 2026.
+ITL-1553 tracks acceptance with one bound slot and both branches running once source and
+stream equivalence is defined. The third
+review tested both orders in sync and async, with and without compilation between
+captures. Main has two live slots named `a`, leaves the declaration unbound and
+reports a partial run. It stores two triple results and two corresponding pipeline
+records, with `declared=[]` and `direct=[9,12]`. PR head `afd1c7ad` completed both
+branches, added `declared=[6,8]` and stored two double results and their pipeline
+records. The saved job changed from 6,857 to 6,841 bytes with version and run ID
+pinned. The run URI changed from `job@af03287e39c266ad` to `job@3dd6f83f7f5c657e`.
+CSV/Delta reads in both directions reproduced the writer’s stored rows. Approving
+the alternative would accept the saved-byte, run-URI and stored-row changes.
+
+**Row 85.** Step 3 refuses late capture from a compiled blueprint step. Enabling the
+direct link would save three vertices with an edge from `first` to `second`.
+Main saves four vertices with a separate implicit slot feeding `second`. In the sync and async review fixture,
+with the writer version pinned, the saved blueprint would change from 6,317 to
+5,114 bytes. With only the original source bound, `second` would return `[7, 9]`
+instead of `[]`. The original invocation stream already saves identical
+5,123-byte blueprints and returns `[7, 9]` on both revisions.
+
+**Row 87.** Step 3 keeps a captured blueprint's slot declaration and wire keys
+fixed. Replacing descriptor inputs requires a new descriptor. Reassigning the
+same input objects in the same positions has no effect. If current source metadata
+changes a held slot's schema, recompilation raises before replacing the compiled
+graph. A future alternative could snapshot the captured declaration and project
+downstream legacy keys through the original input identities, allowing the live
+descriptor to be rewired independently. That would require defining which
+downstream captures use the snapshot and which use the new descriptor identity.
+Refreshing a held slot in place would change the binding contract and stored
+addresses. Even a schema-preserving rewire can change a downstream wire key while
+keeping the same topology and rows.
+
+## 11. Questions and the developer's answers (2026-11-29)
+
+**Q1. Is capturing a node or slot of another job into a blueprint supported in 0.4.0?**
+Answer, 2026-11-29: **(b) refuse**. "agree on refusing this right now until we can properly
+and consistently name the slot." Refused in a `Pipeline` with `main`'s `PipelineJob` error and
+remedy (pass the source itself, or `node.as_source()`). Turned on again with consistent slot
+naming (ITL-1700). Rows 21 to 28 change.
+
+**Q2. If Q1 is (a): does a bound slot of another instance enter as its slot name or as an
+implicit slot of its content?** Answer, 2026-11-29: **moot** (Q1 is (b)).
+
+**Q3. An explicit slot and a root source that take the same name (rows 37 and 38).** Answer,
+2026-11-29: **(a) refuse at capture**, at the step that brings the second leaf, naming the
+slot and both leaves. "I agree that should have been recognized as a clear error at the step
+T.pod(src("x",3)) as there is already a bound slot "x" and the new src is not the same as the
+currently bound source (what constitutes equivalent is a subject of a future case but at
+least judging by not being equal instance is conservatively safe although a bit too
+refusing)."
+
+**Q3b. Is one rule enough: a slot name has exactly one leaf object?** Answer, 2026-11-29:
+**(a)**. "I agree with (a) -- one slot should be bound to exactly one source identity. Until we
+make equivalence relationship between sources more well-established ... we should determine
+identity of a source by object instance." Rows 12, 19 and 35 change. The follow-up is ITL-1553
+(sources and streams answer whether two objects are the same source).
+
+**Q4. One source object on two slots (rows 6 and 7).** Answer, 2026-11-29: **(b) refuse until
+step 6**. "OK for 4 I agree to refuse it until the proper fix comes in." This amends D31's
+choice to keep `main` there.
+
+**Q5. Is an object recorded by another graph a member of this graph (row 42)?** Answer,
+2026-11-29: initially **(a)**. The later decision on the same day refuses `in` until
+membership semantics are settled and accepts the breaking change.
+
+**Q6. The most recent explicit label changes saved labels in rows 4, 11, 12, 23 and 41.**
+Answer, 2026-11-29: **(b)**. "Q6 ok with (b) -- and later change the saved labels." `main`'s
+label choice stays in saved files in step 3; step 4 brings the most recent explicit label.
+
+**On identity (D50 (a), with a condition).** Answer, 2026-11-29: "How we refer to it vs how
+we establish equivalence are two separate things -- we refer to and talk about the node object
+via the label access. However the 'identity' of that node should be determined by node content
+hash in pipeline job"; "in Pipeline template, a node should be identified by their node hash";
+"It's just that membership must be more carefully taken"; and the total identity of
+structural, source and name chains, with "'In' should be very carefully used and likely we
+should provide more descriptive membership methods". Recorded in sections 2 and 3.
+
+## 12. Test plan
+
+One named test per row through the public API, in `tests/test_pipeline/test_capture_boundary.py`
+and, for the cross-revision row 65, `tests/test_pipeline/test_step3_main_compatibility.py`.
+Each asserts what its row decides: the slot names, the graph keys (equal or different as the
+"Same node" column says), the rows after a run where the graph runs, the saved bytes against
+a file frozen from `main` (labels as `main`'s, Q6), or the refusal's error type and the slot
+and leaves its message names. A refused row also asserts that nothing was recorded or bound
+(the graph's nodes, edges, labels, capture registries and bindings equal those before the refused call). Each row runs
+sync and async where the graph runs.
+
+| Row | Test | Decision asserted |
+|---|---|---|
+| 1 | `test_r01_step_inside_graph` | Accept |
+| 2 | `test_r02_own_node_later_capture` | Accept |
+| 3 | `test_r03_root_once` | Accept |
+| 4 | `test_r04_same_object_same_pod` | One node, label `d1` |
+| 5 | `test_r05_same_object_two_pods` | Accept |
+| 6 | `test_r06_one_object_two_slots_bind_refused` | Refused at `bind`; both slots keep their bindings |
+| 7 | `test_r07_one_object_two_slots_capture_refused` | Refused at the step bringing `y` |
+| 8 | `test_r08_equal_content_objects_refused` | `main`'s error |
+| 9 | `test_r09_one_name_other_keys_refused` | `main`'s error |
+| 10 | `test_r10_prebuilt_once` | Accept |
+| 11 | `test_r11_prebuilt_same_object_twice` | One node, label `p1` |
+| 12 | `test_r12_prebuilt_equal_builds_refused` | Refused, names the slot and both streams |
+| 13 | `test_r13_prebuilt_other_content` | Accept |
+| 14 | `test_r14_prebuilt_and_its_root` | Accept |
+| 15 | `test_r15_prebuilt_over_own_slot_refused` | `main`'s error |
+| 16 | `test_r16_raw_without_system_tags_refused` | `main`'s error |
+| 17 | `test_r17_raw_once` | Accept |
+| 18 | `test_r18_raw_two_distinct` (job and blueprint) | Accept |
+| 19 | `test_r19_raw_two_equal_refused` | Refused |
+| 20 | `test_r20_other_job_into_job_refused`, `test_executed_foreign_slot_refused_at_capture` | `main`'s error for direct foreign slots and nodes. Both receivers also refuse slot outputs backed by a table or buffered rows. |
+| 21 | `test_r21_other_job_bound_node_refused` | Refused, `main`'s text for a pipeline |
+| 22 | `test_r22_other_job_unbound_node_refused` | Refused |
+| 23 | `test_r23_instances_same_binding_refused` | Refused |
+| 24 | `test_r24_instances_other_binding_refused` | Refused |
+| 25 | `test_r25_other_job_bound_slot_refused` | Refused |
+| 26 | `test_r26_other_job_unbound_slot_refused` | Refused |
+| 27 | `test_r27_instance_slots_other_binding_refused` | Refused |
+| 28 | `test_r28_loaded_job_node_refused` | Refused; also a prebuilt stream over it |
+| 29 | `test_r29_derived_source` | Accept |
+| 30 | `test_r30_two_derived_objects_refused` | `main`'s error |
+| 31 | `test_r31_loaded_derived_source_refused` | `main`'s error |
+| 32 | `test_r32_cached_source` | Accept |
+| 33 | `test_r33_cached_and_wrapped_refused` | `main`'s error |
+| 34 | `test_r34_slot_name_same_leaf` | Accept, one slot |
+| 35 | `test_r35_slot_name_other_leaf_refused` | Refused |
+| 36 | `test_r36_slot_name_other_schema_refused` | `main`'s error |
+| 37 | `test_r37_slot_and_root_name_blueprint_refused` | Refused at the root's step |
+| 38 | `test_r38_slot_and_root_name_job_refused` | Refused at the root's step |
+| 39 | `test_r39_slot_name_equals_step_label`, `test_r39_automatic_step_shares_its_new_slot_name` | Main’s exact slot and step labels, and both run modes |
+| 40 | `test_r40_merge_join_repeated_input` | Accept |
+| 41 | `test_r41_label_kept_as_main` | One node, label `r1` |
+| 42 | `test_r42_foreign_object_lookup` | Object membership refused. Foreign adjacency raises `KeyError`. |
+| 43 | `test_r43_instances_different_sources` | Object membership refused. Different nodes compare unequal and have distinct hashes. Label access and foreign adjacency follow row 42. |
+| 44 | `test_r44_instances_same_source_object` | Object membership refused. Equal nodes retain equal hashes. Own adjacency answers and foreign adjacency raises `KeyError`. |
+| 45 | `test_r45_instances_equal_source_objects` | Object membership refused. Equality, hashing and adjacency follow row 44. |
+| 46 | `test_r46_unbound_instances` | Object membership refused. Unbound nodes compare equally. Foreign adjacency raises `KeyError`. |
+| 47 | `test_r47_bound_and_unbound_instance` | Object membership refused. Bound and unbound nodes compare unequally. Foreign adjacency raises `KeyError`. |
+| 48 | `test_r48_own_node_after_from_pipeline_bind` | Own-node membership and adjacency answer after instantiation and binding. |
+| 49 | `test_r49_own_node_captured_job` | Own-node membership and adjacency answer for a directly captured job. |
+| 50 | `test_r50_own_node_unbound_then_bind` | Own-node membership and adjacency answer before and after binding. |
+| 51 | `test_r51_blueprint_membership` | The blueprint accepts its own node and refuses the instance’s node. |
+| 52 | `test_r52_standalone_job_slot_into_blueprint_refused` | Refused |
+| 53–54 | `test_r53_r54_mixed_capture_refused` | Second capture refused in both graph types and both orders, with and without compile between calls. ITL-1553 tracks acceptance. |
+| 55 | `test_r55_foreign_blueprint_node_refused` | Foreign-object refusal |
+| 56 | `test_r56_foreign_blueprint_slot_refused` | Foreign-object refusal |
+| 57 | `test_r57_foreign_blueprint_invocation_stream_refused` | Foreign-object refusal |
+| 58 | `test_r58_prebuilt_over_foreign_blueprint_refused` | Foreign-object refusal |
+| 59 | `test_r59_loaded_blueprint_object_refused` | Foreign-object refusal |
+| 60 | `test_r60_unknown_capture_input_refused` | Unknown-input refusal |
+| 61 | `test_r61_capture_into_loaded_blueprint_refused` | Capture refusal |
+| 62 | `test_r62_capture_into_loaded_job_refused` | Capture refusal |
+| 63 | `test_r63_side_effect_over_root` | Accept, both deliveries |
+| 64 | `test_r64_stored_source_with_promoted_tags` | Accept, both rows |
+| 65 | `test_r65_duplicate_explicit_labels_and_public_lifecycle_match_main` | Main's labels, listings, rows and observer addresses |
+| 66 | `test_r66_same_leaf_different_mixed_slot_names_refused` | Refused in both orders |
+| 67 | `test_r67_slot_and_step_legacy_alias_refused`, `test_bind_namespace_cross_product`, `test_r67_rebind_checks_current_step_identity`, `test_r67_binding_checks_pending_capture`, `test_r67_instantiation_checks_bound_execution_roles`, `test_r67_load_checks_restored_execution_roles` | Both capture orders and receivers, pending and compiled binding routes, and a warmed step identity after rebinding |
+| 68 | `test_r68_implicit_name_matches_one_of_two_explicit_slots` | Refused before a third branch |
+| 69 | `test_r69_foreign_live_binding_refused`, `test_executed_foreign_slot_refused_at_binding`, `test_job_binding_refuses_descriptor_rewire_to_live_slot`, `test_detached_binding_descriptor_can_be_rewired` | All three binding entry points refuse foreign live inputs, including executed slot outputs. A live descriptor's proposed slot dependency is refused. After rebinding detaches the descriptor, both run modes preserve the rewired descriptor's rows and the receiving job's replacement rows, as on main. |
+| 70 | `test_r70_capture_into_job_derived_blueprint_refused` | Refused and compiled blueprint preserved |
+| 71 | `test_r71_foreign_declaration_refused_at_capture`, `test_r71_stacked_capture_refuses_without_recording` | Sequential and stacked receivers, with graph and registry snapshots |
+| 72 | `test_r72_slot_and_step_name_collision_refused`, `test_r72_generated_step_name_is_reserved` | Refused before changing the graph |
+| 73 | `test_meta_columns_of_a_narrower_stream_are_kept`, `test_a_load_only_run_refuses_a_source_slot_bound_to_a_side_effect_node` | Binding preserves metadata and load-only runs refuse delivery |
+| 74 | `test_r74_equal_prebuilt_streams_with_different_inferred_names`, `test_r74_invocation_import_validates_its_slots`, `test_r74_prepared_invocation_validates_current_records`, `test_execution_identity_matrix` | Both receivers refuse the alias before publication, including imported slots and delayed recording. The first branch keeps main's rows in both modes. |
+| 75 | `test_r75_schema_only_slot_binds_independently` | Main's rows with a matching example or schemas alone, both capture orders and both binding routes |
+| 76 | `test_public_graph_attribute_is_removed` | **Removed (developer, 2026-11-29)**. Label access and DAG adjacency remain available. |
+| 77 | `test_r77_capture_reads_each_invocation_a_constant_number_of_times` | Linear execution-role record visits during capture |
+| 78 | `test_public_graph_attribute_is_removed` | **Removed (developer, 2026-11-29)**. The former edit surface is gone. |
+| 79 | `test_r79_pending_bind_storage_refusal_is_atomic` | The proposed pipeline or result database is refused before sources, database views or job registries change. |
+| 80 | `test_r80_public_dag_vertex_operations_match_main`, `test_public_dag_refuses_internal_key_strings` | The vertex collection matches main’s dictionary-key operations on held vertices. Internal key strings are absent from public membership queries and raise `KeyError` in vertex lookups. |
+| 81 | `test_r81_public_dag_rejects_foreign_insertions` | Both receivers reject foreign vertex and edge insertion before mutation and keep the capture diagnostic. |
+| 82 | `test_r82_reversed_custom_join_keeps_downstream_rows`, `test_custom_operator_execution_matrix` | Both run modes keep the second call's downstream rows, and job files match main. |
+| 83 | `test_r83_ordered_custom_operator_keeps_both_branches`, `test_custom_operator_execution_matrix`, `test_saved_jobs_read_each_others_stores` | Reversal of a declared tuple produces a separate branch. Both revisions read the results in either revision's saved job. |
+| 84 | `test_r84_import_refuses_a_foreign_invocation_output` | A foreign output cannot claim a prior output position in either receiver. |
+| 85 | `test_r85_refuses_late_capture_of_compiled_blueprint_step`, `test_blueprint_capture_boundary_against_main` | Both modes verify the atomic refusal and compare the original invocation stream's topology, rows and bytes against main. |
+| 86 | `test_blueprint_capture_boundary_against_main` | A standalone descriptor's topology, rows and saved bytes match main in both modes. |
+| 87 | `test_r87_refuses_rewiring_a_captured_descriptor`, `test_r87_compile_refuses_a_changed_slot_schema` | Both modes refuse identity-changing rewires and schema-changing recompiles, preserve saved bytes, and run through the original slot. |
+
+Property tests:
+
+- `test_object_membership_requires_label_access` checks foreign streams, compiled nodes
+ and invocations on both receivers. Label lookup and label membership remain usable.
+- `test_graph_layer_uses_no_node_equality`: replace `__eq__` and `__hash__` of `StreamBase`,
+ `SourceNodeBase` and `PodInvocation` with functions that raise, except inside the one
+ `main`-compatible projection used for saving and the run URI, and when comparing
+ the public `frozenset` results. Run the original accepted capture matrix
+ through capture, compile, bind, run, save, load and `clear_cache`.
+- `test_public_listings_equal_main`: for every accepted row, `job.nodes`, `dag.nodes()`,
+ `dag.edges()`, adjacency, `source_pods` and the saved file equal those of the frozen `main`
+ output, compared as sets of labels and slot names (order is not a result). The row 65
+ probe also compares lookup, ancestor and degree queries, stored bytes, and observer
+ start and end addresses and run URIs against `origin/main` in independent interpreters.
+ It covers capture, compile, run, rebind, load and cache clearing, with sync and async runs.
+- `test_public_equality_equals_main`: for rows 43 to 51, `==` and `hash()` equal `main`'s.
+- `test_keys_fixed_at_capture`: for rows 3, 34 and a custom operator, the graph keys and
+ wire keys are equal before and after a bind, a rebind and a recompile.
+- `test_capture_namespace_cross_product` crosses every ordered pair of fourteen
+ capture kinds and reuses the exact same object for each kind. It runs in sync
+ and async modes for 420 cases. Each accepted pair checks both branches against
+ main's non-empty rows. Each rejected pair checks the named capture error and
+ the preserved graph. A foreign object offered first is refused before it can
+ hold the name. In the matrix, hash-derived candidates share a test name so
+ dissimilar kinds can clash. Rows 12, 19, 67 and 72 exercise natural names and
+ hashes without overriding name derivation.
+- `test_bind_namespace_cross_product` covers slot/step aliases, one object on two slots
+ and equal or distinct prebuilt and raw streams, through instantiation, bind and setter.
+ These 36 sync and async cases preserve
+ registries, sources, modification times, the database and the previous branch outputs.
+- `test_execution_identity_matrix` adds 504 cases for inferred, explicit, and mixed
+ names, roots, prebuilt streams, and declarations, equal and distinct content,
+ both orders, both graph kinds, and sync and async. It covers direct capture,
+ instantiation from a blueprint, batch binding, and slot assignment. Accepted
+ cases compare both downstream branches with main. Refused cases compare the
+ prospective operation's before and after state.
+ Row 75 adds 16 cases spanning declarations from matching examples or schemas alone,
+ both capture orders, immediate or later binding, and both run modes.
+- `test_custom_operator_execution_matrix` adds 96 cases for six user-defined
+ commutative, ordered, and unary operators, including symmetry and identity
+ overrides. It crosses both input orders, shared and distinct sources, direct
+ job capture and live blueprints, and sync and async. Each successful live and
+ load-only run exposes main's two downstream rows. Saved and re-saved jobs
+ compare byte for byte with main for commutative and unary operators. Ordered
+ cases verify distinct reversed vertices and byte-stable re-saves because main
+ used commutative hashes for these operators.
+- The 48 mutation cases cross rewire, bind, rebind and recompile with a new
+ slot or step, distinct or equal legacy identities, and identities that move
+ away from their previous value. The five matrices cover 1,104 cases.
+- The boundary matrices add 14 cases covering ordered branches, foreign
+ invocation substitutions, and late and standalone blueprint captures.
+ Six Delta store cases verify both read directions, in both run modes, for
+ functions and for commutative and ordered custom operators. Function and
+ commutative job bytes match across revisions.
+- Refused capture rows compare snapshots with `refused` or equivalent assertions,
+ covering graph nodes and edges, capture registries, labels and bindings. Stacked tracker
+ refusals compare both receivers and show that the declaration can be used afterward.
+
+## 13. What steps 4, 5 and 6 change
+
+**Step 4** (saved files carry the new hashes). The "Saved" column changes for every accepted
+row: the wire key becomes the graph key, and a saved slot records its name and its source
+identity. Saved labels take the most recent explicit label (rows 4, 11 and 41; Q6). The slot
+names and the "Same node" column do not change. Implicit names still follow D43.
+
+**Step 5** (the switch). Content digests move, so every implicit name `:`
+(rows 10, 11, 13, 14, 17 and 18) changes. ITL-1700 decides content-independent names before
+then or with it, and with them turns rows 21 to 28 and 52 on again.
+
+**Step 6** (lift the two-slot refusals).
+- Rows 6 and 7: accepted; both branches run; equal-content nodes write if missing (DQ1).
+- Rows 8, 30 and 33: two equal objects under one slot name refer to one slot and are
+ accepted (section 6 of the three-chain document), once ITL-1553 defines when two objects
+ are the same source. Rows 12, 19 and 35 follow the same rule. Under differently named slots,
+ two equal objects are accepted as two slots.
+- Row 9 stays refused while the two readings take one slot name (ITL-1506).
+- Row 15 (a prebuilt stream over the job's own slot) stays refused until capture can match
+ the slot (ITL-1470, ITL-1387).
+- Rows 37 and 38 stay refused: no change is planned.
diff --git a/docs/reference/hashing.md b/docs/reference/hashing.md
index edb21d4c0..427e28bf3 100644
--- a/docs/reference/hashing.md
+++ b/docs/reference/hashing.md
@@ -94,6 +94,7 @@ Hash labels:
| `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 `(pipeline_hash, source_chain)` for a stream, invocation or node, with both hashes labelled | `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` |
+| `legacy_graph_key_v1` | SHA-256 of the canonical tuple of the pipeline hash, slot name if any, and positioned upstream addresses | `_LEGACY_GRAPH_KEY_LABEL`, `core/identity_chains.py` |
| `sha256` | the file content hash: SHA-256 of the file's bytes | `SHA256_ALGORITHM`, `hashing/hash_utils.py` |
Where a hash appears, and in which form:
@@ -315,10 +316,13 @@ combines the pipeline hash and the source chain for streams, invocations and nod
The combined hash carries the label `content_hash_v1`. 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. Pipeline hashes and capture keys
-include every commutative input occurrence (ITL-1590). Stored table paths use the
-pipeline hash.
+unbound. Orcapod uses the combined hash for stored node rows and the pipeline
+hash for stored table paths. Pipeline hashes include every commutative input
+occurrence (ITL-1590). In-memory topology uses node hashes, and saved blueprints
+keep their capture-time wire keys. DAG adjacency resolves the receiving graph's
+own node objects. Use `job.nodes[label]` or `job.` to look up a node.
+The public DAG accepts membership queries for its own nodes. A foreign node,
+stream, or invocation raises `UndefinedGraphMembershipError`.
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
@@ -387,7 +391,7 @@ test session with `-p tests.test_hashing.hash_site_trace`.
| value handlers with an ignore list | wrap the value digests above | the type's label | top level, nested, Arrow cell | `logical_types/ignore_list.py:IgnoreListHandler.handle`, `logical_types/ignore_list.py:IgnoreListHandler.hash_ignoring` |
| parse a stored hash | `":"` or `b":" + digest` | the stored label | saved jobs and pipelines, proxies, a node's saved run hash, a cached output hash | `types/__init__.py:ContentHash.from_string`, `types/__init__.py:ContentHash.from_prefixed_digest` |
| folds of `Batch` / `GroupBy` | the canonical JSON list of a group's member values, for each system tag | SHA-256 hex after the operation's label: `batch_v1` (`batch.py`), `group_v1` (`group_by.py`); one helper | folded source id and record id | `utils/arrow_utils.py:fold_system_tag_values` |
-| run snapshot | sorted labelled sink hashes | SHA-256 hex, 16 digits | the run URI `@` (a name) | `pipeline/job.py:PipelineJob._prepare_run`, `pipeline/job.py:PipelineJob._prepare_run..` |
+| run snapshot | sorted sink content hashes from the legacy execution projection | SHA-256 hex, 16 digits | the run URI `@` (a name) | `pipeline/job.py:PipelineJob._project_run`, `pipeline/job.py:PipelineJob._project_run..` |
| user-class identity | a class's identity record | SHA-256 hex prefix | extension name `name@` (a name) | `logical_types/user_class_identity.py:identity_string` |
| database registry key | a database config, canonical JSON | SHA-256 hex, 8 digits | `db_` key in a saved job (a name) | `pipeline/serialization.py:DatabaseRegistry._make_key` |
| SpiralDB schema table digest | the scope and the rows of a dataset's schema table, canonical JSON with the stored schema bytes | SHA-256 hex | completion marker of the schema table (a checksum of stored rows) | `databases/spiraldb_schema_table.py:rows_digest` |
@@ -410,7 +414,7 @@ test session with `-p tests.test_hashing.hash_site_trace`.
| record-id preimage | the recording node's content hash, the row's instance id | the pipeline record id | `b":" + digest` | `core/row_ids.py:record_id_preimage` |
| operator-cache row | the node content hash (`content_hash_v1`) | `_record_hash` | `b":" + digest` | `core/nodes/operator_node.py:OperatorJobNode._store_output_stream` |
| raw-stream tie-break | the Arrow hash (`arrow_v1`) of each row of a tie group | the canonical row order of a raw stream's identity table (compared as bytes, then the table is hashed whole) | `b":" + digest` | `utils/arrow_utils.py:canonical_identity_row_order` |
-| run snapshot | sink nodes' content hashes | the snapshot | `":"` | `pipeline/job.py:PipelineJob._prepare_run..` |
+| run snapshot | sink nodes' content hashes | the snapshot | labelled content digests | `pipeline/job.py:PipelineJob._project_run`, `pipeline/job.py:PipelineJob._project_run..` |
| pandas value hash | the ordered Arrow digest | the pandas value hash | `b"arrow_ordered_v1:" + digest` | `hashing/pandas_value_hash.py:pandas_frame_content_hash`, `hashing/pandas_value_hash.py:pandas_series_content_hash` |
| directory entry | a file's hash | the directory hash | `b":" + digest` | `hashing/directory_hashers.py:_hash_dir` |
| ignore-list value handlers | the pandas digest the handler wraps under its own label | the handler's `ContentHash` | its own procedure's digest | `hashing/semantic_hashing/builtin_handlers.py:PandasDataFrameHandler.digest`, `hashing/semantic_hashing/builtin_handlers.py:PandasSeriesHandler.digest` |
@@ -426,7 +430,7 @@ test session with `-p tests.test_hashing.hash_site_trace`.
| side-effect log key and `entry_id` | `side_effects.py:_execute_side_effect_row` |
| the `_content_hash` column | `core/streams/arrow_table_stream.py:ArrowTableStream._assemble_table..hashes`, `core/function_pod.py:FunctionPodStream.as_table..all_content_hashes`, `core/function_pod.py:FunctionPodStream.head..shown_content_hashes`, `core/function_pod.py:FunctionPodStream.head..`, `core/nodes/function_node.py:FunctionNodeBase.as_table..all_content_hashes`, `core/nodes/function_node.py:FunctionNodeBase._head_of_pairs..`, `side_effects.py:_table_of_rows` |
| `__pf_var_function_signature_hash`, `__pf_var_function_content_hash` | `core/data_function.py:function_signature_hash`, `core/data_function.py:function_content_hash`, `core/data_function.py:PythonDataFunction.__init__` |
-| saved pipeline and job files | `pipeline/graph.py:Pipeline.save`, `pipeline/job.py:PipelineJob.save`, `pipeline/job.py:PipelineJob.as_pipeline`, `core/sources/base.py:RootSource._identity_config` |
+| saved pipeline and job files | `pipeline/graph.py:Pipeline._wire_key`, `pipeline/graph.py:Pipeline.save`, `pipeline/job.py:PipelineJob.save`, `pipeline/job.py:PipelineJob.as_pipeline`, `core/sources/base.py:RootSource._identity_config` |
| cached file hashes (in-memory writes compare validated hashes, SQLite and PostgreSQL read and write `b"sha256:" + 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`, `hashing/file_hashers.py:parse_stored_file_hash`, `hashing/file_hashers.py:serialize_storable_file_hash` |
| `InvocationContext.invocation_hash` (`::::`; its redesign is a side-effect follow-up) | `invocation.py:_serialize_component` |
@@ -460,9 +464,11 @@ id is a hash (site 8b).
|---|---|
| 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_nodes`, `pipeline/base.py:AbstractPipelineBase._compile_nodes..`, `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 graph keys | `core/identity_chains.py:graph_key`, `core/identity_chains.py:IdentityChainsMixin._legacy_graph_identity` (node hash or a namespaced key derived from structure and positioned upstream addresses) |
+| pipeline hash attached to an in-memory graph vertex | `pipeline/base.py:AbstractPipelineBase._compile_nodes` |
+| in-memory concrete-source checks | `pipeline/source_consistency.py:require_consistent_sources`, `pipeline/restrictions.py:sources_read`, `pipeline/base.py:AbstractPipelineBase._validate_invocation` |
+| in-memory validation of shared legacy execution identities across slots and steps | `pipeline/base.py:_legacy_key` |
+| exported invocation graph source keys | `pipeline/base.py:AbstractPipelineBase.to_invocations` |
| in-memory key for an in-flight function result (ITL-1101) | `core/cached_function_pod.py:CachedFunctionPod._async_process_once` |
| in-memory lookup keys for a validated operator input or input pair (ITL-1358) | `core/operators/index.py:Index.validate_unary_input`, `core/operators/index.py:Index.async_execute`, `core/operators/pick.py:Pick.validate_unary_input`, `core/operators/pick.py:Pick.async_execute`, `core/operators/semijoin.py:SemiJoin.validate_binary_inputs`, `core/operators/semijoin.py:SemiJoin.async_execute` |
| in-memory topological sort of compiled and restored nodes, using the pipeline hash to order ready invocations | `pipeline/base.py:AbstractPipelineBase._ordered_node_map..order_key` |
diff --git a/docs/tutorial/05-pipeline-job.md b/docs/tutorial/05-pipeline-job.md
index 5967393dc..e81a04c38 100644
--- a/docs/tutorial/05-pipeline-job.md
+++ b/docs/tutorial/05-pipeline-job.md
@@ -139,14 +139,14 @@ with the nodes it reads from:
print(job.diagram())
# Job 'workshop': 9 nodes
# sessions (source · CSVSource · bound)
-# SelectDataColumns_1 (operator · current) <- sessions
+# SelectDataColumns_3 (operator · current) <- sessions
# units (source · CSVSource · bound)
-# SelectDataColumns_3 (operator · current) <- units
-# Join (operator · current) <- SelectDataColumns_1, SelectDataColumns_3
+# SelectDataColumns_2 (operator · current) <- units
+# Join (operator · current) <- SelectDataColumns_3, SelectDataColumns_2
# rates (function pod · firing_rate · current) <- Join
# GroupBy (operator · current) <- rates
-# SelectDataColumns_2 (operator · current) <- GroupBy
-# session_means (function pod · mean_rate · current) <- SelectDataColumns_2
+# SelectDataColumns_1 (operator · current) <- GroupBy
+# session_means (function pod · mean_rate · current) <- SelectDataColumns_1
```
The `Join` is there because the pod joins the two streams given to `firing_rate`. `current`
diff --git a/docs/tutorial/inspecting-results.md b/docs/tutorial/inspecting-results.md
index f3a538069..eebb6945a 100644
--- a/docs/tutorial/inspecting-results.md
+++ b/docs/tutorial/inspecting-results.md
@@ -67,18 +67,18 @@ a node reads from:
print(job.diagram())
# Job 'workshop': 9 nodes
# sessions (source · CSVSource · bound)
-# SelectDataColumns_1 (operator · current) <- sessions
+# SelectDataColumns_3 (operator · current) <- sessions
# units (source · CSVSource · bound)
-# SelectDataColumns_3 (operator · current) <- units
-# Join (operator · current) <- SelectDataColumns_1, SelectDataColumns_3
+# SelectDataColumns_2 (operator · current) <- units
+# Join (operator · current) <- SelectDataColumns_3, SelectDataColumns_2
# rates (function pod · firing_rate · current) <- Join
# GroupBy (operator · current) <- rates
-# SelectDataColumns_2 (operator · current) <- GroupBy
-# session_means (function pod · mean_rate · current) <- SelectDataColumns_2
+# SelectDataColumns_1 (operator · current) <- GroupBy
+# session_means (function pod · mean_rate · current) <- SelectDataColumns_1
```
To find the steps that produced a result, start at its node and follow `<-` until you reach
-the sources: `session_means` reads `SelectDataColumns_2`, which reads `GroupBy`, and so on back
+the sources: `session_means` reads `SelectDataColumns_1`, which reads `GroupBy`, and so on back
to `units` and `sessions`. When a job has several steps of the same kind, it numbers them
(`SelectDataColumns_1`, ...). The numbers tell the steps apart and do not follow the order you
wrote them in.
diff --git a/docs/tutorial/provenance-diagram-missing-filter.svg b/docs/tutorial/provenance-diagram-missing-filter.svg
index 6244eac8a..2e5ddb9d7 100644
--- a/docs/tutorial/provenance-diagram-missing-filter.svg
+++ b/docs/tutorial/provenance-diagram-missing-filter.svg
@@ -1,23 +1,23 @@
-Job 'imec0': why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter[Filter_2]: probe='imec0' highlighted: why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter… sessions → Filter_1 Filter_1 → SelectDataColumns_2 SelectDataColumns_2 → Join units → Filter_2 Filter_2 → SelectDataColumns_1 SelectDataColumns_1 → Join Join → imec0_rates sessions (source · CSVSource)
+Job 'imec0': why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter[Filter_2]: probe='imec0' highlighted: why record row_4 of units is missing at node imec0_rates: units row_4 is removed by Filter… sessions → Filter_1 Filter_1 → SelectDataColumns_1 SelectDataColumns_1 → Join units → Filter_2 Filter_2 → SelectDataColumns_2 SelectDataColumns_2 → Join Join → imec0_rates sessions (source · CSVSource)
tags: subject_id: str, session: str
data: date: date, duration_s: float source CSVSource sessions Filter_1 (operator)
tags: subject_id: str, session: str
data: date: date, duration_s: float
-inputs: sessions operator Filter_1 SelectDataColumns_2 (operator)
+inputs: sessions operator Filter_1 SelectDataColumns_1 (operator)
tags: subject_id: str, session: str
data: duration_s: float
-inputs: Filter_1 operator SelectDataColumns_2 units (source · CSVSource)
+inputs: Filter_1 operator SelectDataColumns_1 units (source · CSVSource)
tags: subject_id: str, session: str, probe: str, unit: int
data: region: str, depth_um: int, n_spikes: int source CSVSource units Filter_2 (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: region: str, depth_um: int, n_spikes: int
-inputs: units operator Filter_2 SelectDataColumns_1 (operator)
+inputs: units operator Filter_2 SelectDataColumns_2 (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int
-inputs: Filter_2 operator SelectDataColumns_1 Join (operator)
+inputs: Filter_2 operator SelectDataColumns_2 Join (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int, duration_s: float
-inputs: SelectDataColumns_2, SelectDataColumns_1 operator Join imec0_rates (function pod · firing_rate)
+inputs: SelectDataColumns_1, SelectDataColumns_2 operator Join imec0_rates (function pod · firing_rate)
tags: subject_id: str, session: str, probe: str, unit: int
data: rate_hz: float
inputs: Join
diff --git a/docs/tutorial/provenance-diagram-missing-join.svg b/docs/tutorial/provenance-diagram-missing-join.svg
index 7b5542b80..a76c1ee73 100644
--- a/docs/tutorial/provenance-diagram-missing-join.svg
+++ b/docs/tutorial/provenance-diagram-missing-join.svg
@@ -1,23 +1,23 @@
-Job 'imec0': why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join: rows without a match in 'sessions' are dropped highlighted: why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join… sessions → Filter_1 Filter_1 → SelectDataColumns_2 SelectDataColumns_2 → Join units → Filter_2 Filter_2 → SelectDataColumns_1 SelectDataColumns_1 → Join Join → imec0_rates sessions (source · CSVSource)
+Job 'imec0': why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join: rows without a match in 'sessions' are dropped highlighted: why record row_48 of units is missing at node imec0_rates: units row_48 is removed by Join… sessions → Filter_1 Filter_1 → SelectDataColumns_1 SelectDataColumns_1 → Join units → Filter_2 Filter_2 → SelectDataColumns_2 SelectDataColumns_2 → Join Join → imec0_rates sessions (source · CSVSource)
tags: subject_id: str, session: str
data: date: date, duration_s: float source CSVSource sessions Filter_1 (operator)
tags: subject_id: str, session: str
data: date: date, duration_s: float
-inputs: sessions operator Filter_1 SelectDataColumns_2 (operator)
+inputs: sessions operator Filter_1 SelectDataColumns_1 (operator)
tags: subject_id: str, session: str
data: duration_s: float
-inputs: Filter_1 operator SelectDataColumns_2 units (source · CSVSource)
+inputs: Filter_1 operator SelectDataColumns_1 units (source · CSVSource)
tags: subject_id: str, session: str, probe: str, unit: int
data: region: str, depth_um: int, n_spikes: int source CSVSource units Filter_2 (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: region: str, depth_um: int, n_spikes: int
-inputs: units operator Filter_2 SelectDataColumns_1 (operator)
+inputs: units operator Filter_2 SelectDataColumns_2 (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int
-inputs: Filter_2 operator SelectDataColumns_1 Join (operator)
+inputs: Filter_2 operator SelectDataColumns_2 Join (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int, duration_s: float
-inputs: SelectDataColumns_2, SelectDataColumns_1 operator Join imec0_rates (function pod · firing_rate)
+inputs: SelectDataColumns_1, SelectDataColumns_2 operator Join imec0_rates (function pod · firing_rate)
tags: subject_id: str, session: str, probe: str, unit: int
data: rate_hz: float
inputs: Join
diff --git a/docs/tutorial/provenance-diagram-plain.svg b/docs/tutorial/provenance-diagram-plain.svg
index b79cf826d..5169fa9ae 100644
--- a/docs/tutorial/provenance-diagram-plain.svg
+++ b/docs/tutorial/provenance-diagram-plain.svg
@@ -1,28 +1,28 @@
-Job 'workshop' sessions → SelectDataColumns_1 SelectDataColumns_1 → Join units → SelectDataColumns_3 SelectDataColumns_3 → Join Join → rates rates → GroupBy GroupBy → SelectDataColumns_2 SelectDataColumns_2 → session_means sessions (source · CSVSource · bound)
+Job 'workshop' sessions → SelectDataColumns_3 SelectDataColumns_3 → Join units → SelectDataColumns_2 SelectDataColumns_2 → Join Join → rates rates → GroupBy GroupBy → SelectDataColumns_1 SelectDataColumns_1 → session_means sessions (source · CSVSource · bound)
tags: subject_id: str, session: str
-data: date: date, duration_s: float source CSVSource bound sessions SelectDataColumns_1 (operator · current)
+data: date: date, duration_s: float source CSVSource bound sessions SelectDataColumns_3 (operator · current)
tags: subject_id: str, session: str
data: duration_s: float
-inputs: sessions operator · current SelectDataColumns_1 units (source · CSVSource · bound)
+inputs: sessions operator · current SelectDataColumns_3 units (source · CSVSource · bound)
tags: subject_id: str, session: str, probe: str, unit: int
-data: region: str, depth_um: int, n_spikes: int source CSVSource bound units SelectDataColumns_3 (operator · current)
+data: region: str, depth_um: int, n_spikes: int source CSVSource bound units SelectDataColumns_2 (operator · current)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int
-inputs: units operator · current SelectDataColumns_3 Join (operator · current)
+inputs: units operator · current SelectDataColumns_2 Join (operator · current)
tags: subject_id: str, session: str, probe: str, unit: int
data: duration_s: float, n_spikes: int
-inputs: SelectDataColumns_1, SelectDataColumns_3 operator current Join rates (function pod · firing_rate · current)
+inputs: SelectDataColumns_3, SelectDataColumns_2 operator current Join rates (function pod · firing_rate · current)
tags: subject_id: str, session: str, probe: str, unit: int
data: rate_hz: float
inputs: Join
job's last run: 64 rows, 63 computed, 1 reused function pod firing_rate current rates GroupBy (operator · current)
tags: subject_id: str, session: str
data: rate_hz: list[float]
-inputs: rates operator current GroupBy SelectDataColumns_2 (operator · current)
+inputs: rates operator current GroupBy SelectDataColumns_1 (operator · current)
tags: subject_id: str, session: str
data: rate_hz: list[float]
-inputs: GroupBy operator · current SelectDataColumns_2 session_means (function pod · mean_rate · current)
+inputs: GroupBy operator · current SelectDataColumns_1 session_means (function pod · mean_rate · current)
tags: subject_id: str, session: str
data: mean_rate_hz: float
-inputs: SelectDataColumns_2
+inputs: SelectDataColumns_1
job's last run: 8 rows, 8 computed function pod mean_rate current session_means
diff --git a/docs/tutorial/provenance-diagram-trace.svg b/docs/tutorial/provenance-diagram-trace.svg
index c5dd98253..b70be37ca 100644
--- a/docs/tutorial/provenance-diagram-trace.svg
+++ b/docs/tutorial/provenance-diagram-trace.svg
@@ -1,28 +1,28 @@
-Job 'workshop': trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches sessions → SelectDataColumns_1 SelectDataColumns_1 → Join units → SelectDataColumns_3 SelectDataColumns_3 → Join Join → rates rates → GroupBy GroupBy → SelectDataColumns_2 SelectDataColumns_2 → session_means sessions (source · CSVSource)
+Job 'workshop': trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches highlighted: trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches sessions → SelectDataColumns_3 SelectDataColumns_3 → Join units → SelectDataColumns_2 SelectDataColumns_2 → Join Join → rates rates → GroupBy GroupBy → SelectDataColumns_1 SelectDataColumns_1 → session_means sessions (source · CSVSource)
tags: subject_id: str, session: str
-data: date: date, duration_s: float source CSVSource sessions SelectDataColumns_1 (operator)
+data: date: date, duration_s: float source CSVSource sessions SelectDataColumns_3 (operator)
tags: subject_id: str, session: str
data: duration_s: float
-inputs: sessions operator SelectDataColumns_1 units (source · CSVSource)
+inputs: sessions operator SelectDataColumns_3 units (source · CSVSource)
tags: subject_id: str, session: str, probe: str, unit: int
-data: region: str, depth_um: int, n_spikes: int source CSVSource units SelectDataColumns_3 (operator)
+data: region: str, depth_um: int, n_spikes: int source CSVSource units SelectDataColumns_2 (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: n_spikes: int
-inputs: units operator SelectDataColumns_3 Join (operator)
+inputs: units operator SelectDataColumns_2 Join (operator)
tags: subject_id: str, session: str, probe: str, unit: int
data: duration_s: float, n_spikes: int
-inputs: SelectDataColumns_1, SelectDataColumns_3 operator Join rates (function pod · firing_rate)
+inputs: SelectDataColumns_3, SelectDataColumns_2 operator Join rates (function pod · firing_rate)
tags: subject_id: str, session: str, probe: str, unit: int
data: rate_hz: float
inputs: Join
job's last run: 64 rows, 63 computed, 1 reused function pod firing_rate reused traced from here rates GroupBy (operator)
tags: subject_id: str, session: str
data: rate_hz: list[float]
-inputs: rates operator GroupBy SelectDataColumns_2 (operator)
+inputs: rates operator GroupBy SelectDataColumns_1 (operator)
tags: subject_id: str, session: str
data: rate_hz: list[float]
-inputs: GroupBy operator SelectDataColumns_2 session_means (function pod · mean_rate)
+inputs: GroupBy operator SelectDataColumns_1 session_means (function pod · mean_rate)
tags: subject_id: str, session: str
data: mean_rate_hz: float
-inputs: SelectDataColumns_2
+inputs: SelectDataColumns_1
job's last run: 8 rows, 8 computed function pod mean_rate session_means
diff --git a/docs/tutorial/tracing-a-value.md b/docs/tutorial/tracing-a-value.md
index d95763fb2..14e29b7ef 100644
--- a/docs/tutorial/tracing-a-value.md
+++ b/docs/tutorial/tracing-a-value.md
@@ -195,14 +195,14 @@ print(job.diagram(highlight=trace.highlight()))
# Job 'workshop': 9 nodes
# highlight (*): trace of mean_rate_hz at node session_means, for subject_id='mouse_03', session='s2': 1 row matches
# * sessions (source · CSVSource)
-# * SelectDataColumns_1 (operator) <- sessions
+# * SelectDataColumns_3 (operator) <- sessions
# * units (source · CSVSource)
-# * SelectDataColumns_3 (operator) <- units
-# * Join (operator) <- SelectDataColumns_1, SelectDataColumns_3
+# * SelectDataColumns_2 (operator) <- units
+# * Join (operator) <- SelectDataColumns_3, SelectDataColumns_2
# * rates (function pod · firing_rate) [computed] <- Join
# * GroupBy (operator) <- rates
-# * SelectDataColumns_2 (operator) <- GroupBy
-# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_2
+# * SelectDataColumns_1 (operator) <- GroupBy
+# >* session_means (function pod · mean_rate) [computed] [traced from here] <- SelectDataColumns_1
```
A mean is made through every step of the job, so its path covers the whole diagram. The trace
@@ -217,14 +217,14 @@ print(job.diagram(highlight=rate.highlight()))
# Job 'workshop': 9 nodes
# highlight (*): trace of rate_hz at node rates, for subject_id='mouse_02', session='s1', probe='imec1', unit=2: 1 row matches
# * sessions (source · CSVSource)
-# * SelectDataColumns_1 (operator) <- sessions
+# * SelectDataColumns_3 (operator) <- sessions
# * units (source · CSVSource)
-# * SelectDataColumns_3 (operator) <- units
-# * Join (operator) <- SelectDataColumns_1, SelectDataColumns_3
+# * SelectDataColumns_2 (operator) <- units
+# * Join (operator) <- SelectDataColumns_3, SelectDataColumns_2
# >* rates (function pod · firing_rate) [reused] [traced from here] <- Join
# GroupBy (operator) <- rates
-# SelectDataColumns_2 (operator) <- GroupBy
-# session_means (function pod · mean_rate) <- SelectDataColumns_2
+# SelectDataColumns_1 (operator) <- GroupBy
+# session_means (function pod · mean_rate) <- SelectDataColumns_1
```
In a notebook the same call draws the picture. The caption is the question. The path is
@@ -324,7 +324,7 @@ ends at the filter on `probe`:
`units row_48` passes the filter and its column selection and ends at the Join, which has no
session `s1` of `mouse_04` to match it with:
-
+
## Key points
diff --git a/src/orcapod/core/base.py b/src/orcapod/core/base.py
index 1ca4a6955..5953a5ca0 100644
--- a/src/orcapod/core/base.py
+++ b/src/orcapod/core/base.py
@@ -6,7 +6,7 @@
from contextlib import contextmanager
from contextvars import ContextVar
from datetime import datetime, timezone
-from typing import Any, ClassVar
+from typing import Any
import orcapod.contexts as contexts
from orcapod.config import DEFAULT_CONFIG, OrcapodConfig
@@ -139,21 +139,10 @@ class ContentIdentifiableBase(DataContextMixin, ABC):
object is determined by the structure returned by the `identity_structure` method.
The hash of the object is computed based on the `identity_structure` using the provided `ObjectHasher`,
which defaults to the one returned by `get_default_semantic_hasher`.
- Two content-identifiable objects are considered equal if their `identity_structure` returns the same value.
+ Objects compare their identity structures by default. Pipeline graph lookups
+ use the graph's own records.
"""
- _content_hash_generation: ClassVar[object] = object()
-
- @staticmethod
- def content_hash_generation() -> object:
- """Return the generation of state used in capture identities."""
- return ContentIdentifiableBase._content_hash_generation
-
- @staticmethod
- def _invalidate_capture_keys() -> None:
- """Invalidate recorded-stream key memos after a lineage or hash change."""
- ContentIdentifiableBase._content_hash_generation = object()
-
def __init__(
self,
data_context: str | contexts.DataContext | None = None,
@@ -240,15 +229,7 @@ def _object_hash(self) -> ContentHash:
return self.content_hash()
def __eq__(self, other: object) -> bool:
- """
- Equality check that compares the identity structures of two objects.
-
- Args:
- other (object): The object to compare against.
-
- Returns:
- bool: True if both objects have the same identity structure, False otherwise.
- """
+ """Compare the objects' identity structures."""
if not isinstance(other, ContentIdentifiableBase):
return NotImplemented
@@ -263,7 +244,6 @@ 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
diff --git a/src/orcapod/core/cached_function_pod.py b/src/orcapod/core/cached_function_pod.py
index 74f9ac24a..af37b8aa4 100644
--- a/src/orcapod/core/cached_function_pod.py
+++ b/src/orcapod/core/cached_function_pod.py
@@ -599,7 +599,7 @@ def process(
function_pod=self,
input_stream=input_stream,
label=label,
- )
+ )._mark_recorded(self.tracker_manager)
class _CachedFunctionPodStream(FunctionPodStream):
diff --git a/src/orcapod/core/function_pod.py b/src/orcapod/core/function_pod.py
index 1c4dd7087..c8cf12a2e 100644
--- a/src/orcapod/core/function_pod.py
+++ b/src/orcapod/core/function_pod.py
@@ -930,6 +930,16 @@ def __call__(
def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup:
return self.multi_stream_handler().argument_symmetry(streams)
+ def structural_argument_symmetry(
+ self, streams: tuple[StreamProtocol, ...]
+ ) -> ArgumentGroup:
+ """Use the handler's structural grouping when it supplies the symmetry."""
+ from orcapod.core.identity_chains import structural_argument_symmetry
+
+ if type(self).argument_symmetry is _FunctionPodBase.argument_symmetry:
+ return structural_argument_symmetry(self.multi_stream_handler(), streams)
+ return self.argument_symmetry(streams)
+
def output_schema(
self,
*streams: StreamProtocol,
@@ -1321,7 +1331,13 @@ def identity_structure(self) -> Any:
)
def pipeline_identity_structure(self) -> Any:
- return self.identity_structure()
+ from orcapod.core.identity_chains import pipeline_argument_group
+
+ require_current_outputs(self._input_stream)
+ return (
+ self._function_pod,
+ pipeline_argument_group(self._function_pod, (self._input_stream,)),
+ )
def keys(
self,
@@ -2132,6 +2148,15 @@ def _refuse_as_this_pod(self, *streams: StreamProtocol) -> None:
def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup:
return self._function_pod.argument_symmetry(streams)
+ def structural_argument_symmetry(
+ self, streams: tuple[StreamProtocol, ...]
+ ) -> ArgumentGroup:
+ from orcapod.core.identity_chains import structural_argument_symmetry
+
+ if type(self).argument_symmetry is WrappedFunctionPod.argument_symmetry:
+ return structural_argument_symmetry(self._function_pod, streams)
+ return self.argument_symmetry(streams)
+
def output_schema(
self,
*streams: StreamProtocol,
diff --git a/src/orcapod/core/identity_chains.py b/src/orcapod/core/identity_chains.py
index 0ac6c3293..ad8b90726 100644
--- a/src/orcapod/core/identity_chains.py
+++ b/src/orcapod/core/identity_chains.py
@@ -10,7 +10,7 @@
from dataclasses import dataclass
from functools import cached_property
from itertools import groupby
-from typing import TYPE_CHECKING, ClassVar, TypeVar, final
+from typing import TYPE_CHECKING, ClassVar, Protocol, TypeVar, final
from weakref import WeakValueDictionary
from orcapod.core.output_bindings import identity_lock, require_current_outputs
@@ -36,6 +36,52 @@
NAME_CHAIN_HASH_LABEL = "name_chain_v1"
CONTENT_HASH_LABEL = "content_hash_v1"
NODE_HASH_LABEL = "node_hash_v1"
+_LEGACY_GRAPH_KEY_LABEL = "legacy_graph_key_v1"
+
+
+class UndefinedIdentityError(ValueError):
+ """A legacy pipeline element cannot supply its three-chain identity."""
+
+
+class _GraphIdentity(Protocol):
+ def node_hash(self) -> ContentHash: ...
+ def pipeline_hash(self) -> ContentHash: ...
+
+
+def graph_key(
+ element: _GraphIdentity | None,
+ *,
+ legacy_key: str | None = None,
+ use_published: bool = True,
+) -> str:
+ """Use the node hash or retain a separately namespaced legacy graph key."""
+ if element is not None:
+ if (
+ use_published
+ and isinstance(element, IdentityChainsMixin)
+ and element._compiled_graph_key is not None
+ ):
+ return element._compiled_graph_key
+ try:
+ return element.node_hash().to_string()
+ except UndefinedIdentityError:
+ if legacy_key is None:
+ legacy_key = (
+ element._legacy_graph_identity(use_published=use_published)
+ if isinstance(element, IdentityChainsMixin)
+ else element.pipeline_hash().to_string()
+ )
+ if legacy_key is None:
+ raise ValueError("A graph entry without a node must have a saved key.")
+ # The node hash method is always node_hash_v1, a disjoint namespace.
+ return f"legacy:{legacy_key}"
+
+
+def assign_graph_key(element: object, key: str) -> None:
+ """Publish a compiled node's address for graph lookups."""
+ if isinstance(element, IdentityChainsMixin):
+ element._compiled_graph_key = key
+
_reading_chains: ContextVar[bool] = ContextVar("reading_identity_chains", default=False)
@@ -53,7 +99,7 @@ def _identity_read() -> Iterator[None]:
def refuse_identity_io(reason: str = "this source requires a schema") -> None:
"""Report why an identity read would need rows or a source callback."""
if reading_identity_chains():
- raise ValueError(f"Pipeline identity is undefined: {reason}.")
+ raise UndefinedIdentityError(f"Pipeline identity is undefined: {reason}.")
def reading_identity_chains() -> bool:
@@ -67,7 +113,7 @@ def require_builtin_operator_identity(operator: object) -> None:
from orcapod.core.operators import BUILTIN_OPERATOR_TYPES
if type(operator) not in BUILTIN_OPERATOR_TYPES:
- raise ValueError(
+ raise UndefinedIdentityError(
"Pipeline identity is undefined for a custom operator in this step."
)
@@ -100,16 +146,30 @@ def _hash(label: str, preimage: tuple[object, ...]) -> ContentHash:
return SemanticAwarePythonHasher(hasher_id=label).hash_object(preimage)
+class _UncachedIdentityChains(Exception):
+ """Suspend a chain computation until its upstream chains are cached."""
+
+ def __init__(self, element: IdentityChainsMixin) -> None:
+ super().__init__()
+ self.element = element
+
+
@final
class IdentityWalk:
"""Walk uncached inputs and connect their caches to their dependents."""
def __init__(
- self, hasher: SemanticHasherProtocol, *, include_sources: bool
+ self,
+ hasher: SemanticHasherProtocol,
+ *,
+ include_sources: bool,
) -> None:
self.hasher = hasher
self.include_sources = include_sources
self._consumer: IdentityChainsMixin | None = None
+ self._delegated_chains: dict[
+ int, tuple[IdentityChainsMixin, IdentityChains]
+ ] = {}
def depend_on(self, element: IdentityChainsMixin) -> None:
"""Record a dependency for the node whose chains are being evaluated."""
@@ -136,21 +196,49 @@ def visit(self, element: IdentityChainProtocol) -> IdentityChains:
if not isinstance(element, IdentityChainsMixin):
return element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Transparent stream wrapper.
- if self._consumer is None:
- from orcapod.core.streams.base import StreamBase
+ if self._consumer is not None:
+ self.depend_on(element)
+ cached = element._cached_identity_chains(self)
+ if cached is not None:
+ return cached
+ if (delegated := self._delegated_chains.get(id(element))) is not None:
+ return delegated[1]
+ raise _UncachedIdentityChains(element)
- if isinstance(element, StreamBase):
- require_current_outputs(element)
- else:
- require_current_outputs(*element._identity_inputs())
+ from orcapod.core.streams.base import StreamBase
- self.depend_on(element)
- consumer = self._consumer
- self._consumer = element
+ if isinstance(element, StreamBase):
+ require_current_outputs(element)
+ else:
+ require_current_outputs(*element._identity_inputs())
+
+ pending = [element]
+ active = {id(element)}
try:
- return element._identity_chains(self) # pyright: ignore[reportPrivateUsage] # Internal back edge of the identity walk.
+ while True:
+ current = pending[-1]
+ self._consumer = current
+ try:
+ chains = current._identity_chains(self)
+ except _UncachedIdentityChains as request:
+ upstream = request.element
+ if id(upstream) in active:
+ raise ValueError(
+ "Cycle in identity chain dependencies"
+ ) from None
+ active.add(id(upstream))
+ pending.append(upstream)
+ else:
+ # A materialized view can delegate to its origin without
+ # writing its own persistent memo. Retain it for this walk.
+ if current._cached_identity_chains(self) is None:
+ self._delegated_chains[id(current)] = (current, chains)
+ active.remove(id(pending.pop()))
+ if not pending:
+ return chains
finally:
- self._consumer = consumer
+ self._consumer = None
+ self._delegated_chains.clear()
@dataclass(slots=True)
@@ -235,9 +323,10 @@ def structural_argument_symmetry(
pod: PodProtocol, inputs: tuple[StreamProtocol, ...]
) -> ArgumentGroup:
"""Read the argument occurrences used by all three identity chains."""
+ from orcapod.core.function_pod import _FunctionPodBase
from orcapod.core.operators.static_output_pod import StaticOutputOperatorPod
- if isinstance(pod, StaticOutputOperatorPod):
+ if isinstance(pod, (StaticOutputOperatorPod, _FunctionPodBase)):
return pod.structural_argument_symmetry(inputs)
return pod.argument_symmetry(inputs)
@@ -246,16 +335,23 @@ def pipeline_argument_group(
pod: PodProtocol, inputs: tuple[StreamProtocol, ...]
) -> ArgumentGroup:
"""Keep all input occurrences in the structural preimage."""
- return structural_argument_group(inputs, structural_argument_symmetry(pod, inputs))
+
+ def occurrence(group: InputSymmetry) -> ArgumentGroup:
+ if isinstance(group, int):
+ return inputs[group]
+ if isinstance(group, _SymmetricInputs):
+ return SymmetricGroup(tuple(map(occurrence, group.children)))
+ return tuple(map(occurrence, group))
+
+ return occurrence(
+ encode_input_symmetry(inputs, structural_argument_symmetry(pod, inputs))
+ )
def encode_input_symmetry(
inputs: tuple[StreamProtocol, ...], group: ArgumentGroup
) -> InputSymmetry:
"""Encode each argument occurrence as a position in the symmetry tree."""
- if len(inputs) < 2:
- return list(range(len(inputs)))
-
group = structural_argument_group(inputs, group)
remaining: dict[int, deque[int]] = defaultdict(deque)
for index, stream in enumerate(inputs):
@@ -270,6 +366,16 @@ def encode(node: ArgumentGroup, children: list[InputSymmetry]) -> InputSymmetry:
return _transform_argument_group(group, position, encode)
+def _group_graph_keys(group: InputSymmetry, keys: tuple[str, ...]) -> object:
+ """Replace argument positions with graph keys, sorting only symmetric groups."""
+ if isinstance(group, int):
+ return keys[group]
+ if isinstance(group, _SymmetricInputs):
+ members = (_group_graph_keys(child, keys) for child in group.children)
+ return ("frozenset", tuple(sorted(members, key=repr)))
+ return tuple(_group_graph_keys(child, keys) for child in group)
+
+
def _has_symmetric_group(group: InputSymmetry) -> bool:
"""Whether pooling needs structural keys anywhere in this grouping."""
return isinstance(group, _SymmetricInputs) or (
@@ -346,6 +452,28 @@ class IdentityChainsMixin(ABC):
# Guard its reverse edges and memo publication with the same lock as binding.
_identity_lock: ClassVar[AbstractContextManager[object]] = identity_lock
+ _compiled_graph_key: str | None = None
+
+ def _legacy_graph_identity(self, *, use_published: bool = True) -> str:
+ """Address a legacy node by structure, slot name and declared symmetry."""
+ inputs = self._identity_inputs()
+ keys = tuple(
+ graph_key(stream, use_published=use_published) for stream in inputs
+ )
+ group = (
+ encode_input_symmetry(inputs, self._identity_symmetry(inputs))
+ if len(inputs) >= 2
+ else list[InputSymmetry](range(len(inputs)))
+ )
+ return _hash(
+ _LEGACY_GRAPH_KEY_LABEL,
+ (
+ self.pipeline_hash(),
+ getattr(self, "name", None),
+ _group_graph_keys(group, keys),
+ ),
+ ).to_string()
+
# Defaults cover loaded stubs constructed without __init__.
_identity_cache: dict[tuple[str, bool, bool], IdentityChains] | None = None
_identity_name_hashes: dict[tuple[str, tuple[object, ...]], ContentHash] | None = (
@@ -456,23 +584,29 @@ 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:
- """Look up or publish chains for a walk holding the identity lock.
-
- A full memo can satisfy a name-only walk. A name-only memo cannot
- satisfy a walk that includes sources.
- """
+ def _cached_identity_chains(
+ self, walk: IdentityWalkProtocol
+ ) -> IdentityChains | None:
+ """Read the memo, allowing a full memo to satisfy a name-only walk."""
if self._identity_cache is None:
- self._identity_cache = {}
+ return None
hasher_id = walk.hasher.hasher_id
guarded = reading_identity_chains()
- full_key = (hasher_id, True, guarded)
- if not walk.include_sources and full_key in self._identity_cache:
- return self._identity_cache[full_key]
- key = (hasher_id, walk.include_sources, guarded)
- if key not in self._identity_cache:
- self._identity_cache[key] = self._compute_identity_chains(walk)
- return self._identity_cache[key]
+ return self._identity_cache.get(
+ (hasher_id, True, guarded)
+ ) or self._identity_cache.get((hasher_id, walk.include_sources, guarded))
+
+ def _identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains:
+ """Look up or publish chains for a walk holding the identity lock."""
+ cached = self._cached_identity_chains(walk)
+ if cached is not None:
+ return cached
+ chains = self._compute_identity_chains(walk)
+ if self._identity_cache is None:
+ self._identity_cache = {}
+ key = (walk.hasher.hasher_id, walk.include_sources, reading_identity_chains())
+ self._identity_cache[key] = chains
+ return chains
def _compute_identity_chains(self, walk: IdentityWalkProtocol) -> IdentityChains:
"""Compute this element's chains from its entries and upstream chains."""
diff --git a/src/orcapod/core/nodes/function_node.py b/src/orcapod/core/nodes/function_node.py
index 3518b8450..9b7c0791c 100644
--- a/src/orcapod/core/nodes/function_node.py
+++ b/src/orcapod/core/nodes/function_node.py
@@ -37,7 +37,6 @@
from orcapod.core.output_bindings import (
OutputBindings,
capture_output_bindings,
- invalidate_output_lineage,
)
from orcapod.core.nodes.provenance_methods import ProvenanceMethods
from orcapod.core.function_pod import (
@@ -586,11 +585,12 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
if len(value) != 1:
raise ValueError("FunctionPod can only have one upstream")
with self._identity_lock:
- self._input_stream = value[0]
- invalidate_output_lineage()
- self._invalidate_capture_keys()
- self._invalidate_identity_chains(names=True)
- self._forget_output_schema()
+ if self._captured_rewire_is_noop(value):
+ return
+ self._rewire(value, self._assign_upstreams)
+
+ def _assign_upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
+ self._input_stream = value[0]
# ------------------------------------------------------------------
# Read-only overrides (for deserialized nodes without live function_pod)
@@ -1781,57 +1781,56 @@ def attach_databases(
self.require_storable_tables(pipeline_database, result_database)
if ephemeral_database is not None:
self.require_storable_results(ephemeral_database)
- # Another database has its own tables of other generations to account for.
- self._stale_tables_checked = False
- self._current_tables_checked = False
- self._pipeline_preflight_checked = False
- self._token_column_types = None
- self._unlisted_store_reported = False
- self._skipped_rows_reported = False
- # ... and its own rows to compare with the job file's expected count.
- self._row_count_checked = False
- if pipeline_database is not None:
+ attach = self._prepare_database_attachment(pipeline_database, result_database)
+ attach()
+ if ephemeral_database is not None:
+ self.set_ephemeral_database(ephemeral_database)
+
+ def _prepare_database_attachment(
+ self,
+ pipeline_database: ArrowDatabaseProtocol | None,
+ result_database: ArrowDatabaseProtocol | None,
+ ) -> Callable[[], None]:
+ """Prepare an attachment after its storage checks pass."""
+ if pipeline_database is None:
+ cached_pod = None
+ else:
if result_database is None:
- # Default result database is pipeline_database scoped to "_result"
- # so that results are stored separately from pipeline-level records.
result_database = pipeline_database.at("_result")
-
if self._function_pod is not None:
- # A table must state its data-tags: refuse a database that
- # cannot, before anything is written (ITL-1019).
- require_database_keeps_marker(
- pipeline_database, fall_through_tags(self._function_pod)
- )
- # Normal path: wrap in CachedFunctionPod for compute + cache.
# A fall-through pod's results are its plain pod's (ITL-1023).
- self._cached_function_pod = CachedFunctionPod(
- result_pod(self._function_pod),
- result_database=result_database,
+ cached_pod = CachedFunctionPod(
+ result_pod(self._function_pod), result_database=result_database
)
else:
- # Read-only stub path (loaded job without a live function pod).
- # Use the record path stored from the descriptor so that
- # get_all_records() / _load_cached_entries() can query the DB.
- self._cached_function_pod = _ResultDatabaseReader( # type: ignore[assignment]
+ # A saved stub can serve previously stored results without computing.
+ cached_pod = _ResultDatabaseReader(
result_database=result_database,
record_path=self._stored_result_record_path,
)
- # With a database attached, the stub can serve the results its saved
- # run stored, though it still cannot compute.
- from orcapod.pipeline.serialization import LoadStatus
- self._load_status = LoadStatus.READ_ONLY
-
- self._pipeline_database = pipeline_database
-
- # Clear all caches
- self._node_identity_path_cache = None
- self.clear_cache()
- self._invalidate_content_hash_cache()
- self._invalidate_pipeline_hash_cache()
+ def attach() -> None:
+ # Another database has its own tables and expected row counts.
+ self._stale_tables_checked = False
+ self._current_tables_checked = False
+ self._pipeline_preflight_checked = False
+ self._token_column_types = None
+ self._unlisted_store_reported = False
+ self._skipped_rows_reported = False
+ self._row_count_checked = False
+ if cached_pod is not None:
+ self._cached_function_pod = cached_pod # pyright: ignore[reportAttributeAccessIssue, reportAssignmentType] # a saved stub uses the read-only implementation
+ if isinstance(cached_pod, _ResultDatabaseReader):
+ from orcapod.pipeline.serialization import LoadStatus
+
+ self._load_status = LoadStatus.READ_ONLY
+ self._pipeline_database = pipeline_database
+ self._node_identity_path_cache = None
+ self.clear_cache()
+ self._invalidate_content_hash_cache()
+ self._invalidate_pipeline_hash_cache()
- if ephemeral_database is not None:
- self.set_ephemeral_database(ephemeral_database)
+ return attach
# ------------------------------------------------------------------
# from_descriptor — read-only stub for loaded jobs
diff --git a/src/orcapod/core/nodes/operator_node.py b/src/orcapod/core/nodes/operator_node.py
index 91e5f7b25..4172f9a65 100644
--- a/src/orcapod/core/nodes/operator_node.py
+++ b/src/orcapod/core/nodes/operator_node.py
@@ -21,7 +21,15 @@
import sys
import logging
from abc import abstractmethod
-from collections.abc import Collection, Iterable, Iterator, Mapping, Sequence
+from collections.abc import (
+ Callable,
+ Collection,
+ Hashable,
+ Iterable,
+ Iterator,
+ Mapping,
+ Sequence,
+)
from datetime import datetime, timezone
from typing import TYPE_CHECKING, Any, Literal, cast
@@ -41,12 +49,12 @@
from orcapod.channels import Channel, ChannelClosed, ReadableChannel, WritableChannel
from orcapod.config import OrcapodConfig
from orcapod.core.identity_chains import (
+ UndefinedIdentityError,
pipeline_argument_group,
require_builtin_operator_identity,
)
from orcapod.core.output_bindings import (
capture_output_bindings,
- invalidate_output_lineage,
require_current_outputs,
)
from orcapod.core.operators.static_output_pod import (
@@ -204,19 +212,20 @@ def job_input_stream(
return reader.stream if type(reader) is _InputTap else None
-def ordered_operator_inputs(node: Any, predecessors: Iterable[Any]) -> list[Any]:
+def ordered_operator_inputs(
+ node: Any, predecessors: Iterable[Any], *, key: Callable[[Any], Hashable]
+) -> list[Any]:
"""Resolve each declared operand position to its execution predecessor."""
upstreams: tuple[StreamProtocol, ...] = node.upstreams
- # Graph adjacency merges equal nodes, including distinct slots bound to one
- # source. Keep the declared slots for rebinding and serialization, and feed
- # their shared graph predecessor once per operand position during execution.
- occurrences: dict[StreamProtocol, list[int]] = {}
+ # Graph adjacency can hold one edge for several positions. Resolve aliases
+ # through the execution graph's keys and dispatch once per declared position.
+ occurrences: dict[Hashable, list[int]] = {}
for index, upstream in enumerate(upstreams):
- occurrences.setdefault(upstream, []).append(index)
+ occurrences.setdefault(key(upstream), []).append(index)
ranked = [
(index, predecessor)
for predecessor in predecessors
- for index in occurrences.get(predecessor, [0])
+ for index in occurrences.get(key(predecessor), [0])
]
ranked.sort(key=lambda pair: pair[0])
return [predecessor for _, predecessor in ranked]
@@ -355,7 +364,7 @@ def _identity_leaf(self, walk: IdentityWalkProtocol) -> None:
):
# Built-ins add no chain terms, and a single input needs no grouping.
return None
- raise ValueError(
+ raise UndefinedIdentityError(
"Cannot compute operator identity chains because the saved form "
"does not carry input symmetry yet and the operator is unavailable."
)
@@ -428,16 +437,19 @@ def upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
Raises:
ValueError: If the node caches (``LOG`` or ``REPLAY``) and a source
feeding ``value`` is restricted (ITL-1218); nothing changes.
+ InconsistentSourceError: If the replacement changes inputs held by
+ a captured blueprint (ITL-1559).
"""
from orcapod.pipeline.restrictions import refuse_restricted_operator_cache
- refuse_restricted_operator_cache(self, self.cache_mode, streams=value)
with self._identity_lock:
- self._input_streams = value
- invalidate_output_lineage()
- self._invalidate_capture_keys()
- self._invalidate_identity_chains(names=True)
- self._forget_output_schema()
+ if self._captured_rewire_is_noop(value):
+ return
+ refuse_restricted_operator_cache(self, self.cache_mode, streams=value)
+ self._rewire(value, self._assign_upstreams)
+
+ def _assign_upstreams(self, value: tuple[StreamProtocol, ...]) -> None:
+ self._input_streams = value
@property
def arrow_schemas(self) -> "tuple[pa.Schema, pa.Schema] | None":
@@ -1067,6 +1079,8 @@ def require_storable_tables(
"""
if cache_mode == CacheMode.OFF:
return
+ # A stored table must preserve its data-tag marker (ITL-1019).
+ require_database_keeps_marker(pipeline_database, stream_data_tags(self))
try:
require_storable(
pipeline_database,
@@ -1106,25 +1120,29 @@ def attach_databases(
from orcapod.pipeline.restrictions import refuse_restricted_operator_cache
refuse_restricted_operator_cache(self, cache_mode)
- if cache_mode != CacheMode.OFF:
- # A stored table states its data-tags; refuse a database that
- # cannot, before anything runs or is written (ITL-1019).
- require_database_keeps_marker(pipeline_database, stream_data_tags(self))
-
- # A database that cannot store the cache refuses it now, before anything
- # runs or changes (ITL-1162).
self.require_storable_tables(pipeline_database, cache_mode)
- self._skipped_rows_reported = False
- self._stale_tables_checked = False
- self._row_count_checked = False
- self._pipeline_database = pipeline_database
- self._cache_mode = cache_mode
+ attach = self._prepare_database_attachment(pipeline_database, cache_mode)
+ attach()
+
+ def _prepare_database_attachment(
+ self, pipeline_database: ArrowDatabaseProtocol, cache_mode: CacheMode
+ ) -> Callable[[], None]:
+ """Prepare an attachment after its storage and restriction checks pass."""
+
+ def attach() -> None:
+ self._skipped_rows_reported = False
+ self._stale_tables_checked = False
+ self._row_count_checked = False
+ self._pipeline_database = pipeline_database
+ self._cache_mode = cache_mode
+
+ # Clear caches
+ self._node_identity_path_cache = None
+ self.clear_cache()
+ self._invalidate_content_hash_cache()
+ self._invalidate_pipeline_hash_cache()
- # Clear caches
- self._node_identity_path_cache = None
- self.clear_cache()
- self._invalidate_content_hash_cache()
- self._invalidate_pipeline_hash_cache()
+ return attach
# ------------------------------------------------------------------
# from_descriptor — reconstruct from a serialized pipeline descriptor
diff --git a/src/orcapod/core/nodes/source_node.py b/src/orcapod/core/nodes/source_node.py
index c15a541d6..dc045bdd1 100644
--- a/src/orcapod/core/nodes/source_node.py
+++ b/src/orcapod/core/nodes/source_node.py
@@ -1555,6 +1555,9 @@ class SourceNode(SourceNodeBase):
— identical to the old ``SourceSpec`` — so existing DB paths remain valid.
"""
+ _declared_stream: StreamProtocol | None = None
+ _capture_owner: object | None = None
+
def _typed_zero_row_table(self) -> "pa.Table | None":
"""The slot's zero-row table from its own Arrow schemas (ITL-640).
@@ -1609,23 +1612,24 @@ def from_stream(
return stream
tag_schema, data_schema = stream.output_schema()
slot_name = name if name is not None else slot_name_for(stream)
- if not isinstance(stream, SourceNodeBase):
+ if isinstance(stream, SourceNodeBase):
+ arrow_schemas = stream._given_arrow_schemas
+ else:
_require_stream_arrow_types(stream, slot_name)
+ arrow_schemas = typed_arrow_schemas(stream)
node = cls(
name=slot_name,
tag_schema=tag_schema,
data_schema=data_schema,
- arrow_schemas=(
- stream._given_arrow_schemas # pyright: ignore[reportPrivateUsage] # one slot copied into another
- if isinstance(stream, SourceNodeBase)
- else typed_arrow_schemas(stream)
- ),
+ arrow_schemas=arrow_schemas,
_inherited_types=True,
)
if isinstance(stream, SourceNodeBase):
# A loaded job's slot keeps all its saved state (ITL-1138, ITL-640),
# through the one method every copy of a slot uses.
node._take_saved_state_of(stream)
+ if name is not None:
+ node._declared_stream = stream
return node
@@ -2375,35 +2379,6 @@ def from_stream(
_inherited_types=True,
)
- @classmethod
- def _from_loaded_slot(
- cls, slot: SourceNode, bound_source: StreamProtocol | None
- ) -> "SourceJobNode":
- """Build the job node of a slot rebuilt from a saved job (``PipelineJob.load``).
-
- The node takes the slot's saved hashes and saved type texts before *bound_source*
- is checked, so a column saved with a class this process registers only now
- (by building the source) is restored for the check (ITL-1138).
-
- Args:
- slot: The slot ``Pipeline.load`` rebuilt from the job file.
- bound_source: The source rebuilt from the saved config, if any.
-
- Raises:
- SourceSpecMismatchError: If *bound_source* does not fit the slot.
- """
- node = cls(
- name=slot.name,
- tag_schema=slot.tag_schema,
- data_schema=slot.data_schema,
- arrow_schemas=slot._given_arrow_schemas, # pyright: ignore[reportPrivateUsage] # one slot copied into another
- _inherited_types=True,
- )
- node._take_saved_state_of(slot)
- if bound_source is not None:
- node._bind(bound_source)
- return node
-
def as_node(self) -> SourceNode:
"""Return the lightweight ``SourceNode`` equivalent of this job node.
diff --git a/src/orcapod/core/operators/join.py b/src/orcapod/core/operators/join.py
index b7b99e3e5..ebbee487a 100644
--- a/src/orcapod/core/operators/join.py
+++ b/src/orcapod/core/operators/join.py
@@ -515,8 +515,10 @@ def argument_symmetry(self, streams: Collection) -> ArgumentGroup:
def structural_argument_symmetry(
self, streams: tuple[StreamProtocol, ...]
) -> ArgumentGroup:
- """Declare every interchangeable occurrence without comparing the streams."""
- return SymmetricGroup(streams)
+ """Preserve the built-in group's occurrences and honor custom declarations."""
+ if type(self).argument_symmetry is Join.argument_symmetry:
+ return SymmetricGroup(streams)
+ return self.argument_symmetry(streams)
def output_schema(
self,
diff --git a/src/orcapod/core/output_bindings.py b/src/orcapod/core/output_bindings.py
index 89a5a1671..450b669ba 100644
--- a/src/orcapod/core/output_bindings.py
+++ b/src/orcapod/core/output_bindings.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Iterator
+from contextlib import contextmanager
from dataclasses import dataclass
from threading import RLock
from typing import Protocol, TypeAlias, TypeVar, cast
@@ -14,6 +15,13 @@
identity_lock = RLock()
+@contextmanager
+def identity_transaction() -> Iterator[None]:
+ """Keep a graph mutation's validation and publication in one identity read."""
+ with identity_lock:
+ yield
+
+
class _UpstreamElement(Protocol):
"""The graph edge needed to visit a stream without touching its data."""
diff --git a/src/orcapod/core/streams/base.py b/src/orcapod/core/streams/base.py
index 9628288fe..c0a19fa24 100644
--- a/src/orcapod/core/streams/base.py
+++ b/src/orcapod/core/streams/base.py
@@ -18,7 +18,7 @@
from contextvars import ContextVar
from datetime import datetime
from typing import TYPE_CHECKING, Any, Self, cast
-from weakref import ReferenceType, ref
+from weakref import ReferenceType, WeakMethod, ref
import pandas as pd
import polars as pl
@@ -27,6 +27,7 @@
from orcapod.core.output_bindings import (
OutputBindings,
capture_output_bindings,
+ invalidate_output_lineage,
require_current_bindings,
require_current_outputs,
)
@@ -48,6 +49,7 @@
default_note,
preview_html,
)
+from orcapod.errors import InconsistentSourceError
from orcapod.protocols.core_protocols import (
ArgumentGroup,
DataProtocol,
@@ -730,6 +732,7 @@ def _rename_map(
class StreamBase(TraceableBase, IdentityChainsMixin):
_recording_trackers: tuple[ReferenceType[TrackerProtocol], ...] = ()
+ _recorded_in_graph = False
def content_hash(self, hasher: SemanticHasherProtocol | None = None) -> ContentHash:
"""Return the pipeline's identity with its current sources."""
@@ -748,8 +751,12 @@ def _object_hash(self) -> ContentHash:
def _mark_recorded(self, manager: TrackerManagerProtocol) -> Self:
"""Remember recording provenance where a tracker supports weak references."""
+ from orcapod.pipeline.base import AbstractPipelineBase
+
recordings: list[ReferenceType[TrackerProtocol]] = []
for tracker in manager.get_active_trackers():
+ if isinstance(tracker, AbstractPipelineBase):
+ self._recorded_in_graph = True
try:
recordings.append(ref(tracker))
except TypeError:
@@ -763,6 +770,105 @@ def _was_recorded_by(self, tracker: TrackerProtocol) -> bool:
"""Check recording provenance without comparing stream hashes."""
return any(recording() is tracker for recording in self._recording_trackers)
+ _wire_capture_owners: tuple[ReferenceType[TrackerProtocol], ...] = ()
+
+ def _hold_wire_inputs(self, owner: TrackerProtocol) -> None:
+ """Keep the input identities while a blueprint needs their wire keys."""
+ with self._identity_lock:
+ owners = tuple(
+ held for held in self._wire_capture_owners if held() is not None
+ )
+ if not any(held() is owner for held in owners):
+ self._wire_capture_owners = (*owners, ref(owner))
+
+ def _captured_rewire_is_noop(self, inputs: tuple[StreamProtocol, ...]) -> bool:
+ """Refuse a change to inputs used by a live blueprint's wire projection."""
+ if not any(owner() is not None for owner in self._wire_capture_owners):
+ return False
+ upstreams = self.upstreams
+ if len(inputs) == len(upstreams) and all(
+ incoming is held for incoming, held in zip(inputs, upstreams, strict=True)
+ ):
+ return True
+ raise InconsistentSourceError(
+ f"Cannot rewire {self.label!r} because a captured blueprint uses its "
+ "input identities (ITL-1559). Create a new descriptor for the rewired inputs."
+ )
+
+ _rewire_validators: tuple[
+ WeakMethod[
+ Callable[
+ [StreamBase, tuple[StreamProtocol, ...]],
+ Callable[[], Callable[[], None]] | None,
+ ]
+ ],
+ ...,
+ ] = ()
+ _compiled_rewire_validator: (
+ WeakMethod[Callable[[StreamBase, tuple[StreamProtocol, ...]], None]] | None
+ ) = None
+
+ def _watch_compiled_rewire(
+ self, validate: Callable[[StreamBase, tuple[StreamProtocol, ...]], None]
+ ) -> None:
+ """Remember the graph that published this node's inputs."""
+ self._compiled_rewire_validator = WeakMethod(validate)
+
+ def _watch_rewire(
+ self,
+ validate: Callable[
+ [StreamBase, tuple[StreamProtocol, ...]],
+ Callable[[], Callable[[], None]] | None,
+ ],
+ ) -> None:
+ """Register a job that uses this descriptor's live inputs."""
+ validators = tuple(entry for entry in self._rewire_validators if entry())
+ if not any(entry() == validate for entry in validators):
+ self._rewire_validators = (*validators, WeakMethod(validate))
+
+ def _rewire(
+ self,
+ inputs: tuple[StreamProtocol, ...],
+ assign: Callable[[tuple[StreamProtocol, ...]], None],
+ ) -> None:
+ """Validate every affected graph before publishing new upstreams."""
+ previous = self.upstreams
+ if self._compiled_graph_key is not None:
+ if len(inputs) == len(previous) and all(
+ incoming is held
+ for incoming, held in zip(inputs, previous, strict=True)
+ ):
+ return
+ entry = self._compiled_rewire_validator
+ if entry is not None and (validate_compiled := entry()) is not None:
+ validate_compiled(self, inputs)
+ raise InconsistentSourceError(
+ f"Cannot rewire compiled step {self.label!r} (ITL-1559). "
+ "Build a new graph with the desired inputs."
+ )
+ prepare = [
+ prepare_rewire
+ for entry in self._rewire_validators
+ if (validate := entry()) is not None
+ if (prepare_rewire := validate(self, inputs)) is not None
+ ]
+
+ def install(upstreams: tuple[StreamProtocol, ...]) -> None:
+ assign(upstreams)
+ invalidate_output_lineage()
+ self._invalidate_pipeline_hash_cache()
+ self._invalidate_identity_chains(names=True)
+ self._forget_output_schema()
+
+ try:
+ install(inputs)
+ publications = [validate_proposal() for validate_proposal in prepare]
+ except BaseException:
+ install(previous)
+ raise
+ for publish in publications:
+ publish()
+
@property
def _identity_hasher(self) -> SemanticHasherProtocol:
"""Use the stream's structural hasher for the walk."""
diff --git a/src/orcapod/core/tracker.py b/src/orcapod/core/tracker.py
index 8ebceb775..ae06f6be5 100644
--- a/src/orcapod/core/tracker.py
+++ b/src/orcapod/core/tracker.py
@@ -2,10 +2,11 @@
from abc import ABC, abstractmethod
from collections.abc import Callable, Generator
-from contextlib import contextmanager
+from contextlib import AbstractContextManager, contextmanager
from functools import partial
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
+from orcapod.core.output_bindings import identity_transaction
from orcapod.protocols import core_protocols as cp
if TYPE_CHECKING:
@@ -19,6 +20,15 @@ class _PreparesInvocation(Protocol):
def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]: ...
+@runtime_checkable
+class _StagesInvocations(Protocol):
+ """Optional deferred publication when several trackers receive one call."""
+
+ def _stage_invocations(
+ self, declarations: set[int], publications: list[Callable[[], None]]
+ ) -> AbstractContextManager[None]: ...
+
+
class BasicTrackerManager:
def __init__(self) -> None:
self._active_trackers: list[cp.TrackerProtocol] = []
@@ -92,25 +102,36 @@ def record_side_effect_pod_invocation(
),
)
+ @identity_transaction()
def _record(
self,
make_invocation: Callable[[], PodInvocation],
record: Callable[[cp.TrackerProtocol], None],
) -> None:
- """Preflight nested captures before dispatching the recording callbacks."""
+ """Publish graph captures only after every tracker has accepted the call."""
trackers = self.get_active_trackers()
- if len(trackers) > 1:
- preparers = [
- tracker
- for tracker in trackers
- if isinstance(tracker, _PreparesInvocation)
- ]
- if preparers:
- invocation = make_invocation()
- for tracker in preparers:
- _ = tracker.prepare_invocation(invocation)
+ if len(trackers) == 1:
+ record(trackers[0])
+ return
+
+ preparers = [
+ tracker for tracker in trackers if isinstance(tracker, _PreparesInvocation)
+ ]
+ if preparers:
+ invocation = make_invocation()
+ for tracker in preparers:
+ _ = tracker.prepare_invocation(invocation)
+
+ declarations: set[int] = set()
+ publications: list[Callable[[], None]] = []
for tracker in trackers:
- record(tracker)
+ if isinstance(tracker, _StagesInvocations):
+ with tracker._stage_invocations(declarations, publications):
+ record(tracker)
+ else:
+ record(tracker)
+ for publish in publications:
+ publish()
@contextmanager
def no_tracking(self) -> Generator[None, Any, None]:
diff --git a/src/orcapod/errors.py b/src/orcapod/errors.py
index 91a77a590..90b24ff82 100644
--- a/src/orcapod/errors.py
+++ b/src/orcapod/errors.py
@@ -97,6 +97,10 @@ class TypeIdentityError(ValueError):
"""
+class UndefinedGraphMembershipError(TypeError):
+ """Raised for object membership queries with no defined answer on a public graph."""
+
+
class RecursiveTypeError(TypeError):
"""Raised when a class refers back to itself through its fields.
diff --git a/src/orcapod/pipeline/async_orchestrator.py b/src/orcapod/pipeline/async_orchestrator.py
index a83d789be..b3f5b46ec 100644
--- a/src/orcapod/pipeline/async_orchestrator.py
+++ b/src/orcapod/pipeline/async_orchestrator.py
@@ -14,8 +14,7 @@
import threading
import uuid
import warnings
-from collections import defaultdict
-from collections.abc import Callable, Coroutine
+from collections.abc import Callable, Coroutine, Hashable
from typing import TYPE_CHECKING, Any, Literal, TypeVar
from orcapod.channels import BroadcastChannel, Channel
@@ -24,10 +23,10 @@
OrcapodDatabaseWriteError,
TypeIdentityError,
)
+from orcapod.pipeline.dag import NodeMap, node_key_in, nodes_of, operand_key_in
+
from orcapod.core.output_bindings import capture_output_bindings
-from orcapod.protocols.core_protocols import StreamProtocol
from orcapod.pipeline.result import OrchestratorResult, StreamsOnRead
-from orcapod.utils.database_errors import keep_database_error
from orcapod.protocols.node_protocols import (
is_function_node,
is_operator_node,
@@ -35,6 +34,7 @@
is_side_effect_node,
is_source_node,
)
+from orcapod.utils.database_errors import keep_database_error
if TYPE_CHECKING:
from collections.abc import Mapping
@@ -43,6 +43,7 @@
from orcapod.pipeline.dag import GraphProtocol
from orcapod.protocols.core_protocols import (
DataProtocol,
+ StreamProtocol,
TagProtocol,
)
from orcapod.protocols.observability_protocols import ExecutionObserverProtocol
@@ -230,21 +231,29 @@ async def _run_async(
buf = self._buffer_size
# Build edge maps
- in_edges: dict[Any, list[Any]] = defaultdict(list)
- for upstream_node, downstream_node in graph.edges():
- in_edges[downstream_node].append(upstream_node)
- out_edges: dict[Any, list[tuple[Any, int]]] = defaultdict(list)
- for node, predecessors in in_edges.items():
+ in_edges: NodeMap[Any, list[Any]] = NodeMap(graph)
+ out_edges: NodeMap[Any, list[tuple[Hashable, int]]] = NodeMap(graph)
+ for upstream, downstream in graph.edges():
+ in_edges.setdefault(downstream, []).append(upstream)
+ for node in nodes_of(graph):
+ predecessors = in_edges.get(node, [])
if is_operator_node(node):
- predecessors = in_edges[node] = ordered_operator_inputs(
- node, predecessors
+ predecessors = ordered_operator_inputs(
+ node,
+ predecessors,
+ key=lambda upstream: operand_key_in(graph, upstream),
)
+ in_edges[node] = predecessors
for position, upstream in enumerate(predecessors):
- out_edges[upstream].append((node, position))
+ out_edges.setdefault(upstream, []).append(
+ (node_key_in(graph, node), position)
+ )
- # Create channels for each edge
- node_output_channels: dict[Any, Channel | BroadcastChannel] = {}
- edge_readers: dict[tuple[Any, int], Any] = {}
+ # Every operand position gets its own reader, including repeats.
+ node_output_channels: NodeMap[Any, Channel[Any] | BroadcastChannel[Any]] = (
+ NodeMap(graph)
+ )
+ edge_readers: dict[tuple[Hashable, int], Any] = {}
for node, downstreams in out_edges.items():
if len(downstreams) == 1:
@@ -266,7 +275,9 @@ async def _run_async(
terminal_channels.append(ch)
# Result collection
- collectors: dict[Any, list[tuple[TagProtocol, DataProtocol]]] = {}
+ collectors: NodeMap[Any, list[tuple[TagProtocol, DataProtocol]]] = NodeMap(
+ graph
+ )
bindings_at_collection = {}
if materialize_results:
for node in topo_order:
@@ -294,7 +305,11 @@ def collected_output(
# own inputs are read and discarded, so no producer blocks on
# a channel nobody reads.
for position in range(len(in_edges.get(node, []))):
- tg.create_task(_drain(edge_readers[(node, position)]))
+ tg.create_task(
+ _drain(
+ edge_readers[(node_key_in(graph, node), position)]
+ )
+ )
_start_node(
tg,
failed_nodes,
@@ -315,7 +330,7 @@ def collected_output(
raise ValueError(
f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}"
)
- input_reader = edge_readers[(node, 0)]
+ input_reader = edge_readers[(node_key_in(graph, node), 0)]
_start_node(
tg,
failed_nodes,
@@ -332,7 +347,7 @@ def collected_output(
elif is_operator_node(node):
predecessors = in_edges.get(node, [])
input_readers = [
- edge_readers[(node, position)]
+ edge_readers[(node_key_in(graph, node), position)]
for position in range(len(predecessors))
]
_start_node(
@@ -352,7 +367,7 @@ def collected_output(
raise ValueError(
"SideEffectNode expects exactly 1 upstream, got 0"
)
- input_reader = edge_readers[(node, 0)]
+ input_reader = edge_readers[(node_key_in(graph, node), 0)]
# In a load-only run the node passes its rows on and delivers
# nothing.
_start_node(
@@ -378,7 +393,7 @@ def collected_output(
return OrchestratorResult(
node_outputs=(
- StreamsOnRead(collectors, collected_output)
+ StreamsOnRead(collectors, collected_output, graph=graph)
if materialize_results
else {}
)
@@ -575,7 +590,7 @@ def _async_function_labels(graph: GraphProtocol[Any]) -> frozenset[str]:
The labels.
"""
labels: set[str] = set()
- for node in graph.nodes():
+ for node in nodes_of(graph):
label: str = node.label
if not (is_function_node(node) or is_side_effect_function_node(node)):
continue
diff --git a/src/orcapod/pipeline/base.py b/src/orcapod/pipeline/base.py
index 6b6ed8d26..e0946ef29 100644
--- a/src/orcapod/pipeline/base.py
+++ b/src/orcapod/pipeline/base.py
@@ -4,49 +4,81 @@
import logging
from abc import ABC, abstractmethod
-from collections import ChainMap
from collections.abc import Callable, Hashable, Iterable, Iterator, Mapping
-from dataclasses import dataclass
-from functools import partial
+from contextlib import contextmanager
+from contextvars import ContextVar
+from copy import copy
+from dataclasses import dataclass, field
from itertools import chain
-from typing import TYPE_CHECKING, Any, Generic, Literal, TypeVar, cast
-from weakref import ReferenceType, ref
-
-from orcapod.core.base import ContentIdentifiableBase
-from orcapod.core.identity_chains import graph_hash
+from types import MappingProxyType
+from typing import TYPE_CHECKING, Any, ClassVar, Generic, Literal, TypeVar, cast
+from weakref import ref
+
+from orcapod.core.identity_chains import (
+ IdentityChainsMixin,
+ assign_graph_key,
+ graph_hash,
+ graph_key,
+)
from orcapod.core.nodes.function_node import FunctionNodeBase
+from orcapod.core.nodes.source_node import (
+ SourceJobNode,
+ SourceNode,
+ SourceNodeBase,
+ slot_name_for,
+)
+from orcapod.core.output_bindings import identity_transaction
+from orcapod.core.sources.base import RootSource
+from orcapod.core.streams.base import StreamBase
from orcapod.core.tracker import AutoRegisteringContextBasedTracker
-from orcapod.pipeline.dag import OrcaDAG
+from orcapod.errors import InconsistentSourceError, UnboundSourceError
+from orcapod.pipeline.dag import (
+ OrcaDAG,
+ default_node_key,
+ keyed_dag,
+ node_key_in,
+ public_dag,
+ require_membership_key,
+)
from orcapod.pipeline.pod_invocation import (
FunctionInvocation,
OperatorInvocation,
PodInvocation,
SideEffectInvocation,
)
+from orcapod.pipeline.restrictions import streams_beneath
from orcapod.pipeline.source_consistency import (
invocation_source_uses,
+ live_inputs,
require_consistent_sources,
+ require_distinct_slot_bindings,
require_live_source_bindings,
)
-from orcapod.side_effects import SideEffectNode
from orcapod.protocols import core_protocols as cp
+from orcapod.side_effects import SideEffectNode
from orcapod.utils.lazy_module import LazyModule
if TYPE_CHECKING:
import networkx as nx
+
from orcapod.pipeline.diagram import PipelineDiagram
- from orcapod.types.provenance import Highlight
- from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
from orcapod.pipeline.source_consistency import SourceUse
- from orcapod.pipeline.pod_invocation import CaptureStreamKeys
from orcapod.protocols.core_protocols import StreamProtocol
- from orcapod.protocols.hashing_protocols import IdentityChainProtocol
+ from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
+ from orcapod.protocols.hashing_protocols import (
+ ContentIdentifiableProtocol,
+ IdentityChainProtocol,
+ )
+ from orcapod.types.provenance import Highlight
else:
nx = LazyModule("networkx")
logger = logging.getLogger(__name__)
NodeT = TypeVar("NodeT", bound=Hashable)
+_capture_batch: ContextVar[tuple[object, set[int], list[Callable[[], None]]] | None] = (
+ ContextVar("capture_batch", default=None)
+)
def _refuse_sources_sharing_a_slot_name(
@@ -67,8 +99,6 @@ def _refuse_sources_sharing_a_slot_name(
Raises:
SourceSlotNameCollisionError: Naming every full source id and the remedy.
"""
- from orcapod.core.sources.base import RootSource
-
sources = [s for s in streams if isinstance(s, RootSource)]
if len(sources) < 2:
return
@@ -87,24 +117,191 @@ def _refuse_sources_sharing_a_slot_name(
)
+def _leaf_object(stream: cp.StreamProtocol) -> cp.StreamProtocol:
+ if isinstance(stream, SourceJobNode):
+ return stream.bound_source if stream.bound_source is not None else stream
+ if isinstance(stream, SourceNode) and stream._declared_stream is not None:
+ return stream._declared_stream
+ return stream
+
+
+def _capture_object_ref(value: object) -> Callable[[], object | None]:
+ """Track object identity without retaining coalesced calls where possible."""
+ try:
+ return ref(value)
+ except TypeError:
+ # A user implementation of a pod or stream protocol may use slots.
+ return lambda: value
+
+
+def _has_execution_binding(stream: StreamProtocol) -> bool:
+ """Return whether a slot has concrete input data for execution identity."""
+ pending = [stream]
+ seen: set[int] = set()
+ while pending:
+ current = pending.pop()
+ if isinstance(current, SourceNode) or (
+ isinstance(current, SourceJobNode) and current.bound_source is None
+ ):
+ return False
+ token = id(current)
+ if token not in seen:
+ seen.add(token)
+ pending.extend(streams_beneath(current))
+ return True
+
+
+def _legacy_key(element: ContentIdentifiableProtocol) -> str | None:
+ """Read a legacy content key where the element implements one."""
+ try:
+ return element.content_hash().to_string()
+ except UnboundSourceError:
+ return (
+ graph_hash(element).to_string()
+ if isinstance(element, IdentityChainsMixin)
+ else None
+ )
+ except NotImplementedError:
+ return None
+
+
+def _slot_step_collision(name: str) -> None:
+ raise InconsistentSourceError(
+ f"Slot {name!r} and an in-graph step share a legacy execution "
+ "identity. Capture the step inside the graph and reuse its "
+ "output (ITL-1559)."
+ )
+
+
+class ExecutionRoles:
+ """Index the concrete legacy keys held by distinct slots and retained steps."""
+
+ def __init__(self) -> None:
+ self._slots: dict[str, str] = {}
+ self._steps: dict[str, set[str]] = {}
+ self._step_roles: dict[str, str] = {}
+
+ def shared_step_keys(self) -> set[str]:
+ """Return steps whose legacy digest is also held by a different step."""
+ return {
+ key for steps in self._steps.values() if len(steps) > 1 for key in steps
+ }
+
+ def prepare(
+ self,
+ slots: Iterable[tuple[str, str | None]],
+ step_key: str | None = None,
+ step_role: str | None = None,
+ ) -> Callable[[], None]:
+ """Validate proposed roles and return their publication callback."""
+ staged: dict[str, str] = {}
+ for name, digest in slots:
+ if digest is None:
+ continue
+ first = self._slots.get(digest, staged.setdefault(digest, name))
+ if first != name:
+ raise InconsistentSourceError(
+ f"Slots {first!r} and {name!r} share a legacy execution "
+ "identity. Bind distinct sources to the slots, or read "
+ "through one slot and branch from it (ITL-1559)."
+ )
+
+ for role, name in staged.items():
+ steps = self._steps.get(role)
+ if steps and (len(steps) > 1 or step_key not in steps):
+ _slot_step_collision(name)
+ if step_role is not None:
+ name = self._slots.get(step_role, staged.get(step_role))
+ if name is not None:
+ _slot_step_collision(name)
+
+ def publish() -> None:
+ for role, name in staged.items():
+ self._slots.setdefault(role, name)
+ if step_key is not None:
+ old_role = self._step_roles.pop(step_key, None)
+ if old_role is not None:
+ steps = self._steps[old_role]
+ steps.remove(step_key)
+ if not steps:
+ del self._steps[old_role]
+ if step_role is not None:
+ self._step_roles[step_key] = step_role
+ self._steps.setdefault(step_role, set()).add(step_key)
+
+ return publish
+
+
+def execution_roles_for(
+ slots: Iterable[tuple[str, StreamProtocol]],
+ steps: Iterable[tuple[str, ContentIdentifiableProtocol]],
+) -> ExecutionRoles:
+ """Build a validated index for a resolved graph."""
+ roles = ExecutionRoles()
+ roles.prepare(
+ (
+ name,
+ _legacy_key(
+ stream.bound_source
+ if isinstance(stream, SourceJobNode) and stream.bound_source is not None
+ else stream
+ ),
+ )
+ for name, stream in slots
+ if _has_execution_binding(stream)
+ )()
+ for key, step in steps:
+ roles.prepare((), key, _legacy_key(step))()
+ return roles
+
+
+def _leaf_description(stream: cp.StreamProtocol, name: str) -> str:
+ if isinstance(stream, RootSource):
+ return f"source {stream.source_id!r}"
+ if isinstance(stream, SourceNodeBase):
+ return f"declared slot {stream.name!r}"
+ kind = "prebuilt stream" if stream.upstreams else "raw stream"
+ return f"{kind} {name!r}"
+
+
@dataclass(frozen=True)
class InvocationGraph:
"""Interchange value object between Pipeline and PipelineJob.
Carries a topologically ordered tuple of ``PodInvocation`` objects and a
- mapping from content-hash string to the corresponding source stream.
+ mapping from node-key string to the corresponding source stream.
Both classes exchange representations by converting to this neutral form
via ``to_invocations()`` and reconstructing via ``from_invocations()``.
Args:
invocations: Topologically ordered sequence of pod invocations
(sources excluded).
- source_streams: Mapping of content-hash string → source stream
+ source_streams: Mapping of node-key string → source stream
(nodes whose invocation was not recorded in the pipeline).
+ outputs: Compiled outputs paired with invocations in an exported graph.
"""
invocations: tuple[PodInvocation, ...]
- source_streams: dict[str, Any] # hash → StreamProtocol-compatible node
+ source_streams: Mapping[str, StreamProtocol]
+ outputs: tuple[StreamProtocol, ...] = ()
+ _exported: bool = field(default=False, init=False, repr=False, compare=False)
+
+
+@dataclass(frozen=True)
+class _CaptureName:
+ """A graph slot name or a step's candidate display label."""
+
+ key: str
+ stream: StreamProtocol
+ step: bool = False
+
+
+class _NodeLabels(dict[str, Any]):
+ """A copy of the graph's label lookup with object membership refused."""
+
+ def __contains__(self, key: object) -> bool:
+ require_membership_key(key)
+ return super().__contains__(key)
class AbstractPipelineBase(Generic[NodeT], AutoRegisteringContextBasedTracker, ABC):
@@ -141,17 +338,27 @@ def __init__(
self._name: tuple[str, ...] = (name,) if isinstance(name, str) else tuple(name)
# --- Additive recording state (never cleared) -----------------
- # Maps capture key → PodInvocation for each recorded invocation.
+ # Maps node key → PodInvocation for each recorded invocation.
self._invocation_lut: dict[str, PodInvocation] = {}
- self._capture_key_generation = ContentIdentifiableBase.content_hash_generation()
- self._capture_stream_keys: dict[int, CaptureStreamKeys] = {}
# Ordered graph keys chosen at capture, which stay fixed across rebindings.
self._invocation_input_keys: dict[str, tuple[str, ...]] = {}
- # Maps content-hash-string → raw stream for each unregistered upstream.
+ # Maps node key → raw stream for each unregistered upstream.
self._source_streams: dict[str, Any] = {}
- # Topology graph — vertices and edges are content-hash strings.
+ self._capture_leaves: dict[str, tuple[str, StreamProtocol]] = {}
+ self._execution_roles = ExecutionRoles()
+ self._unbound_keys: set[str] = set()
+ self._capture_names: dict[str, dict[str, _CaptureName]] = {}
+ self._leaf_names_by_object: dict[tuple[bool, int], dict[str, None]] = {}
+ self._capture_owner = object()
+ self._import_publications: list[Callable[[], None]] | None = None
+ self._capture_nodes: dict[str, StreamProtocol] = {}
+ self._captured_calls: dict[
+ tuple[int, ...], tuple[str, tuple[Callable[[], object | None], ...]]
+ ] = {}
+ # Topology graph — vertices and edges are node-key strings.
# Additive: persists and grows across multiple with-blocks.
- self._hash_graph: "nx.DiGraph" = nx.DiGraph()
+ self._capture_graph: "nx.DiGraph[str]" = nx.DiGraph()
+ self._hash_graph: "nx.DiGraph[str]" = self._capture_graph
# --- Compiled state (populated / replaced by compile()) --------
self._persistent_node_map: dict[str, NodeT] = {}
@@ -174,15 +381,10 @@ def name(self) -> tuple[str, ...]:
"""Pipeline name tuple."""
return self._name
- @property
- def graph(self) -> "nx.DiGraph":
- """Directed hash graph of accumulated pipeline structure."""
- return self._hash_graph
-
@property
def nodes(self) -> dict[str, Any]:
"""Copy of the compiled nodes dict (label → node)."""
- return self._nodes.copy()
+ return _NodeLabels(self._nodes)
@property
def source_pods(self) -> dict[str, Any]:
@@ -235,7 +437,10 @@ def dag(self) -> OrcaDAG[NodeT]:
Returns an ``OrcaDAG`` whose vertices are the compiled node objects
(``GraphNode`` for ``Pipeline``, ``JobNode`` for ``PipelineJob``) and
- whose edges follow the data-flow topology.
+ whose edges follow the data-flow topology. Use ``nodes[label]`` to
+ access a node by label. The DAG holds its own vertices and raises
+ ``UndefinedGraphMembershipError`` for membership of foreign stream, node,
+ and invocation objects. Use the pipeline API to change the topology.
Raises:
RuntimeError: If the pipeline has not been compiled yet.
@@ -251,6 +456,8 @@ def dag(self) -> OrcaDAG[NodeT]:
# Abstract — subclass node-factory declarations
# ------------------------------------------------------------------
+ _capture_receiver: ClassVar[Literal["pipeline", "job"]]
+
@property
@abstractmethod
def source_node_class(self) -> type:
@@ -330,20 +537,320 @@ def record_side_effect_pod_invocation(
SideEffectInvocation(pod=pod, input_streams=(input_stream,), label=label)
)
- def _record_invocation(self, invocation: PodInvocation) -> None:
+ @identity_transaction()
+ def _record_invocation(
+ self, invocation: PodInvocation, imported: dict[int, str] | None = None
+ ) -> str:
"""Validate the invocation and record it immediately."""
- key, input_keys = self._validate_invocation(invocation, remember_streams=True)
- self._remember_invocation(key, invocation, input_keys)
- self._hash_graph.add_node(key)
- for upstream, upstream_hash in zip(
- invocation.input_streams, input_keys, strict=True
+ key, publish = self._prepare_recording(invocation, imported)
+ batch = _capture_batch.get()
+ if batch is not None and batch[0] is self and imported is None:
+ _, declarations, publications = batch
+ claims = {
+ id(stream): stream
+ for stream in invocation.input_streams
+ if isinstance(stream, SourceNode) and stream._compiled_graph_key is None
+ }
+ for token, stream in claims.items():
+ if token in declarations:
+ raise self._foreign_capture_input(stream)
+ declarations.update(claims)
+ publications.append(publish)
+ else:
+ publish()
+ return key
+
+ def _prepare_recording(
+ self, invocation: PodInvocation, imported: dict[int, str] | None = None
+ ) -> tuple[str, Callable[[], None]]:
+ """Check the entire capture and return its publication callback."""
+ key, input_keys, node, leaves = self._validate_invocation(invocation, imported)
+ call = (invocation.pod, *invocation.input_streams)
+ call_id = tuple(map(id, call))
+ previous_key = self._captured_call_key(call, call_id)
+ if previous_key is not None and previous_key != key:
+ raise InconsistentSourceError(
+ "Capturing the same pod and input objects under a different graph key "
+ "is not supported yet (ITL-1559). Create a new descriptor for the "
+ "rewired inputs."
+ )
+ retained = self._prefer_invocation(invocation, self._invocation_lut.get(key))
+ publish_roles = self._prepare_capture_roles(
+ invocation, key, input_keys, leaves, retained
+ )
+ captured: dict[str, PodInvocation | StreamProtocol] = {key: invocation}
+ captured.update((leaf_key, stream) for leaf_key, stream, _ in leaves.values())
+ publish_wire_keys = self._prepare_wire_keys(captured)
+
+ def publish() -> None:
+ publish_wire_keys()
+ publish_roles()
+ for stream in invocation.input_streams:
+ if isinstance(stream, SourceNode) and (
+ stream._compiled_graph_key is None
+ and (imported is None or id(stream) not in imported)
+ ):
+ self._publish_capture_effect(
+ lambda stream=stream: setattr(
+ stream, "_capture_owner", self._capture_owner
+ )
+ )
+ for name, (leaf_key, stream, slot) in leaves.items():
+ self._remember_leaf(name, leaf_key, stream, slot)
+ if previous_key is None:
+ self._captured_calls[call_id] = (
+ key,
+ tuple(map(_capture_object_ref, call)),
+ )
+ self._remember_invocation(key, invocation, input_keys)
+ previous_node = self._capture_nodes.get(key)
+ if self._invocation_lut[key] is invocation and (
+ previous_node is None or previous_node.label != node.label
+ ):
+ if previous_node is not None:
+ del self._capture_names[previous_node.label][key]
+ self._capture_nodes[key] = node
+ self._capture_names.setdefault(node.label, {})[key] = _CaptureName(
+ key, node, step=True
+ )
+ self._record_edges(key)
+
+ return key, publish
+
+ def _prepare_capture_roles(
+ self,
+ invocation: PodInvocation,
+ key: str,
+ input_keys: tuple[str, ...],
+ leaves: dict[str, tuple[str, StreamProtocol, SourceNodeBase]],
+ retained: bool,
+ ) -> Callable[[], None]:
+ """Check the execution roles introduced by one recording."""
+ unbound_leaves = {
+ leaf_key
+ for leaf_key, stream, _ in leaves.values()
+ if not _has_execution_binding(stream)
+ }
+ unbound = (
+ bool(unbound_leaves)
+ or any(input_key in self._unbound_keys for input_key in input_keys)
+ or self._capture_receiver == "pipeline"
+ and self._node_graph is not None
+ and any(
+ self._node_graph._contains_node(stream) # pyright: ignore[reportPrivateUsage] # capture checks the receiving graph's objects
+ for stream in invocation.input_streams
+ )
+ )
+ publish_roles = self._execution_roles.prepare(
+ (
+ (name, _legacy_key(stream))
+ for name, (leaf_key, stream, _) in leaves.items()
+ if leaf_key not in unbound_leaves
+ ),
+ key if retained else None,
+ _legacy_key(invocation) if retained and not unbound else None,
+ )
+
+ def publish() -> None:
+ publish_roles()
+ self._unbound_keys.update(unbound_leaves)
+ if retained:
+ if unbound:
+ self._unbound_keys.add(key)
+ else:
+ self._unbound_keys.discard(key)
+
+ return publish
+
+ def _captured_call_key(
+ self, call: tuple[object, ...], call_id: tuple[int, ...]
+ ) -> str | None:
+ """Look up the capture only while the original call objects match."""
+ entry = self._captured_calls.get(call_id)
+ if entry is None:
+ return None
+ key, objects = entry
+ if all(
+ reference() is value for reference, value in zip(objects, call, strict=True)
):
- self._hash_graph.add_edge(upstream_hash, key)
- self._source_streams.setdefault(upstream_hash, upstream)
+ return key
+ return None
+
+ def _held_key(self, stream: StreamProtocol) -> str | None:
+ if self._node_graph is not None and self._node_graph._contains_node(stream): # pyright: ignore[reportPrivateUsage] # capture checks the receiving graph's objects
+ return str(node_key_in(self._node_graph, stream)) # pyright: ignore[reportArgumentType] # membership proved above
+ if isinstance(stream, StreamBase) and stream._was_recorded_by(self):
+ call = (stream.producer, *stream.upstreams)
+ return self._captured_call_key(call, tuple(map(id, call)))
+ return None
+
+ def _prepare_wire_keys(
+ self, captured: dict[str, PodInvocation | StreamProtocol]
+ ) -> Callable[[], None]:
+ """Prepare legacy wire keys when the capture itself is serializable."""
+ return lambda: None
+
+ def _publish_capture_effect(self, publish: Callable[[], None]) -> None:
+ """Delay changes to caller-owned objects until reconstruction succeeds."""
+ if self._import_publications is None:
+ publish()
+ else:
+ self._import_publications.append(publish)
+
+ def _record_edges(self, key: str) -> None:
+ """Record each input occurrence with its argument position."""
+ self._capture_graph.add_node(key)
+ self._capture_graph.remove_edges_from(tuple(self._capture_graph.in_edges(key)))
+ for position, upstream in enumerate(self._invocation_input_keys[key]):
+ if not self._capture_graph.has_edge(upstream, key):
+ self._capture_graph.add_edge(upstream, key, positions=())
+ edge = self._capture_graph[upstream][key]
+ edge["positions"] += (position,)
+
+ def _validate_capture_state(self) -> None:
+ """Check that this graph can record a new invocation."""
+
+ def _validate_capture_root(self, stream: RootSource) -> None:
+ """Check receiver-specific requirements for a root source."""
+
+ def _capture_input_key(
+ self, stream: StreamProtocol, imported: dict[int, str], *, binding: bool = False
+ ) -> str | None:
+ """Classify a capture input and check wrappers before choosing a slot."""
+ from orcapod.core.function_pod import FunctionPodStream
+ from orcapod.core.nodes.operator_node import OperatorNodeBase
+ from orcapod.core.operators.static_output_pod import (
+ DynamicPodStream,
+ RowsOnRead,
+ )
+ from orcapod.core.streams.arrow_table_stream import ArrowTableStream
+ from orcapod.side_effects import SideEffectPodStream
+
+ pending = [(stream, False)]
+ seen: set[tuple[int, bool]] = set()
+ resolved: str | None = None
+ while pending:
+ current, prebuilt = pending.pop()
+ visit = id(current), prebuilt
+ if visit in seen:
+ continue
+ seen.add(visit)
+ if current is stream and id(current) in imported:
+ return imported[id(current)]
+ held = (
+ self._held_key(current)
+ if isinstance(current, (StreamBase, SourceNodeBase))
+ else None
+ )
+ if held is not None and not binding:
+ if prebuilt:
+ name = self._capture_boundary_name(current)
+ raise InconsistentSourceError(
+ f"Capturing a prebuilt stream over source slot {name!r} "
+ f"is not supported yet (ITL-1559). Build the step inside the "
+ f"{self._capture_receiver} from its slot, or pass the source itself."
+ )
+ if current is stream:
+ if (
+ self._capture_receiver == "pipeline"
+ and isinstance(current, StreamBase)
+ and current._compiled_graph_key is not None
+ ):
+ raise InconsistentSourceError(
+ f"Capturing compiled blueprint step {current.label!r} "
+ "is not supported yet (ITL-1559). Pass the original "
+ "invocation stream to add a downstream step."
+ )
+ resolved = held
+ elif (
+ held is not None
+ or isinstance(current, SourceJobNode)
+ or isinstance(current, SourceNode)
+ and current._capture_owner is not None
+ and (binding or current._capture_owner is not self._capture_owner)
+ or isinstance(current, IdentityChainsMixin)
+ and current._compiled_graph_key is not None
+ or isinstance(current, StreamBase)
+ and current._recorded_in_graph
+ ):
+ raise self._foreign_capture_input(current)
+ elif isinstance(current, SourceNode):
+ if current._declared_stream is not None:
+ pending.append((current._declared_stream, prebuilt))
+ elif isinstance(current, RootSource):
+ self._validate_capture_root(current)
+ elif isinstance(
+ current,
+ (
+ ArrowTableStream,
+ DynamicPodStream,
+ FunctionNodeBase,
+ FunctionPodStream,
+ OperatorNodeBase,
+ RowsOnRead,
+ SideEffectNode,
+ SideEffectPodStream,
+ ),
+ ):
+ prebuilt = True
+ else:
+ raise InconsistentSourceError(
+ f"Capturing an input of type {type(current).__name__!r} is not "
+ "supported yet (ITL-1559). Pass a source or a supported stream."
+ )
+ pending.extend((upstream, prebuilt) for upstream in live_inputs(current))
+ return resolved
- def _validate_capture_sources(self, streams: Iterable[StreamProtocol]) -> None:
- """Check the streams of a new capture before recording it."""
+ def _rewire_input_keys(
+ self,
+ node: StreamBase,
+ inputs: tuple[StreamProtocol, ...],
+ *,
+ binding: bool = False,
+ ) -> tuple[str | None, ...]:
+ """Classify introduced edges using the capture boundary."""
+ return tuple(
+ self._held_key(stream)
+ if any(stream is previous for previous in node.upstreams)
+ else self._capture_input_key(stream, {}, binding=binding)
+ for stream in inputs
+ )
+ def _validate_compiled_rewire(
+ self, node: StreamBase, inputs: tuple[StreamProtocol, ...]
+ ) -> None:
+ """Check input ownership before a compiled node refuses a topology edit."""
+ _ = self._rewire_input_keys(node, inputs)
+
+ def _foreign_capture_input(self, stream: StreamProtocol) -> InconsistentSourceError:
+ name = self._capture_boundary_name(stream)
+ return InconsistentSourceError(
+ f"Capturing source slot {name!r} from outside this {self._capture_receiver} "
+ "is not supported yet (ITL-1559). Pass the source itself, or "
+ "use node.as_source() to read another job's stored results."
+ )
+
+ @staticmethod
+ def _capture_boundary_name(stream: StreamProtocol) -> str:
+ """Find a diagnostic slot name without reading data or hashing."""
+ pending = [stream]
+ seen: set[int] = set()
+ while pending:
+ current = pending.pop()
+ if id(current) in seen:
+ continue
+ seen.add(id(current))
+ if isinstance(current, SourceNodeBase):
+ return current.name
+ if isinstance(current, RootSource):
+ return current.source_name
+ upstreams = live_inputs(current)
+ if not upstreams and isinstance(current, StreamBase):
+ upstreams = current._identity_inputs()
+ pending.extend(reversed(upstreams))
+ return stream.label
+
+ @identity_transaction()
def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]:
"""Validate *invocation* and prepare to update the topology graph.
@@ -358,105 +865,275 @@ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]:
Raises:
ValueError: If the invocation cannot be recorded in the current graph.
"""
- self._validate_invocation(invocation)
- return partial(self._record_invocation, invocation)
-
- def _validate_invocation(
- self, invocation: PodInvocation, *, remember_streams: bool = False
- ) -> tuple[str, tuple[str, ...]]:
- """Check whether a capture can be recorded and resolve its graph keys.
+ self._prepare_recording(invocation)
- Non-source nodes in ``_persistent_node_map`` are keyed by the
- corresponding invocation's content hash while bound, and its node
- hash while unbound. A ``Pipeline`` promotes concrete inputs to
- unbound source declarations when it compiles. The persistent node map
- keeps the keys from capture so its topology can still be resolved.
+ def record() -> None:
+ _ = self._record_invocation(invocation)
- Args:
- invocation: The pod invocation to record.
+ return record
- Returns:
- The invocation hash and the upstream stream hashes.
+ @contextmanager
+ def _stage_invocations(
+ self, declarations: set[int], publications: list[Callable[[], None]]
+ ) -> Iterator[None]:
+ """Collect publications for a tracker dispatch without changing the graph."""
+ token = _capture_batch.set((self, declarations, publications))
+ try:
+ yield
+ finally:
+ _capture_batch.reset(token)
- Raises:
- ValueError: If the invocation reads a source under another restriction
- than the pipeline's streams read it under now, or two of its inputs
- read one source under two restrictions (ITL-1218), whatever streams
- lead there. Nothing is recorded then.
- """
+ def _validate_invocation(
+ self, invocation: PodInvocation, imported: dict[int, str] | None = None
+ ) -> tuple[
+ str,
+ tuple[str, ...],
+ StreamProtocol,
+ dict[str, tuple[str, StreamProtocol, SourceNodeBase]],
+ ]:
+ """Resolve receiving slot names and validate the capture before publishing it."""
from orcapod.pipeline.restrictions import require_one_restriction
inputs = tuple(invocation.input_streams)
- self._validate_capture_sources(inputs)
+ self._validate_capture_state()
+ owned = imported or {}
+ resolved = [self._capture_input_key(stream, owned) for stream in inputs]
+ names = [
+ None if key is not None else self._leaf_name(stream)
+ for stream, key in zip(inputs, resolved, strict=True)
+ ]
+
uses = tuple(self._source_uses(invocation))
require_live_source_bindings(stream for _, stream in uses)
- capture_streams = self._capture_key_memo()
- key, input_keys = invocation.capture_keys(
- capture_streams, self._input_graph_key
- )
- # Checked before anything is recorded, so a refused invocation leaves the
- # graph as it was. A restriction does not change a source's identity, so the
- # pipeline keeps one restriction (or none) per source identity, whatever
- # streams lead to it: every source this invocation reads is checked with
- # every source the pipeline's streams read now (nothing is remembered: a
- # slot rebound since the last invocation changes what they read).
require_consistent_sources(uses)
require_one_restriction(stream for _, stream in uses)
- if remember_streams:
- self._remember_capture_stream_keys(capture_streams.maps[0])
- return key, input_keys
-
- def _input_graph_key(self, upstream: StreamProtocol) -> str:
- """Return the capture graph key for an invocation input."""
- return graph_hash(upstream).to_string()
-
- def _capture_key_memo(self) -> ChainMap[int, CaptureStreamKeys]:
- """Reuse upstream keys until binding or upstream invalidation."""
- generation = ContentIdentifiableBase.content_hash_generation()
- if self._capture_key_generation is not generation:
- self._capture_stream_keys.clear()
- self._capture_key_generation = generation
- # Stage new entries until validation succeeds.
- return ChainMap({}, self._capture_stream_keys)
-
- def _remember_capture_stream_keys(
- self, keys: Mapping[int, CaptureStreamKeys]
- ) -> None:
- """Memoize keys without holding on to streams that coalesced at capture."""
- owner = ref(self)
- for identity, (stream, key) in keys.items():
- if isinstance(stream, ReferenceType):
+ new_leaves: dict[str, tuple[str, StreamProtocol, SourceNodeBase]] = {}
+ namespace: dict[str, list[_CaptureName]] = {}
+ leaf_names: dict[tuple[bool, int], dict[str, None]] = {}
+ for index, (name, stream) in enumerate(zip(names, inputs, strict=True)):
+ if name is None:
continue
+ self._check_leaf_object(leaf_names, name, stream)
+ previous = new_leaves.get(name) or self._capture_leaves.get(name)
+ if previous is not None:
+ leaf_key = previous[0]
+ self._claim_capture_name(
+ namespace, name, _CaptureName(leaf_key, stream)
+ )
+ else:
+ self._claim_capture_name(namespace, name, _CaptureName("", stream))
+ slot = self._capture_slot(stream, name)
+ leaf_key = graph_key(slot, use_published=False)
+ new_leaves[name] = (leaf_key, stream, slot)
+ namespace[name] = [_CaptureName(leaf_key, stream)]
+ leaf_names.setdefault(self._leaf_object_key(stream), {})[name] = None
+ resolved[index] = leaf_key
+
+ input_keys = tuple(key for key in resolved if key is not None)
+ upstreams = tuple(
+ self._capture_nodes[key] if name not in new_leaves else new_leaves[name][2]
+ for name, key in zip(names, input_keys, strict=True)
+ )
+ node = self._node_from_invocation(invocation, upstreams)
+ key = graph_key(node, use_published=False)
+ self._claim_capture_name(
+ namespace,
+ node.label,
+ _CaptureName(key, node, step=True),
+ input_keys
+ if imported is not None
+ else tuple(leaf_key for leaf_key, _, _ in new_leaves.values()),
+ )
+ return key, input_keys, node, new_leaves
+
+ def _leaf_object_key(self, stream: StreamProtocol) -> tuple[bool, int]:
+ declared = self._capture_receiver == "pipeline" and isinstance(
+ stream, SourceNode
+ )
+ return declared, id(_leaf_object(stream))
- def discard(
- dead: ReferenceType[StreamProtocol], *, identity: int = identity
- ) -> None:
- graph = owner()
- if graph is not None:
- memo = graph._capture_stream_keys
- if (current := memo.get(identity)) is not None and current[
- 0
- ] is dead:
- del memo[identity]
-
- try:
- stream_ref = ref(stream, discard)
- except TypeError:
- # A third-party stream can implement the protocol without weak refs.
+ def _check_leaf_object(
+ self,
+ staged: dict[tuple[bool, int], dict[str, None]],
+ name: str,
+ stream: StreamProtocol,
+ ) -> None:
+ """Check the other slot names that claim the same input object."""
+ declared, token = self._leaf_object_key(stream)
+ # A blueprint may declare several slots from one example. Refuse when
+ # the same object is also captured directly, in either order.
+ other_key = (
+ (not declared, token)
+ if self._capture_receiver == "pipeline"
+ else (declared, token)
+ )
+ for other_name in chain(
+ self._leaf_names_by_object.get(other_key, ()),
+ staged.get(other_key, ()),
+ ):
+ if other_name != name:
+ leaf = _leaf_object(stream)
+ require_distinct_slot_bindings(((other_name, leaf), (name, leaf)))
+
+ def _remember_leaf(
+ self, name: str, key: str, stream: StreamProtocol, slot: SourceNodeBase
+ ) -> None:
+ """Publish a new named leaf to the capture indexes."""
+ self._capture_leaves[name] = (key, stream)
+ self._capture_names.setdefault(name, {})[key] = _CaptureName(key, stream)
+ self._leaf_names_by_object.setdefault(self._leaf_object_key(stream), {})[
+ name
+ ] = None
+ self._source_streams[key] = stream
+ self._capture_nodes[key] = slot
+
+ def _claim_capture_name(
+ self,
+ namespace: dict[str, list[_CaptureName]],
+ name: str,
+ incoming: _CaptureName,
+ introduced_slots: tuple[str, ...] = (),
+ ) -> None:
+ """Validate one slot name or step label against every existing owner."""
+ owners = namespace.get(name)
+ if owners is None:
+ owners = list(self._capture_names.get(name, {}).values())
+ if incoming.step and any(
+ held.step and held.key == incoming.key for held in owners
+ ):
+ return
+ for held in owners:
+ if held.step and incoming.step:
+ # A repeated graph key is the same step. Main numbers distinct
+ # steps that share a display label, including explicit labels.
+ continue
+ if not held.step and not incoming.step:
+ self._check_leaf(name, held.stream, incoming.stream)
+ return
+ if incoming.step and held.key in introduced_slots:
+ # Row 39: the step introduces its own input slot. Main numbers
+ # the display labels without changing the slot's binding name.
continue
- self._capture_stream_keys[identity] = (stream_ref, key)
+ self._taken_capture_name(name, held, incoming)
+
+ # A suffix becomes a display label when compilation publishes it.
+ # Until then, main lets slot names and explicit labels reserve it.
+ if not owners:
+ published = self._nodes.get(name)
+ if isinstance(published, (StreamBase, SourceNodeBase)):
+ key = graph_key(published)
+ if not incoming.step or incoming.key != key:
+ self._taken_capture_name(
+ name,
+ _CaptureName(
+ key,
+ published,
+ step=not isinstance(published, SourceNodeBase),
+ ),
+ incoming,
+ )
+ if not incoming.step and not owners:
+ namespace[name] = [incoming]
+
+ @staticmethod
+ def _taken_capture_name(
+ name: str, held: _CaptureName, incoming: _CaptureName
+ ) -> None:
+ first = (
+ f"step {held.stream.label!r}"
+ if held.step
+ else _leaf_description(held.stream, name)
+ )
+ second = (
+ f"step {incoming.stream.label!r}"
+ if incoming.step
+ else _leaf_description(incoming.stream, name)
+ )
+ raise InconsistentSourceError(
+ f"Name {name!r} already holds {first}; {second} is another object under "
+ "the same name. Use the original object or choose a distinct name (ITL-1559)."
+ )
+
+ @staticmethod
+ def _leaf_name(stream: StreamProtocol) -> str:
+ return (
+ stream.name if isinstance(stream, SourceNodeBase) else slot_name_for(stream)
+ )
+
+ def _capture_slot(self, stream: StreamProtocol, name: str) -> SourceNode:
+ """Validate the leaf and derive a declaration independent of its data."""
+ from orcapod.core.sources.source_proxy import SourceProxy
+
+ if isinstance(stream, SourceProxy):
+ # A proxy can be declared before it has the system tags required for
+ # binding. Capture can still diagnose conflicting readings of it.
+ return SourceNode.from_stream(stream, name=name)
+ slot = self.source_node_class.from_stream(stream, name=name)
+ return slot.as_node() if isinstance(slot, SourceJobNode) else slot
+
+ def _check_leaf(
+ self, name: str, first: StreamProtocol, stream: StreamProtocol
+ ) -> None:
+ if first is stream:
+ return
+ roots = [
+ leaf.source_id for leaf in (first, stream) if isinstance(leaf, RootSource)
+ ]
+ declared = isinstance(first, SourceNodeBase) and isinstance(
+ stream, SourceNodeBase
+ )
+ if (
+ declared or len(roots) == 2
+ ) and first.output_schema() != stream.output_schema():
+ named = (
+ f" ({', '.join(repr(source_id) for source_id in sorted(set(roots)))})"
+ if roots
+ else ""
+ )
+ raise InconsistentSourceError(
+ f"Pipeline '{'.'.join(self._name)}' has 2 source nodes all named "
+ f"{name!r}{named} but with different schemas. Assign distinct source_id "
+ "values to the conflicting sources so each slot has a unique, "
+ "stable identity."
+ )
+ _refuse_sources_sharing_a_slot_name(name, [first, stream])
+ same_object = _leaf_object(first) is _leaf_object(stream)
+ if same_object and isinstance(first, SourceNode) != isinstance(
+ stream, SourceNode
+ ):
+ raise InconsistentSourceError(
+ f"The same source object is already declared under slot {name!r}. "
+ "Use the slot declaration or capture the source directly (ITL-1559)."
+ )
+ if not same_object:
+ raise InconsistentSourceError(
+ f"Slot {name!r} already holds {_leaf_description(first, name)}; "
+ f"{_leaf_description(stream, name)} is another object under the same "
+ "name. A slot holds exactly one source object until source equivalence "
+ "is defined (ITL-1553). Pass the same object again, or declare the "
+ "second one under its own slot name with "
+ "SourceNode.from_stream(stream, name=...)."
+ )
def _remember_invocation(
self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...]
) -> None:
- """Keep the smallest explicit label when identical invocations share a node."""
- previous = self._invocation_lut.get(key)
- if previous is not None and previous.label is not None:
- if invocation.label is None or previous.label < invocation.label:
- return
- self._invocation_lut[key] = invocation
- self._invocation_input_keys[key] = input_keys
+ """Keep the smallest explicit label when invocations share a node."""
+ if self._prefer_invocation(invocation, self._invocation_lut.get(key)):
+ self._invocation_lut[key] = invocation
+ self._invocation_input_keys[key] = input_keys
+
+ @staticmethod
+ def _prefer_invocation(
+ invocation: PodInvocation, previous: PodInvocation | None
+ ) -> bool:
+ return (
+ previous is None
+ or previous.label is None
+ or invocation.label is not None
+ and invocation.label <= previous.label
+ )
def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]:
"""Held inputs and, when supplied, the candidate's inputs before deduplication."""
@@ -471,7 +1148,26 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse
def _source_node_from_recording(self, key: str) -> Any:
"""Create the source node for a recorded leaf."""
- return self.source_node_class.from_stream(self._source_streams[key])
+ slot = self._capture_nodes[key]
+ assert isinstance(slot, SourceNodeBase)
+ current: SourceNodeBase = self.source_node_class.from_stream(
+ self._source_streams[key], name=slot.name
+ )
+ if current is not slot and (
+ current.output_schema() != slot.output_schema()
+ or any(
+ not old.equals(new, check_metadata=True)
+ for old, new in zip(
+ slot.arrow_schemas, current.arrow_schemas, strict=True
+ )
+ )
+ ):
+ raise InconsistentSourceError(
+ f"Cannot recompile source slot {slot.name!r} because its captured "
+ "schema changed (ITL-1559). Restore the original schema or capture "
+ "the new schema in a new blueprint."
+ )
+ return current
# ------------------------------------------------------------------
# Diagram (ITL-1197)
@@ -573,6 +1269,13 @@ def __getattr__(self, item: str) -> Any:
# compile() — single-pass, class-property driven
# ------------------------------------------------------------------
+ def _prepare_compiled_roles(
+ self, nodes: dict[str, cp.StreamProtocol], *, validate_steps: bool
+ ) -> Callable[[], None]:
+ """Prepare role validation for a replacement compiled graph."""
+ return lambda: None
+
+ @identity_transaction()
def compile(self) -> None:
"""Compile recorded invocations into a frozen DAG.
@@ -600,9 +1303,7 @@ def compile(self) -> None:
"""
self._compile_nodes()
- def _compile_nodes(
- self, validate_nodes: Callable[[Iterable[NodeT]], None] | None = None
- ) -> None:
+ def _compile_nodes(self, *, validate_steps: bool = True) -> None:
"""Build and publish compiled nodes, optionally checking them first."""
import networkx as _nx
@@ -616,8 +1317,6 @@ def _compile_nodes(
require_consistent_sources(uses)
require_one_restriction(stream for _, stream in uses)
- source_node_cls = self.source_node_class
-
# 1. Resolve source nodes in hash order, then insert them by their slot
# labels. The original stream hash breaks ties between identical labels.
sources = [
@@ -628,79 +1327,21 @@ def _compile_nodes(
sorted(sources, key=lambda item: (item[1].label, item[0]))
)
- # 2. Validate source-node name uniqueness.
- # Source node names are identity-forming (used as bind() keys and
- # included in content_hash()). Two distinct source nodes with the
- # same name are refused: with different schemas by InconsistentSourceError,
- # and when two or more are sources (RootSource), whatever their schemas, by
- # SourceSlotNameCollisionError (ITL-1425: a slot is named by the source's
- # name without its kind part, so another kind, version, key or id would
- # otherwise share the slot). Only streams that are not sources, with equal
- # schemas and colliding label:hash names, are left as they are.
- name_to_hashes: dict[str, list[str]] = {}
- for h, node in node_map.items():
- name_to_hashes.setdefault(node._name, []).append(h)
- for node_name, hashes in name_to_hashes.items():
- if len(hashes) <= 1:
- continue
- nodes = [node_map[h] for h in hashes]
- first = nodes[0]
- schemas_differ = any(
- n._tag_schema != first._tag_schema
- or n._data_schema != first._data_schema
- for n in nodes[1:]
- )
- if schemas_differ:
- from orcapod.errors import InconsistentSourceError
-
- from orcapod.core.sources.base import RootSource
-
- ids = sorted(
- {
- s.source_id
- for s in (self._source_streams[h] for h in hashes)
- if isinstance(s, RootSource)
- }
- )
- named = f" ({', '.join(repr(i) for i in ids)})" if ids else ""
- raise InconsistentSourceError(
- f"Pipeline '{'.'.join(self._name)}' has {len(hashes)} source "
- f"nodes all named {node_name!r}{named} but with different "
- f"schemas. Assign distinct source_id values to the conflicting "
- f"sources so each slot has a unique, stable identity."
- )
- _refuse_sources_sharing_a_slot_name(
- node_name, [self._source_streams[h] for h in hashes]
- )
-
- # 3. Topological pass with independent invocations ordered by hash.
- for key in _nx.lexicographical_topological_sort(self._hash_graph):
+ # 2. Topological pass with independent invocations ordered by hash.
+ for key in _nx.lexicographical_topological_sort(self._capture_graph):
if key in node_map:
- continue # already added as a source node in step 2
+ continue # already added as a source node
if key not in self._invocation_lut:
continue # vertex with no invocation (e.g. pure source hash)
inv = self._invocation_lut[key]
upstream_nodes = [node_map[up] for up in self._invocation_input_keys[key]]
- if isinstance(inv, FunctionInvocation):
- node_map[key] = self.function_node_class(
- function_pod=inv.pod,
- input_stream=upstream_nodes[0],
- label=inv.label,
- )
- elif isinstance(inv, SideEffectInvocation):
- node_map[key] = self.side_effect_node_class(
- side_effect_pod=inv.pod,
- input_stream=upstream_nodes[0],
- label=inv.label,
- )
- else:
- node_map[key] = self.operator_node_class(
- operator=inv.pod,
- input_streams=tuple(upstream_nodes),
- label=inv.label,
- )
+ node_map[key] = self._node_from_invocation(inv, tuple(upstream_nodes))
- # 4. Reserve every original label before generating any suffixes.
+ for key, node in node_map.items():
+ assign_graph_key(node, key)
+ self._hash_graph = self._capture_graph
+
+ # 3. Reserve every original label before generating any suffixes.
name_candidates: dict[str, list] = {}
for node in node_map.values():
name_candidates.setdefault(node.label, []).append(node)
@@ -708,13 +1349,19 @@ def _compile_nodes(
reserved_names = set(name_candidates)
for label, nodes in name_candidates.items():
if len(nodes) > 1:
- explicitly_named = [node for node in nodes if node._label is not None]
- if len(explicitly_named) == 1:
- # A computed label can coincide with an otherwise unique explicit one.
- nodes = [node for node in nodes if node is not explicitly_named[0]]
- sorted_nodes = sorted(nodes, key=lambda n: graph_hash(n).to_string())
+ automatic = [node for node in nodes if not node.has_assigned_label]
+ candidates = automatic if len(nodes) - len(automatic) == 1 else nodes
+ if len(nodes) - len(automatic) <= 1 and all(
+ not isinstance(node, SourceNodeBase) for node in nodes
+ ):
+ candidates = sorted(candidates, key=graph_key)
+ else:
+ candidates = sorted(
+ candidates,
+ key=lambda node: _legacy_key(node) or graph_key(node),
+ )
i = 1
- for node in sorted_nodes:
+ for node in candidates:
key = f"{label}_{i}"
while key in reserved_names:
i += 1
@@ -724,15 +1371,16 @@ def _compile_nodes(
i += 1
node_map = self._ordered_node_map(node_map, self._hash_graph)
- if validate_nodes is not None:
- validate_nodes(node_map.values())
+ publish_roles = self._prepare_compiled_roles(
+ node_map, validate_steps=validate_steps
+ )
self._persistent_node_map = node_map
self._nodes.clear()
self._nodes.update((node.label, node) for node in node_map.values())
- # 5. Build node_graph (OrcaDAG with node objects as vertices).
+ # 4. Build node_graph (OrcaDAG with node objects as vertices).
graph_edges = sorted(self._hash_graph.edges())
- node_dag: OrcaDAG[NodeT] = OrcaDAG()
+ node_dag: OrcaDAG[NodeT] = keyed_dag(default_node_key)
for node in node_map.values():
node_dag.add_node(node)
for up_hash, down_hash in graph_edges:
@@ -740,41 +1388,65 @@ def _compile_nodes(
down_node = node_map.get(down_hash)
if up_node is not None and down_node is not None:
node_dag.add_edge(up_node, down_node)
- self._node_graph = node_dag
+ self._publish_compiled_dag(node_dag)
- # 6. Enrich hash_graph node attributes (used by serialization).
+ # 5. Enrich hash_graph node attributes (used by serialization).
for node_hash, node in node_map.items():
if node_hash not in self._hash_graph:
continue
attrs = self._hash_graph.nodes[node_hash]
if not attrs.get("node_type"):
attrs["node_type"] = node.node_type
- if not attrs.get("label"):
- computed = node._label or (
- node.computed_label() if hasattr(node, "computed_label") else None
- )
- if computed:
- attrs["label"] = computed
+ attrs["label"] = node.label
if not attrs.get("pipeline_hash"):
attrs["pipeline_hash"] = node.pipeline_hash().to_string()
- # 7. Populate fields used by is_runnable(), run(), and save().
+ # 6. Populate fields used by is_runnable(), run(), and save().
self._node_lut = {
- h: n for h, n in node_map.items() if not isinstance(n, source_node_cls)
+ h: n for h, n in node_map.items() if not isinstance(n, SourceNodeBase)
}
self._upstreams = {
- h: n for h, n in node_map.items() if isinstance(n, source_node_cls)
+ h: n for h, n in node_map.items() if isinstance(n, SourceNodeBase)
}
self._graph_edges = graph_edges
self._compiled = True
+ publish_roles()
+
+ def _publish_compiled_dag(self, dag: OrcaDAG[NodeT]) -> None:
+ """Publish read-only topology and register the compiled setter preflight."""
+ from orcapod.core.nodes.operator_node import OperatorNodeBase
+
+ for node in dag:
+ if isinstance(node, (FunctionNodeBase, OperatorNodeBase)):
+ node._watch_compiled_rewire(self._validate_compiled_rewire)
+ self._node_graph = public_dag(dag)
+
+ def _node_from_invocation(
+ self, invocation: PodInvocation, upstreams: tuple[cp.StreamProtocol, ...]
+ ) -> Any:
+ """Build the node for this invocation and its resolved upstreams."""
+ if isinstance(invocation, FunctionInvocation):
+ return self.function_node_class(
+ function_pod=invocation.pod,
+ input_stream=upstreams[0],
+ label=invocation.label,
+ )
+ if isinstance(invocation, SideEffectInvocation):
+ return self.side_effect_node_class(
+ side_effect_pod=invocation.pod,
+ input_stream=upstreams[0],
+ label=invocation.label,
+ )
+ return self.operator_node_class(
+ operator=invocation.pod, input_streams=upstreams, label=invocation.label
+ )
@staticmethod
def _ordered_node_map(
nodes: dict[str, Any], graph: nx.DiGraph[str]
) -> dict[str, Any]:
"""Order compiled or restored nodes with slots first and dependencies intact."""
- from orcapod.core.nodes.source_node import SourceNodeBase
def order_key(key: str) -> tuple[int, str, str, str]:
node = nodes.get(key)
@@ -820,20 +1492,15 @@ def to_invocations(self) -> InvocationGraph:
"Use 'with pipeline:' or call compile() first."
)
- source_node_cls = self.source_node_class
- fn_node_cls = self.function_node_class
- source_streams: dict[str, Any] = {}
- # Map node_hash (from _persistent_node_map / _hash_graph) → invocation.
- # Using node_hash (not inv.content_hash()) so the topological sort keys
- # from _hash_graph align with inv_by_node_hash.
+ source_streams: dict[str, StreamProtocol] = {}
inv_by_node_hash: dict[str, PodInvocation] = {}
for node_hash, node in self._persistent_node_map.items():
- if isinstance(node, source_node_cls):
+ if isinstance(node, SourceNodeBase):
source_streams[
graph_hash(cast("IdentityChainProtocol", node)).to_string()
- ] = node
- elif isinstance(node, fn_node_cls):
+ ] = cast("StreamProtocol", node)
+ elif isinstance(node, FunctionNodeBase):
if node._function_pod is None:
raise RuntimeError(
f"to_invocations() cannot serialise FunctionNode {node_hash!r}: "
@@ -881,14 +1548,23 @@ def to_invocations(self) -> InvocationGraph:
# Sort topologically using _hash_graph (node_hash keys match _hash_graph).
topo_keys = _nx.lexicographical_topological_sort(self._hash_graph)
- ordered = [inv_by_node_hash[k] for k in topo_keys if k in inv_by_node_hash]
-
- return InvocationGraph(
- invocations=tuple(ordered),
- source_streams=source_streams,
+ ordered = [key for key in topo_keys if key in inv_by_node_hash]
+
+ exported = InvocationGraph(
+ invocations=tuple(inv_by_node_hash[key] for key in ordered),
+ source_streams=MappingProxyType(source_streams),
+ outputs=tuple(
+ cast("StreamProtocol", self._persistent_node_map[key])
+ for key in ordered
+ ),
)
+ # Reconstructing a public InvocationGraph (including dataclasses.replace)
+ # must go through the ordinary capture boundary again.
+ object.__setattr__(exported, "_exported", True)
+ return exported
@classmethod
+ @identity_transaction()
def from_invocations(
cls,
graph: InvocationGraph,
@@ -908,31 +1584,84 @@ def from_invocations(
A compiled instance of ``cls``.
"""
instance = cls(name=name)
- inputs = tuple(
- chain(
- graph.source_streams.values(),
- chain.from_iterable(
- invocation.input_streams for invocation in graph.invocations
- ),
+ publications: list[Callable[[], None]] = []
+ instance._import_publications = publications
+ try:
+ instance._import_invocations(graph)
+ finally:
+ instance._import_publications = None
+ for publish in publications:
+ publish()
+ return instance
+
+ def _import_invocations(self, graph: InvocationGraph) -> None:
+ """Build the scratch receiver before publishing caller-visible claims."""
+ exported = graph._exported
+ if not exported and graph.outputs:
+ for output in graph.outputs:
+ self._capture_input_key(output, {})
+ raise InconsistentSourceError(
+ "Compiled output positions must come from to_invocations() (ITL-1559)."
)
- )
- instance._validate_capture_sources(inputs)
- require_live_source_bindings(inputs)
- require_consistent_sources(invocation_source_uses(graph.invocations))
- instance._source_streams = dict(graph.source_streams)
- capture_streams = instance._capture_key_memo()
- for inv in graph.invocations:
- key, input_keys = inv.capture_keys(
- capture_streams, instance._input_graph_key
+ imported: dict[int, str] = {}
+ namespace: dict[str, list[_CaptureName]] = {}
+ for original in graph.source_streams.values():
+ stream = original
+ if exported and isinstance(original, SourceNode):
+ # The exports carry the declarations, and every graph owns its slots.
+ stream = copy(original)
+ stream._compiled_graph_key = None
+ stream._capture_owner = None
+ else:
+ self._capture_input_key(stream, {})
+ name = self._leaf_name(stream)
+ slot = self._capture_slot(stream, name)
+ key = graph_key(slot, use_published=False)
+ # Importing a blueprint gives the job unbound slots. The blueprint's
+ # original input objects are only relevant to its own captures.
+ leaf = (
+ slot
+ if self._capture_receiver == "job" and isinstance(stream, SourceNode)
+ else stream
)
- instance._remember_invocation(key, inv, input_keys)
- instance._hash_graph.add_node(key)
- for input_key in input_keys:
- instance._hash_graph.add_edge(input_key, key)
- instance._remember_capture_stream_keys(capture_streams.maps[0])
- # Also add source hashes as isolated nodes (no incoming edges)
- for h in graph.source_streams:
- if h not in instance._hash_graph:
- instance._hash_graph.add_node(h)
- instance.compile()
- return instance
+ self._claim_capture_name(namespace, name, _CaptureName(key, leaf))
+ self._check_leaf_object({}, name, leaf)
+ if name not in self._capture_leaves:
+ self._remember_leaf(name, key, leaf, slot)
+ if not _has_execution_binding(leaf):
+ self._unbound_keys.add(key)
+ self._source_streams[key] = stream
+ leaf_key, _ = self._capture_leaves[name]
+ imported[id(original)] = leaf_key
+ self._capture_graph.add_node(leaf_key)
+ require_live_source_bindings(self._source_streams.values())
+ require_consistent_sources(
+ (f"source {stream.label!r}", stream)
+ for stream in self._source_streams.values()
+ )
+ self._execution_roles.prepare(
+ (name, _legacy_key(stream))
+ for name, (key, stream) in self._capture_leaves.items()
+ if key not in self._unbound_keys
+ )()
+ self._prepare_wire_keys(dict(self._source_streams))()
+ for index, inv in enumerate(graph.invocations):
+ key = self._record_invocation(inv, imported)
+ if exported:
+ imported[id(graph.outputs[index])] = key
+ declarations = [
+ (stream, stream._compiled_graph_key, stream._label)
+ for stream in self._source_streams.values()
+ if isinstance(stream, SourceNode)
+ ]
+ try:
+ self.compile()
+ except BaseException:
+ for stream, key, label in declarations:
+ stream._compiled_graph_key = key
+ stream._label = label
+ raise
+ if not exported:
+ for stream in graph.source_streams.values():
+ if isinstance(stream, SourceNode):
+ stream._capture_owner = self._capture_owner
diff --git a/src/orcapod/pipeline/dag.py b/src/orcapod/pipeline/dag.py
index b192a5c96..e71504727 100644
--- a/src/orcapod/pipeline/dag.py
+++ b/src/orcapod/pipeline/dag.py
@@ -18,8 +18,11 @@
from __future__ import annotations
import heapq
-from collections.abc import Hashable
+import operator
+from collections.abc import Callable, Collection, Hashable, Mapping, MutableMapping, Set
from graphlib import CycleError, TopologicalSorter
+from inspect import getattr_static
+from types import MappingProxyType
from typing import (
Any,
Generic,
@@ -27,9 +30,13 @@
Iterator,
Protocol,
TypeVar,
+ cast,
runtime_checkable,
)
+from orcapod.core.identity_chains import IdentityChainsMixin, graph_key
+from orcapod.errors import UndefinedGraphMembershipError
+
__all__ = ["Comparable", "GraphProtocol", "OrcaDAG", "CycleError"]
@@ -49,6 +56,7 @@ def __lt__(self, other: Any) -> bool: ...
# Class-level TypeVar: only requires hashability (usable as a dict key).
NodeT = TypeVar("NodeT", bound=Hashable)
+KeyT = TypeVar("KeyT", bound=Hashable)
# Method-level TypeVar for topological_sort_deterministic: additionally
# requires ordering so heapq operations are type-safe.
@@ -96,6 +104,281 @@ def topological_sort(self) -> list[NodeT]: ...
def ancestors(self, node: NodeT) -> frozenset[NodeT]: ...
+def node_key_in(graph: GraphProtocol[NodeT], node: NodeT) -> Hashable:
+ """Use the graph's chosen key when it has one."""
+ return graph._key_for(node) if isinstance(graph, OrcaDAG) else node
+
+
+def operand_key_in(graph: GraphProtocol[NodeT], node: NodeT) -> Hashable:
+ """Resolve a declared operand, including aliases in a projected execution DAG."""
+ if isinstance(graph, OrcaDAG):
+ return node if graph._key is None else graph._key(node)
+ return node
+
+
+def default_node_key(node: Hashable) -> Hashable:
+ """Resolve explicit keys for pipeline-owned graphs."""
+ return graph_key(node) if isinstance(node, IdentityChainsMixin) else node
+
+
+def require_membership_key(node: object) -> None:
+ """Refuse a stream, node, or invocation as a public membership operand."""
+ if isinstance(node, str):
+ return
+ # Use static lookup to cover transparent stream wrappers without evaluating
+ # any properties or asking the stream to compute an identity.
+ if getattr_static(node, "_identity_chains", None) is not None:
+ raise UndefinedGraphMembershipError(
+ "Graph object membership is not defined yet. Access the node by label "
+ "with job.nodes[label] or pipeline.nodes[label]."
+ )
+
+
+def keyed_dag(key: Callable[[NodeT], Hashable]) -> OrcaDAG[NodeT]:
+ """Build a DAG with a caller-supplied key."""
+ dag: OrcaDAG[NodeT] = OrcaDAG()
+ dag._key = key
+ return dag
+
+
+def empty_dag_like(graph: OrcaDAG[NodeT]) -> OrcaDAG[NodeT]:
+ """Build an empty subgraph with the parent graph's key resolution."""
+ if graph._key is None:
+ return OrcaDAG()
+ return keyed_dag(graph._key_for)
+
+
+def public_dag(dag: OrcaDAG[NodeT]) -> OrcaDAG[NodeT]:
+ """Publish a compiled DAG with read-only topology."""
+ dag._public = True
+ return dag
+
+
+def project_legacy_graph(
+ nodes: Mapping[KeyT, NodeT],
+ edges: Iterable[tuple[KeyT, KeyT]],
+ legacy_key: Callable[[KeyT, NodeT], Hashable],
+ *,
+ prefer: Callable[[KeyT, KeyT], bool] | None = None,
+) -> tuple[dict[KeyT, KeyT], dict[KeyT, None], dict[tuple[KeyT, KeyT], None]]:
+ """Select legacy representatives and unique edges for execution or saving.
+
+ Return each key's representative, the representatives in insertion order, and
+ the projected edges. These are boundary data and never update the public DAG.
+ """
+ representatives: dict[Hashable, KeyT] = {}
+ aliases: dict[KeyT, Hashable] = {}
+ for key, node in nodes.items():
+ identity = legacy_key(key, node)
+ aliases[key] = identity
+ previous = representatives.setdefault(identity, key)
+ if prefer is not None and prefer(key, previous):
+ representatives[identity] = key
+ projected = {key: representatives[identity] for key, identity in aliases.items()}
+ return (
+ projected,
+ dict.fromkeys(representatives.values()),
+ dict.fromkeys((projected[up], projected[down]) for up, down in edges),
+ )
+
+
+def nodes_of(graph: GraphProtocol[NodeT]) -> Iterable[NodeT]:
+ """Read every vertex of a keyed graph, including content-equal vertices."""
+ if isinstance(graph, OrcaDAG):
+ return graph._nodes.values()
+ return graph.nodes()
+
+
+def predecessors_of(graph: GraphProtocol[NodeT], node: NodeT) -> Collection[NodeT]:
+ """Read adjacency without collapsing distinct keyed endpoints."""
+ if isinstance(graph, OrcaDAG) and graph._key is not None:
+ return graph._nodes_at(graph._predecessors[graph._key_for(node)])
+ return graph.predecessors(node)
+
+
+def successors_of(graph: GraphProtocol[NodeT], node: NodeT) -> Collection[NodeT]:
+ """Read adjacency without collapsing distinct keyed endpoints."""
+ if isinstance(graph, OrcaDAG) and graph._key is not None:
+ return graph._nodes_at(graph._successors[graph._key_for(node)])
+ return graph.successors(node)
+
+
+def ancestors_of(graph: OrcaDAG[NodeT], node: NodeT) -> Iterable[NodeT]:
+ """Read transitive adjacency without collapsing distinct keyed endpoints."""
+ if graph._key is None:
+ return graph.ancestors(node)
+ return graph._nodes_at(graph._ancestor_keys(node))
+
+
+ValueT = TypeVar("ValueT")
+
+
+class NodeMap(MutableMapping[NodeT, ValueT]):
+ """A mapping indexed by nodes that uses the graph's identity internally."""
+
+ def __init__(self, graph: GraphProtocol[NodeT]) -> None:
+ self._graph = graph
+ self._entries: dict[Hashable, tuple[NodeT, ValueT]] = {}
+
+ def __getitem__(self, node: NodeT) -> ValueT:
+ return self._entries[node_key_in(self._graph, node)][1]
+
+ def __setitem__(self, node: NodeT, value: ValueT) -> None:
+ self._entries[node_key_in(self._graph, node)] = (node, value)
+
+ def __delitem__(self, node: NodeT) -> None:
+ del self._entries[node_key_in(self._graph, node)]
+
+ def __iter__(self) -> Iterator[NodeT]:
+ return (node for node, _ in self._entries.values())
+
+ def __len__(self) -> int:
+ return len(self._entries)
+
+
+class NodeSet(Set[NodeT]):
+ """Read-only set of nodes with membership determined by graph keys."""
+
+ def __init__(
+ self,
+ nodes: Mapping[Hashable, NodeT],
+ key: Callable[[NodeT], Hashable],
+ ) -> None:
+ self._nodes = nodes
+ self._key = key
+
+ def __contains__(self, node: object) -> bool:
+ return self._contains_node(node)
+
+ def _contains_node(self, node: object) -> bool:
+ try:
+ return self._key(cast(NodeT, node)) in self._nodes
+ except (KeyError, TypeError):
+ return False
+
+ def __iter__(self) -> Iterator[NodeT]:
+ return iter(self._nodes.values())
+
+ def __len__(self) -> int:
+ return len(self._nodes)
+
+ def __le__(self, other: Set[object]) -> bool:
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) <= len(other) and sum(
+ self._contains_node(node) for node in other
+ ) == len(self)
+
+ def __ge__(self, other: Set[object]) -> bool:
+ if not isinstance(other, Set):
+ return NotImplemented
+ return all(self._contains_node(node) for node in other)
+
+ def __lt__(self, other: Set[object]) -> bool:
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) < len(other) and self <= other
+
+ def __gt__(self, other: Set[object]) -> bool:
+ if not isinstance(other, Set):
+ return NotImplemented
+ return len(self) > len(other) and self >= other
+
+ @classmethod
+ def _from_iterable(cls, it: Iterable[NodeT]) -> NodeSet[NodeT]:
+ def key(node: NodeT) -> Hashable:
+ return (
+ (IdentityChainsMixin, id(node))
+ if isinstance(node, IdentityChainsMixin)
+ else node
+ )
+
+ return cls({key(node): node for node in it}, key)
+
+
+class PublicNodeView(Set[NodeT]):
+ """Expose dict-key collection operations over the compiled vertices."""
+
+ def __init__(
+ self,
+ nodes: dict[Hashable, NodeT],
+ attrs: Mapping[Hashable, dict[str, Any]],
+ contains: Callable[[object], bool],
+ ) -> None:
+ self._nodes = nodes
+ self._attrs = attrs
+ self._contains = contains
+
+ def __contains__(self, node: object) -> bool:
+ return self._contains(node)
+
+ def __iter__(self) -> Iterator[NodeT]:
+ return iter(self._nodes.values())
+
+ def __len__(self) -> int:
+ return len(self._nodes)
+
+ def __reversed__(self) -> Iterator[NodeT]:
+ return (self._nodes[key] for key in reversed(self._nodes))
+
+ def __repr__(self) -> str:
+ return f"dict_keys({list(self)!r})"
+
+ def _node_attrs(self) -> dict[NodeT, dict[str, Any]]:
+ # Hash vertices only for public operations that used dict keys on main.
+ return {node: self._attrs[key] for key, node in self._nodes.items()}
+
+ @property
+ def mapping(self) -> Mapping[NodeT, dict[str, Any]]:
+ """Return a read-only mapping from vertices to their attribute dictionaries."""
+ return MappingProxyType(self._node_attrs())
+
+ @staticmethod
+ def _operand(other: object) -> object:
+ if isinstance(other, PublicNodeView):
+ return other._node_attrs().keys()
+ return other
+
+ def __and__(self, other: Iterable[object]) -> set[NodeT]:
+ return operator.and_(self._node_attrs().keys(), self._operand(other))
+
+ __rand__ = __and__
+
+ def __or__(self, other: Iterable[object]) -> set[object]:
+ return operator.or_(self._node_attrs().keys(), self._operand(other))
+
+ __ror__ = __or__
+
+ def __sub__(self, other: Iterable[object]) -> set[NodeT]:
+ return operator.sub(self._node_attrs().keys(), self._operand(other))
+
+ def __rsub__(self, other: Iterable[object]) -> set[object]:
+ return operator.sub(self._operand(other), self._node_attrs().keys())
+
+ def __xor__(self, other: Iterable[object]) -> set[object]:
+ return operator.xor(self._node_attrs().keys(), self._operand(other))
+
+ __rxor__ = __xor__
+
+ def __eq__(self, other: object) -> bool:
+ return operator.eq(self._node_attrs().keys(), self._operand(other))
+
+ def __le__(self, other: Set[object]) -> bool:
+ return self._node_attrs().keys() <= cast("Set[object]", self._operand(other))
+
+ def __lt__(self, other: Set[object]) -> bool:
+ return self._node_attrs().keys() < cast("Set[object]", self._operand(other))
+
+ def __ge__(self, other: Set[object]) -> bool:
+ return self._node_attrs().keys() >= cast("Set[object]", self._operand(other))
+
+ def __gt__(self, other: Set[object]) -> bool:
+ return self._node_attrs().keys() > cast("Set[object]", self._operand(other))
+
+ def isdisjoint(self, other: Iterable[object]) -> bool:
+ return self._node_attrs().keys().isdisjoint(other)
+
+
class OrcaDAG(Generic[NodeT]):
"""Minimal directed acyclic graph for Orcapod pipeline topology.
@@ -112,13 +395,27 @@ class OrcaDAG(Generic[NodeT]):
"""
def __init__(self) -> None:
- # node → mutable attribute dict
- self._attrs: dict[NodeT, dict[str, Any]] = {}
- # node → immediate neighbours in edge insertion order
- self._successors: dict[NodeT, dict[NodeT, None]] = {}
- self._predecessors: dict[NodeT, dict[NodeT, None]] = {}
- # node → number of incoming edges (kept in sync with _predecessors)
- self._in_degree: dict[NodeT, int] = {}
+ self._key: Callable[[NodeT], Hashable] | None = None
+ self._public = False
+ self._nodes: dict[Hashable, NodeT] = {}
+ self._pipeline_node_keys: dict[int, Hashable] = {}
+ self._attrs: dict[Hashable, dict[str, Any]] = {}
+ self._successors: dict[Hashable, dict[Hashable, None]] = {}
+ self._predecessors: dict[Hashable, dict[Hashable, None]] = {}
+ self._in_degree: dict[Hashable, int] = {}
+
+ def _key_for(self, node: NodeT) -> Hashable:
+ """Return the identity used for this node in the graph."""
+ if self._key is None:
+ return node
+ if self._public and isinstance(node, str):
+ raise KeyError("Pass a DAG vertex object. Look up nodes by label first.")
+ if self._public or isinstance(node, IdentityChainsMixin):
+ return self._pipeline_node_keys[id(node)]
+ return self._key(node)
+
+ def _nodes_at(self, keys: Iterable[Hashable]) -> tuple[NodeT, ...]:
+ return tuple(self._nodes[key] for key in keys)
# ------------------------------------------------------------------
# Construction
@@ -133,14 +430,23 @@ def add_node(self, node: NodeT, **attrs: Any) -> None:
Args:
node: The node to add.
**attrs: Attribute key/value pairs to store on the node.
+
+ Raises:
+ TypeError: If the DAG has been published by a pipeline.
"""
- if node not in self._attrs:
- self._attrs[node] = {}
- self._successors[node] = {}
- self._predecessors[node] = {}
- self._in_degree[node] = 0
+ if self._public:
+ raise TypeError("Pipeline DAG topology is read-only. Use the pipeline API.")
+ key = node if self._key is None else self._key(node)
+ if key not in self._attrs:
+ self._nodes[key] = node
+ if self._key is not None:
+ self._pipeline_node_keys[id(node)] = key
+ self._attrs[key] = {}
+ self._successors[key] = {}
+ self._predecessors[key] = {}
+ self._in_degree[key] = 0
if attrs:
- self._attrs[node].update(attrs)
+ self._attrs[key].update(attrs)
def add_edge(self, u: NodeT, v: NodeT) -> None:
"""Add a directed edge from *u* to *v*.
@@ -151,13 +457,17 @@ def add_edge(self, u: NodeT, v: NodeT) -> None:
Args:
u: Source node.
v: Target node.
+
+ Raises:
+ TypeError: If the DAG has been published by a pipeline.
"""
self.add_node(u)
self.add_node(v)
- if v not in self._successors[u]:
- self._successors[u][v] = None
- self._predecessors[v][u] = None
- self._in_degree[v] += 1
+ upstream, downstream = self._key_for(u), self._key_for(v)
+ if downstream not in self._successors[upstream]:
+ self._successors[upstream][downstream] = None
+ self._predecessors[downstream][upstream] = None
+ self._in_degree[downstream] += 1
# ------------------------------------------------------------------
# Node attribute access
@@ -177,21 +487,34 @@ def node_attrs(self, node: NodeT) -> dict[str, Any]:
Raises:
KeyError: If *node* is not in the graph.
"""
- return self._attrs[node]
+ return self._attrs[self._key_for(node)]
# ------------------------------------------------------------------
# Membership and sizing
# ------------------------------------------------------------------
def __contains__(self, node: object) -> bool:
- return node in self._attrs
+ if self._key is None:
+ return node in self._attrs
+ if self._contains_node(node):
+ return True
+ if self._public:
+ require_membership_key(node)
+ return False
+
+ def _contains_node(self, node: object) -> bool:
+ """Test internal membership without calling the public API."""
+ try:
+ return self._key_for(cast(NodeT, node)) in self._attrs
+ except (KeyError, TypeError):
+ return False
def __len__(self) -> int:
return len(self._attrs)
def __iter__(self) -> Iterator[NodeT]:
"""Iterate over all nodes (insertion order)."""
- return iter(self._attrs)
+ return iter(self._nodes.values())
# ------------------------------------------------------------------
# Traversal
@@ -203,51 +526,67 @@ def nodes(self) -> Iterable[NodeT]:
Returns:
Iterable of all nodes.
"""
- return self._attrs.keys()
-
- def edges(self) -> Iterable[tuple[NodeT, NodeT]]:
- """Return an iterable over all (source, target) edge pairs.
-
- Returns:
- Iterable of (u, v) tuples for every directed edge in the graph.
+ if self._public:
+ return PublicNodeView(self._nodes, self._attrs, self.__contains__)
+ if self._key is None:
+ return cast("Iterable[NodeT]", self._attrs.keys())
+ return NodeSet(self._nodes, self._key_for)
+
+ def _snapshot(self, keys: Iterable[Hashable]) -> frozenset[NodeT]:
+ if self._key is None:
+ return frozenset(cast("Iterable[NodeT]", keys))
+ return frozenset(self._nodes[key] for key in keys)
+
+ def edges(self) -> Iterator[tuple[NodeT, NodeT]]:
+ """Iterate over all (source, target) edge pairs.
+
+ Yields:
+ The source and target objects for each directed edge.
"""
- for u, successors in self._successors.items():
- for v in successors:
- yield u, v
+ if self._key is None:
+ # The source comes from vertex registration, and the target from
+ # the first insertion of this edge, as in an object-keyed DAG.
+ for up, successors in self._successors.items():
+ for down in successors:
+ yield cast(NodeT, up), cast(NodeT, down)
+ return
+ for up, successors in self._successors.items():
+ for down in successors:
+ yield self._nodes[up], self._nodes[down]
def successors(self, node: NodeT) -> frozenset[NodeT]:
"""Return the immediate successors (outgoing neighbours) of *node*.
- Returns a snapshot `frozenset` so callers cannot mutate internal
+ Returns a read-only snapshot so callers cannot mutate internal
graph state through the returned value.
Args:
node: The source node.
Returns:
- Frozen set of nodes that *node* has a directed edge to.
+ Read-only set of nodes that *node* has a directed edge to.
Raises:
KeyError: If *node* is not in the graph.
"""
- return frozenset(self._successors[node])
+ return self._snapshot(self._successors[self._key_for(node)])
def predecessors(self, node: NodeT) -> frozenset[NodeT]:
"""Return the immediate predecessors (incoming neighbours) of *node*.
- Returns a snapshot `frozenset` so callers cannot mutate internal
+ Returns a read-only snapshot so callers cannot mutate internal
graph state through the returned value.
Args:
node: The target node.
Returns:
- Frozen set of nodes that have a directed edge to *node*.
+ Read-only set of nodes that have a directed edge to *node*.
Raises:
KeyError: If *node* is not in the graph.
"""
- return frozenset(self._predecessors[node])
+ return self._snapshot(self._predecessors[self._key_for(node)])
def in_degree(self, node: NodeT) -> int:
"""Return the number of incoming edges for *node*.
@@ -261,13 +600,13 @@ def in_degree(self, node: NodeT) -> int:
Raises:
KeyError: If *node* is not in the graph.
"""
- return self._in_degree[node]
+ return self._in_degree[self._key_for(node)]
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
- def _build_predecessor_dict(self) -> dict[NodeT, tuple[NodeT, ...]]:
+ def _build_predecessor_dict(self) -> dict[Hashable, tuple[Hashable, ...]]:
"""Build the predecessor mapping required by TopologicalSorter.
Returns:
@@ -292,8 +631,10 @@ def topological_sort(self) -> list[NodeT]:
Raises:
graphlib.CycleError: If the graph contains a cycle.
"""
- ts: TopologicalSorter[NodeT] = TopologicalSorter(self._build_predecessor_dict())
- return list(ts.static_order())
+ ts = TopologicalSorter(self._build_predecessor_dict())
+ if self._key is None:
+ return list(cast("Iterator[NodeT]", ts.static_order()))
+ return [self._nodes[key] for key in ts.static_order()]
def topological_sort_deterministic(
self: "OrcaDAG[ComparableNodeT]",
@@ -318,15 +659,21 @@ def topological_sort_deterministic(
Raises:
graphlib.CycleError: If the graph contains a cycle.
"""
- in_deg: dict[ComparableNodeT, int] = dict(self._in_degree)
- frontier: list[ComparableNodeT] = [n for n, d in in_deg.items() if d == 0]
+ in_deg = dict(self._in_degree)
+ frontier = [cast(Comparable, key) for key, d in in_deg.items() if d == 0]
heapq.heapify(frontier)
ordered: list[ComparableNodeT] = []
while frontier:
- node: ComparableNodeT = heapq.heappop(frontier)
- ordered.append(node)
- for successor in sorted(self._successors[node]):
+ key = heapq.heappop(frontier)
+ successors = self._successors[key]
+ if self._key is None:
+ ordered.append(cast(ComparableNodeT, key))
+ next_keys = sorted(cast("Iterable[Comparable]", successors))
+ else:
+ ordered.append(self._nodes[key])
+ next_keys = cast("Iterable[Comparable]", successors)
+ for successor in next_keys:
in_deg[successor] -= 1
if in_deg[successor] == 0:
heapq.heappush(frontier, successor)
@@ -350,19 +697,23 @@ def ancestors(self, node: NodeT) -> frozenset[NodeT]:
node: The node whose ancestors to find.
Returns:
- Frozen set of all nodes from which there is a directed path to
+ Read-only set of all nodes from which there is a directed path to
*node*. Empty if *node* is a source (no incoming edges).
Raises:
KeyError: If *node* is not in the graph.
"""
- if node not in self._predecessors:
+ return self._snapshot(self._ancestor_keys(node))
+
+ def _ancestor_keys(self, node: NodeT) -> set[Hashable]:
+ key = self._key_for(node)
+ if key not in self._predecessors:
raise KeyError(node)
- visited: set[NodeT] = set()
- queue: list[NodeT] = list(self._predecessors[node])
+ visited: set[Hashable] = set()
+ queue = list(self._predecessors[key])
while queue:
n = queue.pop()
if n not in visited:
visited.add(n)
queue.extend(self._predecessors[n])
- return frozenset(visited)
+ return visited
diff --git a/src/orcapod/pipeline/diagram.py b/src/orcapod/pipeline/diagram.py
index 28b73c2c7..ca1be3684 100644
--- a/src/orcapod/pipeline/diagram.py
+++ b/src/orcapod/pipeline/diagram.py
@@ -32,7 +32,7 @@
import importlib.resources
import json
import re
-from collections.abc import Iterable, Mapping, Sequence
+from collections.abc import Hashable, Iterable, Mapping, Sequence
from dataclasses import dataclass, field
from pathlib import Path
from typing import TYPE_CHECKING, Any, Literal, Protocol
@@ -40,6 +40,7 @@
from typing_extensions import override
from orcapod.core.sources.display_names import class_dicts, node_display_names
+from orcapod.pipeline.dag import default_node_key, nodes_of
from orcapod.types.provenance import Highlight
from orcapod.utils.in_development import warn_in_development
@@ -203,17 +204,17 @@ def _collapsible(node: Any) -> bool:
)
-def _upstream_labels(node: Any, label_of: Mapping[int, str]) -> list[str | None]:
+def _upstream_labels(node: Any, label_of: Mapping[Hashable, str]) -> list[str | None]:
"""The label of each of an operator node's inputs, in argument order.
Args:
node: The node.
- label_of: The label of each node of the graph, by the node's ``id()``.
+ label_of: The label of each node of the graph, by graph key.
Returns:
One label per input; ``None`` for an input that is not a node of the graph.
"""
- return [label_of.get(id(stream)) for stream in node.upstreams]
+ return [label_of.get(default_node_key(stream)) for stream in node.upstreams]
def _declared(producer: Any, name: str) -> Any:
@@ -233,7 +234,7 @@ def _declared(producer: Any, name: str) -> Any:
def _input_roles(
- node: Any, upstream_labels: Sequence[str], label_of: Mapping[int, str]
+ node: Any, upstream_labels: Sequence[str], label_of: Mapping[Hashable, str]
) -> list[tuple[str, bool]]:
"""A node's inputs, each with whether it only constrains the others (ITL-1455).
@@ -243,7 +244,7 @@ def _input_roles(
Args:
node: The node.
upstream_labels: The labels of the nodes it reads from, in drawing order.
- label_of: The label of each node of the graph, by the node's ``id()``.
+ label_of: The label of each node of the graph, by graph key.
Returns:
The label and role of each input, in the order of ``upstream_labels``.
@@ -335,13 +336,13 @@ def _failed_rows(node: Any) -> int:
def _constraint_fact(
- node: Any, label_of: Mapping[int, str], by_label: Mapping[str, Any]
+ node: Any, label_of: Mapping[Hashable, str], by_label: Mapping[str, Any]
) -> tuple[str, str] | None:
"""What a node's constraining inputs do, from its inputs' predicted tag columns.
Args:
node: An operator node with a constraining input.
- label_of: The label of each node of the graph, by the node's ``id()``.
+ label_of: The label of each node of the graph, by graph key.
by_label: The nodes, by label.
Returns:
@@ -421,8 +422,6 @@ def _build_model(
last_run.nodes if last_run is not None else {}
)
by_label: dict[str, Any] = {node.label: node for node in dag.nodes()}
- # From the edge list, never by looking a node up: a source node's hash changes
- # when a source is bound to it, so a lookup by node can miss.
preds: dict[str, list[str]] = {label: [] for label in by_label}
succs: dict[str, list[str]] = {label: [] for label in by_label}
for upstream, downstream in dag.edges():
@@ -431,7 +430,7 @@ def _build_model(
for names in (*preds.values(), *succs.values()):
names.sort()
- label_of = {id(node): label for label, node in by_label.items()}
+ label_of = {default_node_key(node): label for label, node in by_label.items()}
roles = {
label: _input_roles(node, preds[label], label_of)
for label, node in by_label.items()
@@ -1426,7 +1425,7 @@ def __init__(
"development: its interface and appearance may change in any release.",
)
if highlight is not None:
- labels = {node.label for node in pipeline.dag.nodes()}
+ labels = {node.label for node in nodes_of(pipeline.dag)}
unknown = sorted(
{
*highlight.nodes,
diff --git a/src/orcapod/pipeline/graph.py b/src/orcapod/pipeline/graph.py
index 9c6304cbf..8b0400aca 100644
--- a/src/orcapod/pipeline/graph.py
+++ b/src/orcapod/pipeline/graph.py
@@ -1,5 +1,15 @@
+"""Pipeline topology and blueprint persistence.
+
+Inside the graph a node is identified only by its graph key: its node hash,
+or the namespaced legacy key when that hash is unavailable. Assign implicit
+slot names before comparing capture keys. Project legacy identities only at
+the execution and save boundaries, without feeding them back into topology.
+"""
+
from __future__ import annotations
+from collections.abc import Callable
+
import copy
import logging
from pathlib import Path
@@ -8,17 +18,28 @@
import orcapod
from orcapod.config import config_for_save, validate_descriptor_config
from orcapod.contexts import resolve_saved_context
+from orcapod.core.identity_chains import assign_graph_key, graph_hash, graph_key
from orcapod.core.nodes import (
FunctionNode,
GraphNode,
OperatorNode,
SourceNode,
)
-from orcapod.side_effects import SideEffectNode
+from orcapod.core.nodes.function_node import FunctionNodeBase
+from orcapod.core.nodes.operator_node import OperatorNodeBase
+from orcapod.core.streams.base import StreamBase
from orcapod.core.tracker import AutoRegisteringContextBasedTracker
from orcapod.pipeline.base import AbstractPipelineBase
-from orcapod.pipeline.dag import OrcaDAG
+from orcapod.pipeline.dag import (
+ OrcaDAG,
+ default_node_key,
+ keyed_dag,
+ project_legacy_graph,
+)
+from orcapod.pipeline.pod_invocation import PodInvocation
+from orcapod.pipeline.restrictions import streams_beneath
from orcapod.protocols import core_protocols as cp
+from orcapod.side_effects import SideEffectNode
from orcapod.utils.lazy_module import LazyModule
from orcapod.utils.schema_utils import ReservedColumnNameError
@@ -63,6 +84,8 @@ class Pipeline(AbstractPipelineBase[GraphNode]):
# Node-factory class attributes (used by AbstractPipelineBase.compile())
# ------------------------------------------------------------------
+ _capture_receiver = "pipeline"
+
source_node_class = SourceNode
function_node_class = FunctionNode
operator_node_class = OperatorNode
@@ -91,8 +114,12 @@ def __init__(
"""
super().__init__(name=name, tracker_manager=tracker_manager)
self._auto_compile = auto_compile
+ self._loaded = False
+ self._from_compiled_job = False
# A loaded blueprint's operator input keys in argument order (ITL-1417).
self._loaded_input_keys: dict[str, list[str]] = {}
+ self._saved_keys: dict[str, str] = {}
+ self._captured_wire_keys: dict[str, str] = {}
# ------------------------------------------------------------------
# Context manager — respects auto_compile flag
@@ -111,6 +138,70 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None):
# Serialization
# ------------------------------------------------------------------
+ def _validate_capture_state(self) -> None:
+ from orcapod.errors import InconsistentSourceError
+
+ if self._loaded:
+ raise InconsistentSourceError(
+ "Capturing into a loaded pipeline is not supported yet (ITL-1559). "
+ "Rebuild the pipeline from its original code before adding steps."
+ )
+ if self._from_compiled_job:
+ raise InconsistentSourceError(
+ "Capturing into a job-derived pipeline is not supported yet "
+ "(ITL-1559). Rebuild the pipeline from its original code before adding steps."
+ )
+
+ def compile(self) -> None:
+ """Compile live captures. A blueprint projected from a job is already compiled."""
+ if not self._from_compiled_job:
+ super().compile()
+
+ def _prepare_wire_keys(
+ self, captured: dict[str, PodInvocation | cp.StreamProtocol]
+ ) -> Callable[[], None]:
+ """Freeze the legacy keys before adding the capture to the topology."""
+ keys: dict[str, str] = {}
+ pending: list[cp.StreamProtocol] = []
+ for key, element in captured.items():
+ if key not in self._captured_wire_keys:
+ keys[key] = self._wire_key(key, element)
+ if isinstance(element, PodInvocation):
+ pending.extend(element.input_streams)
+ else:
+ pending.append(element)
+ seen: set[int] = set()
+ descriptors: list[FunctionNodeBase | OperatorNodeBase] = []
+ while pending:
+ stream = pending.pop()
+ token = id(stream)
+ if token in seen:
+ continue
+ seen.add(token)
+ if isinstance(stream, (FunctionNodeBase, OperatorNodeBase)):
+ descriptors.append(stream)
+ elif isinstance(stream, StreamBase) and self._held_key(stream) is not None:
+ # This invocation's inputs were guarded when it was recorded.
+ continue
+ pending.extend(streams_beneath(stream))
+
+ def publish() -> None:
+ for descriptor in descriptors:
+ self._publish_capture_effect(
+ lambda descriptor=descriptor: descriptor._hold_wire_inputs(self) # pyright: ignore[reportPrivateUsage] # blueprint owns the wire capture
+ )
+ self._captured_wire_keys.update(keys)
+
+ return publish
+
+ def _wire_key(self, key: str, element: PodInvocation | cp.StreamProtocol) -> str:
+ """Resolve the legacy key for captured, restored, and job-derived nodes."""
+ if key in self._saved_keys:
+ return self._saved_keys[key]
+ if key in self._captured_wire_keys:
+ return self._captured_wire_keys[key]
+ return graph_hash(element).to_string()
+
def save(self, path: str | Path) -> None:
"""Serialize the pure pipeline blueprint to a JSON file.
@@ -132,6 +223,10 @@ def save(self, path: str | Path) -> None:
)
import json as _json
+
+ from orcapod.core.nodes import FunctionNode, OperatorNode
+ from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass
+ from orcapod.core.streams.base import shared_zero_row_memo, typed_arrow_schemas
from orcapod.pipeline.serialization import (
FALL_THROUGH_TAGS_KEY,
OPERATOR_INPUTS_KEY,
@@ -139,9 +234,83 @@ def save(self, path: str | Path) -> None:
serialize_arrow_schemas,
serialize_output_schema,
)
- 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
+
+ # The capture kept the original wire key and insertion order. Legacy
+ # capture used the first leaf and the smallest explicit invocation label.
+ file_keys = dict(self._saved_keys)
+ file_keys.update(
+ (key, self._wire_key(key, node))
+ for key, node in self._persistent_node_map.items()
+ )
+ capture_order = {
+ key: self._persistent_node_map[key]
+ for key in self._captured_wire_keys
+ if key in self._persistent_node_map
+ }
+
+ def prefer(candidate: str, previous: str) -> bool:
+ current = self._invocation_lut.get(candidate)
+ prior = self._invocation_lut.get(previous)
+ return (
+ current is not None
+ and prior is not None
+ and current.label is not None
+ and (prior.label is None or current.label < prior.label)
+ )
+
+ graph_edges = self._graph_edges
+ nodes_to_save = self._persistent_node_map
+ # Saved edges may reference unavailable descriptors.
+ present_edges = (
+ (up, down)
+ for up, down in graph_edges
+ if up in nodes_to_save and down in nodes_to_save
+ )
+ aliases, representatives, projected_edges = project_legacy_graph(
+ capture_order | nodes_to_save,
+ present_edges,
+ lambda key, _node: file_keys[key],
+ prefer=prefer,
+ )
+ if len(representatives) != len(nodes_to_save):
+ wire_graph = nx.DiGraph()
+ wire_graph.add_nodes_from(file_keys[key] for key in representatives)
+ wire_graph.add_edges_from(
+ (file_keys[up], file_keys[down]) for up, down in projected_edges
+ )
+ keys = {file_keys[key]: key for key in representatives}
+ wire_nodes: dict[str, GraphNode] = {}
+ for wire in nx.topological_sort(wire_graph):
+ key = keys[wire]
+ node = nodes_to_save[key]
+ invocation = self._invocation_lut.get(key)
+ if invocation is not None:
+ upstreams = tuple(
+ wire_nodes[file_keys[aliases[graph_key(upstream)]]]
+ for upstream in node.upstreams
+ )
+ if any(
+ before is not after
+ for before, after in zip(node.upstreams, upstreams, strict=True)
+ ):
+ corrected = self._node_from_invocation(invocation, upstreams)
+ corrected._label = node.label
+ assign_graph_key(corrected, key)
+ node = corrected
+ wire_nodes[wire] = node
+ nodes_to_save = {
+ keys[wire]: node
+ for wire, node in self._ordered_node_map(wire_nodes, wire_graph).items()
+ }
+ graph_edges = [
+ *projected_edges,
+ *(
+ (up, down)
+ for up, down in self._graph_edges
+ if up not in self._persistent_node_map
+ or down not in self._persistent_node_map
+ ),
+ ]
# Every node's own Arrow types, derived in one walk: an upstream that several
# nodes share is typed once (ITL-640).
@@ -154,7 +323,7 @@ def save(self, path: str | Path) -> None:
# output_schema and its source_config are both this entry (ITL-640).
slot_types: dict[str, dict[str, Any]] = {}
with shared_zero_row_memo():
- for key, node in self._persistent_node_map.items():
+ for key, node in nodes_to_save.items():
if isinstance(node, SourceNodeClass):
try:
slot_types[key] = node.saved_type_texts()
@@ -173,8 +342,7 @@ def save(self, path: str | Path) -> None:
raise
retained[key] = stored
nodes: dict[str, Any] = {}
- key_of = {id(node): key for key, node in self._persistent_node_map.items()}
- for content_hash_str, node in self._persistent_node_map.items():
+ for node_key, node in nodes_to_save.items():
try:
type_converter = node.data_context.type_converter
except (AttributeError, TypeError):
@@ -193,21 +361,18 @@ def save(self, path: str | Path) -> None:
config_val = config_for_save(node.orcapod_config)
try:
- output_schema: dict[str, Any] = (
- copy.deepcopy(slot_types[content_hash_str])
- if content_hash_str in slot_types
- else serialize_arrow_schemas(
- *arrow_types[content_hash_str], type_converter
+ if node_key in slot_types:
+ output_schema = copy.deepcopy(slot_types[node_key])
+ elif node_key in arrow_types:
+ output_schema = serialize_arrow_schemas(
+ *arrow_types[node_key], type_converter
)
- if content_hash_str in arrow_types
- else dict(retained[content_hash_str])
- if content_hash_str in retained
- # Only this branch reads the node's Python schema: a loaded node
- # whose saved schema names an unregistered logical type keeps
- # its retained texts above, and saving again never asks for a
- # Python type it cannot restore (CodeRabbit on PR 454).
- else serialize_output_schema(*node.output_schema(), type_converter)
- )
+ elif node_key in retained:
+ output_schema = dict(retained[node_key])
+ else:
+ # Read Python types only when no retained schema is available.
+ tags, data = node.output_schema()
+ output_schema = serialize_output_schema(tags, data, type_converter)
except ValueError as exc:
# A type text that would not read back (CodeRabbit on PR 454).
exc.add_note(f"Saving the pipeline's node {node.label!r}")
@@ -216,7 +381,7 @@ def save(self, path: str | Path) -> None:
descriptor: dict[str, Any] = {
"node_type": node.node_type,
"label": node.label,
- "content_hash": content_hash_str,
+ "content_hash": file_keys[node_key],
"pipeline_hash": node.pipeline_hash().to_string(),
# A node's own Arrow types are the saved authority (ITL-640): the
# types its rows have, from its typed zero-row table, never types
@@ -234,7 +399,7 @@ def save(self, path: str | Path) -> None:
# The slot's column types from the one writer (ITL-640): its own
# Arrow pair, or, while unresolved, the Arrow type texts it was
# loaded with, every column (an int32 stays int32).
- saved = slot_types[content_hash_str]
+ saved = slot_types[node_key]
descriptor["source_config"] = {
"source_type": "node",
"name": node.name,
@@ -279,9 +444,9 @@ def save(self, path: str | Path) -> None:
# (MergeJoin, SemiJoin) is rebuilt from this list, never from the
# edge list, which is sorted by hash before serialization.
inputs = [
- key_of[id(upstream)]
+ file_keys[key]
for upstream in node.upstreams
- if id(upstream) in key_of
+ if (key := graph_key(upstream)) in file_keys
]
if not inputs and OPERATOR_INPUTS_KEY in node._descriptor:
# A loaded read-only node holds no inputs: its saved list is
@@ -299,14 +464,18 @@ def save(self, path: str | Path) -> None:
)
descriptor["table_scope"] = node._table_scope
- nodes[content_hash_str] = descriptor
+ nodes[file_keys[node_key]] = descriptor
output: dict[str, Any] = {
"orcapod_pipeline_version": PIPELINE_FORMAT_VERSION,
"orcapod_version": orcapod.__version__,
"pipeline": {"name": list(self._name)},
"nodes": nodes,
- "edges": [list(edge) for edge in self._graph_edges],
+ "edges": sorted(
+ [file_keys[up], file_keys[down]]
+ for up, down in graph_edges
+ if up in file_keys and down in file_keys
+ ),
}
path = Path(path)
@@ -333,19 +502,20 @@ def load(cls, path: str | Path) -> "Pipeline":
writes or a node specifies a removed hash-length setting.
"""
import json as _json
+
+ from orcapod.core.nodes import FunctionNode, OperatorNode
+ from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass
from orcapod.pipeline.serialization import (
FALL_THROUGH_TAGS_KEY,
OPERATOR_INPUTS_KEY,
PIPELINE_FORMAT_VERSION,
- require_current_format,
- require_positively_commutative,
- require_nullability_records,
arrow_schema_from_texts,
deserialize_schema,
+ require_current_format,
+ require_nullability_records,
+ require_positively_commutative,
saved_fall_through_tags,
)
- from orcapod.core.nodes import FunctionNode, OperatorNode
- from orcapod.core.nodes.source_node import SourceNode as SourceNodeClass
from orcapod.types import Schema
path = Path(path)
@@ -623,19 +793,36 @@ def load(cls, path: str | Path) -> "Pipeline":
descriptor, input_stream=upstream_node
)
- # Keep old files' edge order only for the legacy input-order fallback above.
- edges = sorted((up, down) for up, down in edges)
+ # Reconstruct on the wire keys first, then translate every graph reference.
+ file_to_graph = {
+ key: graph_key(reconstructed.get(key), legacy_key=key) for key in edge_graph
+ }
reconstructed = cls._ordered_node_map(reconstructed, edge_graph)
+ reconstructed = {
+ file_to_graph[key]: node for key, node in reconstructed.items()
+ }
+ edges = sorted(
+ (file_to_graph[up], file_to_graph[down])
+ for up, down in edges
+ if up in file_to_graph and down in file_to_graph
+ )
- # Build Pipeline instance
pipeline = cls(name=name, auto_compile=False)
+ pipeline._loaded = True
+ pipeline._saved_keys = {value: key for key, value in file_to_graph.items()}
pipeline._loaded_output_schemas = {
- node_hash: descriptor["output_schema"]
- for node_hash, descriptor in nodes_data.items()
- if isinstance(descriptor.get("output_schema"), dict)
+ file_to_graph[key]: descriptor["output_schema"]
+ for key, descriptor in nodes_data.items()
+ if key in file_to_graph
+ and isinstance(descriptor.get("output_schema"), dict)
+ }
+ pipeline._persistent_node_map = reconstructed
+ pipeline._loaded_input_keys = {
+ file_to_graph[key]: [
+ file_to_graph[up] for up in upstreams if up in file_to_graph
+ ]
+ for key, upstreams in loaded_input_keys.items()
}
- pipeline._persistent_node_map = dict(reconstructed)
- pipeline._loaded_input_keys = loaded_input_keys
nodes_by_label: dict[str, GraphNode] = {}
for node in reconstructed.values():
@@ -650,15 +837,16 @@ def load(cls, path: str | Path) -> "Pipeline":
nodes_by_label[node.label] = node
pipeline._nodes = nodes_by_label
- node_dag: OrcaDAG[GraphNode] = OrcaDAG()
- for node in reconstructed.values():
+ node_dag: OrcaDAG[GraphNode] = keyed_dag(default_node_key)
+ for key, node in reconstructed.items():
+ assign_graph_key(node, key)
node_dag.add_node(node)
for up_hash, down_hash in edges:
up_node = reconstructed.get(up_hash)
down_node = reconstructed.get(down_hash)
if up_node is not None and down_node is not None:
node_dag.add_edge(up_node, down_node)
- pipeline._node_graph = node_dag
+ pipeline._publish_compiled_dag(node_dag)
pipeline._graph_edges = edges
pipeline._hash_graph = nx.DiGraph()
@@ -672,6 +860,12 @@ def load(cls, path: str | Path) -> "Pipeline":
if node.label:
attrs["label"] = node.label
+ for up, down in edges:
+ ordered = pipeline._loaded_input_keys.get(down, [up])
+ pipeline._hash_graph[up][down]["positions"] = tuple(
+ position for position, key in enumerate(ordered) if key == up
+ )
+
# Restore _node_lut and _upstreams so PipelineJob can substitute bound
# sources and build a correct execution graph at run time.
pipeline._node_lut = {
@@ -686,44 +880,5 @@ def load(cls, path: str | Path) -> "Pipeline":
pipeline._compiled = True
return pipeline
- def _clone_for_execution(self) -> "Pipeline":
- """Create a lightweight copy of this compiled pipeline for isolated execution.
-
- All structural state (``_node_lut``, ``_upstreams``, ``_graph_edges``,
- ``_hash_graph``, ``_node_graph``, ``_persistent_node_map``) is shared
- read-only with the original — these are immutable after ``compile()``.
- Only ``_nodes`` (the label → exec-node mapping) gets its own copy so
- that execution setup can update it without affecting other
- ``PipelineJob`` instances that reference this blueprint.
-
- The clone is never registered as a tracker context manager.
-
- Returns:
- A new ``Pipeline`` instance sharing read-only state with ``self``.
- """
- clone = Pipeline.__new__(Pipeline)
- # Base class state — clone is inactive and never registered
- clone._tracker_manager = self._tracker_manager
- clone._active = False
- # Shared read-only structural state (recording + compiled)
- clone._name = self._name
- clone._invocation_lut = self._invocation_lut
- clone._capture_key_generation = self._capture_key_generation
- clone._capture_stream_keys = {}
- clone._invocation_input_keys = self._invocation_input_keys
- clone._source_streams = self._source_streams
- clone._node_lut = self._node_lut
- clone._upstreams = self._upstreams
- clone._graph_edges = self._graph_edges
- clone._hash_graph = self._hash_graph
- clone._persistent_node_map = self._persistent_node_map
- clone._node_graph = self._node_graph
- clone._auto_compile = self._auto_compile
- clone._compiled = self._compiled
- clone._loaded_output_schemas = self._loaded_output_schemas
- # Mutable per-execution state — own copy so runs don't interfere
- clone._nodes = dict(self._nodes)
- return clone
-
def __dir__(self) -> list[str]:
return list(super().__dir__()) + list(self._nodes.keys())
diff --git a/src/orcapod/pipeline/job.py b/src/orcapod/pipeline/job.py
index 7ac378968..45d77d8e3 100644
--- a/src/orcapod/pipeline/job.py
+++ b/src/orcapod/pipeline/job.py
@@ -13,14 +13,28 @@
from itertools import chain
from typing import TYPE_CHECKING, Any, cast
+from typing_extensions import override
+
import orcapod
+from orcapod.core.base import live_content_hashes
from orcapod.core.database_writes import DatabaseWrites, collect_database_writes
-from orcapod.core.identity_chains import graph_hash
+from orcapod.core.identity_chains import (
+ IdentityChainsMixin,
+ assign_graph_key,
+ graph_key,
+)
from orcapod.core.nodes import JobNode
-from orcapod.core.nodes.function_node import FunctionJobNode
-from orcapod.core.nodes.operator_node import OperatorJobNode
-from orcapod.core.nodes.source_node import SourceJobNode
+from orcapod.core.nodes.function_node import FunctionJobNode, FunctionNodeBase
+from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNodeBase
+from orcapod.core.nodes.source_node import SourceJobNode, SourceNodeBase
from orcapod.core.nodes.staleness import RunHoldingNode
+from orcapod.core.output_bindings import (
+ OutputBindings,
+ bindings_changed,
+ capture_output_bindings,
+ identity_transaction,
+ output_lineage_version,
+)
from orcapod.core.sources.base import RootSource
from orcapod.core.sources.derived_source import DerivedSource
from orcapod.core.streams.base import StreamBase
@@ -34,20 +48,38 @@
OrcapodDatabaseWriteError,
UnboundSourceError,
)
-from orcapod.pipeline.base import AbstractPipelineBase
-from orcapod.pipeline.dag import OrcaDAG
+from orcapod.pipeline.base import (
+ AbstractPipelineBase,
+ ExecutionRoles,
+ _has_execution_binding,
+ _legacy_key,
+ execution_roles_for,
+)
+from orcapod.pipeline.dag import (
+ OrcaDAG,
+ default_node_key,
+ keyed_dag,
+ node_key_in,
+ nodes_of,
+ successors_of,
+)
from orcapod.pipeline.node_run import (
RunPlan,
check_sources,
clear_run_rows,
+ legacy_execution_dag,
plan_run,
)
+from orcapod.pipeline.pod_invocation import (
+ FunctionInvocation,
+ OperatorInvocation,
+ SideEffectInvocation,
+)
from orcapod.pipeline.observer_losses import RunLosses
from orcapod.pipeline.restrictions import (
refuse_restricted_operator_caches,
refuse_restriction_conflicts,
restrictions_in_force,
- streams_beneath,
warn_restricted_aggregation,
)
from orcapod.pipeline.run_summary import (
@@ -62,7 +94,9 @@
independent_source_dependency,
invocation_source_uses,
require_consistent_sources,
+ require_distinct_slot_bindings,
require_live_source_bindings,
+ walk_live_inputs,
)
from orcapod.protocols import core_protocols as cp
from orcapod.side_effects import SideEffectJobNode, SideEffectNode
@@ -85,14 +119,14 @@
from orcapod.databases._pending_commits import PendingCommits
from orcapod.pipeline.async_orchestrator import AsyncPipelineOrchestrator
from orcapod.pipeline.execution_context import ExecutionContext
- from orcapod.pipeline.graph import Pipeline
+ from orcapod.pipeline.graph import GraphNode, Pipeline
from orcapod.pipeline.observer_losses import LostObserverEvents
from orcapod.pipeline.pod_invocation import PodInvocation
from orcapod.pipeline.restrictions import Rebinding
from orcapod.pipeline.source_consistency import SourceUse
from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
- from orcapod.protocols.hashing_protocols import IdentityChainProtocol
+ from orcapod.protocols.hashing_protocols import ContentIdentifiableProtocol
from orcapod.protocols.observability_protocols import ExecutionObserverProtocol
logger = logging.getLogger(__name__)
@@ -105,22 +139,24 @@ def _backend(database: WriteDatabase) -> WriteDatabase:
return database
-def _refuse_shadowed_steps(nodes: Iterable[JobNode]) -> None:
- """Refuse distinct steps that would share an object-keyed DAG vertex (ITL-1767)."""
- steps: dict[JobNode, JobNode] = {}
+def _refuse_shadowed_steps(nodes: Iterable[cp.StreamProtocol]) -> None:
+ """Refuse distinct steps that the legacy execution projection would merge."""
+ steps: dict[str, list[cp.StreamProtocol]] = {}
for node in nodes:
- # Source slots can safely read the same source. Steps hold their own run
- # rows and each needs a vertex to receive them. Use the DAG's own Python
- # key semantics: equal content hashes alone do not imply equal keys.
if isinstance(node, SourceJobNode):
continue
- previous = steps.setdefault(node, node)
- if previous is not node:
- raise ValueError(
- f"Steps {previous.label!r} and {node.label!r} have the same "
- "identity in this job (ITL-1767). Put them in separate jobs or use "
- "only one of the two forms."
- )
+ digest = _legacy_key(node)
+ if digest is None:
+ continue
+ candidates = steps.setdefault(digest, [])
+ for previous in candidates:
+ if previous is not node and previous == node:
+ raise ValueError(
+ f"Steps {previous.label!r} and {node.label!r} have the same "
+ "identity in this job (ITL-1767). Put them in separate jobs or use "
+ "only one of the two forms."
+ )
+ candidates.append(node)
def _supports_attachment_enrollment(database: WriteDatabase) -> bool:
@@ -246,6 +282,23 @@ def _warn_run_completion(summary: RunSummary) -> None:
raise row_error
+@dataclass
+class _ExecutionGraph:
+ """Resolved nodes and availability of their execution identities."""
+
+ nodes: dict[str, cp.StreamProtocol]
+ unbound: set[str]
+ roles: ExecutionRoles
+
+ def refuse_shadowed_steps(self) -> None:
+ """Check the legacy equality of steps already known to share a hash."""
+ shared = self.roles.shared_step_keys()
+ if shared:
+ _refuse_shadowed_steps(
+ node for key, node in self.nodes.items() if key in shared
+ )
+
+
class PipelineJob(AbstractPipelineBase[JobNode]):
"""Pipeline + source bindings + execution context.
@@ -283,6 +336,8 @@ class PipelineJob(AbstractPipelineBase[JobNode]):
# Node-factory class attributes (used by AbstractPipelineBase.compile())
# ------------------------------------------------------------------
+ _capture_receiver = "job"
+
source_node_class = SourceJobNode
function_node_class = FunctionJobNode
operator_node_class = OperatorJobNode
@@ -321,6 +376,10 @@ def __init__(
self._unresolved_sources: dict[str, dict[str, Any]] = {}
self._rebound_source_keys: set[str] = set()
self._sources_as_captured: dict[str, cp.StreamProtocol | None] = {}
+ self._pending_source_slots: dict[str, SourceJobNode] = {}
+ self._execution_graph: _ExecutionGraph | None = None
+ self._stored_execution_bindings: dict[int, OutputBindings] = {}
+ self._execution_lineage_version: int | None = output_lineage_version()
self._has_run: bool = False
# True only while the last run started has finished and committed its writes:
# what the database then holds for each node is what that run left (ITL-1043).
@@ -347,36 +406,36 @@ def __exit__(self, exc_type=None, exc_value=None, traceback=None) -> None:
AutoRegisteringContextBasedTracker.__exit__(
self, exc_type, exc_value, traceback
)
- if exc_type is None and self._auto_compile:
+ if exc_type is None and self._auto_compile and not self._loaded:
if not self._compiled or self._has_uncompiled_invocations:
self.compile()
else:
- # A block that accepted no invocations can leave bindings partway
- # through a restore. Keep the normal refresh, and check the
- # bindings on an explicit compile or before running.
+ # An empty block still refreshes an already compiled graph.
self._compile_job()
- def _record_invocation(self, invocation: PodInvocation) -> None:
- super()._record_invocation(invocation)
+ def _remember_invocation(
+ self, key: str, invocation: PodInvocation, input_keys: tuple[str, ...]
+ ) -> None:
+ super()._remember_invocation(key, invocation, input_keys)
self._has_uncompiled_invocations = True
- def _input_graph_key(self, upstream: cp.StreamProtocol) -> str:
- """Reuse an active slot's recorded key when capturing from that slot."""
- if isinstance(upstream, SourceJobNode):
- for key, slot in self._persistent_node_map.items():
- if slot is upstream:
- return key
- return super()._input_graph_key(upstream)
-
- def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> None:
- """Require original bindings and refuse captures that can detach a slot."""
+ def _validate_capture_state(self) -> None:
+ """Require a live graph with its original bindings before recording."""
+ if self._loaded:
+ raise InconsistentSourceError(
+ "Capturing into a loaded job is not supported yet (ITL-1559). "
+ "Rebuild the job from its original code before adding steps."
+ )
# ITL-1559: refuse additive capture until the relationship between captured
# objects and slots is defined. Check at recording so a bind inside an
# open capture context cannot bypass the rule.
changed = sorted(
{
node.name
- for key, node in self._persistent_node_map.items()
+ for key, node in chain(
+ self._persistent_node_map.items(),
+ self._pending_source_slots.items(),
+ )
if isinstance(node, SourceJobNode)
and key in self._sources_as_captured
and node.bound_source is not self._sources_as_captured[key]
@@ -389,46 +448,16 @@ def _validate_capture_sources(self, streams: Iterable[cp.StreamProtocol]) -> Non
f"{names}. Bind them back to their original objects or build a new "
"job (ITL-1559)."
)
- # ITL-1559 stopgap: SourceJobNode has a mutable bound_source even when
- # unbound. SourceNode only declares a name and schemas.
- # A prebuilt stream can retain an own slot after compile replaces it.
- # Only recorded steps are rewired to their job's current slots.
- own_nodes = {id(node) for node in self._persistent_node_map.values()}
- visited: set[tuple[int, bool]] = set()
- pending = [(stream, False) for stream in streams]
- while pending:
- stream, prebuilt = pending.pop()
- key = id(stream), prebuilt
- if key in visited:
- continue
- visited.add(key)
- if (
- isinstance(stream, DerivedSource)
- and stream.stored_result_origin is not None
- and (dependency := independent_source_dependency(stream, self))
- is not None
- ):
- # The stored origin ends the live capture walk. Its metadata
- # still follows bindings, which must be valid for the new slot.
- raise binding_dependency_error(dependency, stream.source_name)
- if isinstance(stream, SourceJobNode):
- if id(stream) not in own_nodes:
- raise InconsistentSourceError(
- f"Capturing source slot {stream.name!r} from outside this job "
- "is not supported yet (ITL-1559). Pass the source itself, or "
- "use node.as_source() to read another job's stored results."
- )
- if prebuilt:
- raise InconsistentSourceError(
- f"Capturing a prebuilt stream over source slot {stream.name!r} "
- "is not supported yet (ITL-1559). Build the step inside the "
- "job from its slot, or pass the source itself."
- )
- elif id(stream) not in own_nodes and not (
- isinstance(stream, StreamBase) and stream._was_recorded_by(self)
- ):
- prebuilt = True
- pending.extend((upstream, prebuilt) for upstream in streams_beneath(stream))
+
+ def _validate_capture_root(self, stream: RootSource) -> None:
+ if (
+ isinstance(stream, DerivedSource)
+ and stream.stored_result_origin is not None
+ and (dependency := independent_source_dependency(stream, self)) is not None
+ ):
+ # A stored origin ends the live capture walk, but its metadata still
+ # follows bindings that must be valid for the new slot.
+ raise binding_dependency_error(dependency, stream.source_name)
def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse]:
"""Validate actual graph leaves after a binding replaces a captured input."""
@@ -440,8 +469,13 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse
for key, stream in self._source_streams.items():
if key in self._invocation_lut:
continue
- slot = self._persistent_node_map.get(key)
- if key in self._rebound_source_keys and isinstance(slot, SourceJobNode):
+ compiled_key = key
+ slot = self._pending_source_slots.get(
+ compiled_key, self._persistent_node_map.get(compiled_key)
+ )
+ if compiled_key in self._rebound_source_keys and isinstance(
+ slot, SourceJobNode
+ ):
yield f"node {slot.label!r}", slot
else:
yield f"source {stream.label!r}", stream
@@ -451,8 +485,11 @@ def _source_uses(self, extra: PodInvocation | None = None) -> Iterator[SourceUse
def _source_node_from_recording(self, key: str) -> SourceJobNode:
"""Preserve an explicit binding when recompiling its slot."""
stream = self._source_streams[key]
- if key in self._rebound_source_keys:
- slot = self._persistent_node_map.get(key)
+ compiled_key = key
+ if compiled_key in self._rebound_source_keys:
+ slot = self._pending_source_slots.get(
+ compiled_key, self._persistent_node_map.get(compiled_key)
+ )
if isinstance(slot, SourceJobNode):
stream = slot
source = stream.bound_source if isinstance(stream, SourceJobNode) else stream
@@ -463,8 +500,189 @@ def _source_node_from_recording(self, key: str) -> SourceJobNode:
elif isinstance(stream, RootSource):
name = stream.source_name
raise binding_dependency_error(dependency, name)
- return self.source_node_class.from_stream(stream)
+ captured = self._capture_nodes[key]
+ assert isinstance(captured, SourceNodeBase)
+ return self.source_node_class.from_stream(stream, name=captured.name)
+
+ def _watch_execution_inputs(self, streams: Iterable[cp.StreamProtocol]) -> None:
+ """Find descriptors that can change the execution roles of this job."""
+ for stream in walk_live_inputs(streams):
+ if isinstance(stream, (FunctionNodeBase, OperatorNodeBase)):
+ if stream._compiled_graph_key is None: # pyright: ignore[reportPrivateUsage] # compiled nodes have their own setter preflight
+ self._publish_capture_effect(
+ lambda stream=stream: stream._watch_rewire(self._prepare_rewire) # pyright: ignore[reportPrivateUsage] # the descriptor validates its dependent jobs
+ )
+ elif (
+ isinstance(stream, DerivedSource)
+ and (origin := stream.stored_result_origin) is not None
+ ):
+ self._stored_execution_bindings[id(stream)] = capture_output_bindings(
+ origin
+ )
+
+ def _prepare_rewire(
+ self, node: StreamBase, inputs: tuple[cp.StreamProtocol, ...]
+ ) -> Callable[[], Callable[[], None]] | None:
+ """Check new input ownership before the proposed edge is installed."""
+ roots = (
+ *self._binding_slots().values(),
+ *self._persistent_node_map.values(),
+ )
+ if not any(stream is node for stream in walk_live_inputs(roots)):
+ return None
+ require_live_source_bindings(roots, rewire=(node, inputs))
+ _ = self._rewire_input_keys(node, inputs, binding=True)
+ return self._prepare_rewired_roles
+
+ @override
+ def _validate_compiled_rewire(
+ self, node: StreamBase, inputs: tuple[cp.StreamProtocol, ...]
+ ) -> None:
+ """Preserve the shadowed-step refusal for proposals between held nodes."""
+ import networkx as nx
+
+ keys = self._rewire_input_keys(node, inputs)
+ node_key = graph_key(node)
+ if (
+ self._loaded
+ or self._persistent_node_map.get(node_key) is not node
+ or any(
+ key is None
+ or self._persistent_node_map.get(key) is not stream
+ or nx.has_path(self._hash_graph, node_key, key)
+ for key, stream in zip(keys, inputs, strict=True)
+ )
+ ):
+ return
+ with live_content_hashes():
+ graph = self._prospective_binding_nodes(
+ (), self._binding_slots().values(), rewire=(node, inputs)
+ )
+ graph.refuse_shadowed_steps()
+
+ def _prepare_rewired_roles(self) -> Callable[[], None]:
+ """Validate the job against a descriptor's proposed upstreams."""
+ slots = self._binding_slots().values()
+ with live_content_hashes():
+ graph = self._prospective_binding_nodes((), slots)
+ graph.refuse_shadowed_steps()
+ return lambda: self._publish_execution_graph(graph)
+
+ def _publish_execution_graph(self, graph: _ExecutionGraph) -> None:
+ self._execution_graph = graph
+ self._execution_roles = graph.roles
+ self._stored_execution_bindings.clear()
+ self._execution_lineage_version = output_lineage_version()
+ self._watch_execution_inputs(graph.nodes.values())
+
+ def _prepare_compiled_roles(
+ self, nodes: dict[str, cp.StreamProtocol], *, validate_steps: bool
+ ) -> Callable[[], None]:
+ slots = [
+ (node.name, node)
+ for node in nodes.values()
+ if isinstance(node, SourceJobNode)
+ ]
+ unbound: dict[int, str] = {}
+ steps: list[tuple[str, cp.StreamProtocol]] = []
+ for key, node in nodes.items():
+ if isinstance(node, SourceJobNode):
+ if not _has_execution_binding(node):
+ unbound[id(node)] = key
+ elif any(id(upstream) in unbound for upstream in node.upstreams):
+ unbound[id(node)] = key
+ else:
+ steps.append((key, node))
+ graph = _ExecutionGraph(
+ dict(nodes), set(unbound.values()), execution_roles_for(slots, steps)
+ )
+ if validate_steps:
+ graph.refuse_shadowed_steps()
+ # These are new descriptors. Role validation can pool their hashes,
+ # then the compiled graph starts with the usual lazy source-chain cache.
+ for node in nodes.values():
+ if isinstance(node, IdentityChainsMixin) and not node.upstreams:
+ node._invalidate_identity_chains() # pyright: ignore[reportPrivateUsage] # discard the proposal's identity memo before publication
+ return lambda: self._publish_execution_graph(graph)
+
+ def _prepare_capture_roles(
+ self,
+ invocation: PodInvocation,
+ key: str,
+ input_keys: tuple[str, ...],
+ leaves: dict[str, tuple[str, cp.StreamProtocol, SourceNodeBase]],
+ retained: bool,
+ ) -> Callable[[], None]:
+ graph = self._execution_graph
+ # A stored-result source can follow a binding in another job. Refresh
+ # the receiving index before testing a new role against that source.
+ refresh = self._execution_lineage_version is None or (
+ bool(self._stored_execution_bindings)
+ and (
+ self._execution_lineage_version != output_lineage_version()
+ or any(
+ bindings_changed(inputs)
+ for inputs in self._stored_execution_bindings.values()
+ )
+ )
+ )
+ if refresh:
+ with live_content_hashes():
+ graph = self._prospective_binding_nodes(
+ (), self._binding_slots().values()
+ )
+ added: dict[str, cp.StreamProtocol] = {}
+ unbound: set[str] = set()
+ if graph is None:
+ publish_roles = super()._prepare_capture_roles(
+ invocation, key, input_keys, leaves, retained
+ )
+ else:
+ concrete_slots: list[tuple[str, str | None]] = []
+ for name, (leaf_key, stream, _) in leaves.items():
+ slot = self.source_node_class.from_stream(stream, name=name)
+ added[leaf_key] = slot
+ if not _has_execution_binding(slot):
+ unbound.add(leaf_key)
+ else:
+ source = slot.bound_source
+ assert source is not None
+ concrete_slots.append((name, _legacy_key(source)))
+ role = None
+ if retained:
+ step: cp.StreamProtocol = self._node_from_invocation(
+ invocation,
+ tuple(
+ added[up] if up in added else graph.nodes[up]
+ for up in input_keys
+ ),
+ )
+ added[key] = step
+ if any(up in unbound or up in graph.unbound for up in input_keys):
+ unbound.add(key)
+ else:
+ role = _legacy_key(step)
+ publish_roles = graph.roles.prepare(
+ concrete_slots,
+ key if retained else None,
+ role,
+ )
+ def publish() -> None:
+ publish_roles()
+ if graph is not None:
+ graph.nodes.update(added)
+ graph.unbound.difference_update(added)
+ graph.unbound.update(unbound)
+ if refresh:
+ self._publish_execution_graph(graph)
+ return
+ self._watch_execution_inputs(stream for _, stream, _ in leaves.values())
+ self._execution_lineage_version = output_lineage_version()
+
+ return publish
+
+ @identity_transaction()
def compile(self) -> None:
"""Compile recorded invocations into a frozen DAG of job nodes.
@@ -485,18 +703,18 @@ def compile(self) -> None:
ValueError: If distinct steps would share a vertex in the job graph
and one would lose its current-run rows (ITL-1767).
"""
- self._compile_job(_refuse_shadowed_steps)
+ self._compile_job(validate_steps=True)
- def _compile_job(
- self, validate_nodes: Callable[[Iterable[JobNode]], None] | None = None
- ) -> None:
+ @identity_transaction()
+ def _compile_job(self, *, validate_steps: bool = False) -> None:
"""Rebuild the graph and wire the compiled job's bindings and databases."""
previous_slots = [
node
for node in self._persistent_node_map.values()
if isinstance(node, SourceJobNode)
]
- self._compile_nodes(validate_nodes)
+ self._compile_nodes(validate_steps=validate_steps)
+ self._pending_source_slots.clear()
self._has_uncompiled_invocations = False
for slot in previous_slots:
@@ -507,8 +725,8 @@ def _compile_job(
if isinstance(node, RunHoldingNode):
node._set_pipeline_job(self) # pyright: ignore[reportPrivateUsage] # compiled node provenance
if isinstance(node, SourceJobNode):
- if not self._loaded:
- self._sources_as_captured.setdefault(key, node.bound_source)
+ if not self._loaded and key not in self._rebound_source_keys:
+ self._sources_as_captured[key] = node.bound_source
node._set_binding_owner(self) # pyright: ignore[reportPrivateUsage] # setters participate in this job's binding transaction
if node.bound_source is not None:
self._sources[node.name] = node.bound_source
@@ -677,7 +895,6 @@ def from_pipeline(
# Bind concrete sources and distribute databases.
if bound_sources:
job.bind(sources=bound_sources)
- _refuse_shadowed_steps(job._persistent_node_map.values())
if database is not None:
job._distribute_databases()
@@ -735,8 +952,6 @@ def bind(
UnstorableColumnError: If *database* or *result_database* cannot store
a table of a node (ITL-1162); the job is left as it was.
"""
- from orcapod.core.nodes.source_node import SourceNodeBase
-
result_database_given = not isinstance(result_database, _Unchanged)
database_changed = (
database is not None and database is not self._database
@@ -748,18 +963,14 @@ def bind(
)
)
+ slots = self._binding_slots()
if sources is not None:
- source_names = {
- node.name
- for node in (self._persistent_node_map or {}).values()
- if isinstance(node, SourceNodeBase)
- }
- unknown = set(sources.keys()) - source_names
+ unknown = sources.keys() - slots.keys()
if unknown:
raise ValueError(
f"bind() received source keys with no matching source slot "
f"(SourceJobNode): {sorted(unknown)}. "
- f"Known slot names: {sorted(source_names)}"
+ f"Known slot names: {sorted(slots)}"
)
# A database that cannot store a node's tables is refused before anything
@@ -770,22 +981,27 @@ def bind(
# being bound may itself be a slot of another job with the same name.
to_bind = sources or {}
rebinding = [
- (node, to_bind[node.name])
- for node in (self._persistent_node_map or {}).values()
- if isinstance(node, SourceJobNode) and node.name in to_bind
+ (slot, to_bind[name]) for name, slot in slots.items() if name in to_bind
]
- prepared = self._prepare_source_bindings(rebinding)
new_database = database if database is not None else self._database
new_result_database = (
self._result_database
if isinstance(result_database, _Unchanged)
else result_database
)
- if database_changed and new_database is not None:
- self._require_storable_tables(new_database, new_result_database)
-
- # Every source is validated before anything changes: a refused source leaves
- # the job as it was, its database included (ITL-1112).
+ # Validate the proposed source and database bindings together before
+ # publishing either.
+ attach_databases = self._bind_sources(
+ rebinding,
+ slots.values(),
+ database_change=(new_database, new_result_database)
+ if database_changed
+ else None,
+ result_database_unresolved=(
+ not result_database_given
+ and self._unresolved_result_database is not None
+ ),
+ )
self._database = new_database
self._result_database = new_result_database
if database is not None:
@@ -793,33 +1009,56 @@ def bind(
if result_database_given:
self._unresolved_result_database = None
- self._apply_source_bindings(prepared)
-
if execution_context is not None:
self._execution_context = execution_context
- if database_changed and self._database is not None:
- self._distribute_databases()
+ if attach_databases is not None:
+ attach_databases()
def _replace_source_binding(
self, slot: SourceJobNode, source: cp.StreamProtocol | None
) -> None:
"""Apply a setter change through the same transaction as bind()."""
- self._apply_source_bindings(self._prepare_source_bindings([(slot, source)]))
+ self._bind_sources([(slot, source)], self._binding_slots().values())
+
+ def _binding_slots(self) -> dict[str, SourceJobNode]:
+ """Resolve active slots and materialize any leaves still awaiting compile."""
+ slots = {
+ node.name: node
+ for node in self._persistent_node_map.values()
+ if isinstance(node, SourceJobNode)
+ }
+ for name, (key, _) in self._capture_leaves.items():
+ if name in slots:
+ continue
+ node = self._pending_source_slots.get(key)
+ if node is None:
+ node = self._source_node_from_recording(key)
+ assign_graph_key(node, key)
+ slots[name] = node
+ return slots
def _prepare_source_bindings(
- self, rebinding: Rebinding
+ self, rebinding: Rebinding, slots: Iterable[SourceJobNode]
) -> list[tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]]:
"""Validate the prospective job and prepare each changed slot's row form."""
nodes = self._persistent_node_map.values()
# Walk the proposed bindings in input order so a refused batch names the
# same receiving slot as a single bind, then check the rest of the graph.
+ all_nodes = tuple(
+ chain(
+ slots, (node for node in nodes if not isinstance(node, SourceJobNode))
+ )
+ )
require_live_source_bindings(
- chain((slot for slot, _ in rebinding), nodes),
+ chain((slot for slot, _ in rebinding), all_nodes),
rebinding=rebinding,
)
+ for _, source in rebinding:
+ if source is not None:
+ self._capture_input_key(source, {}, binding=True)
require_consistent_sources(
- ((f"node {node.label!r}", node) for node in nodes), rebinding
+ ((f"node {node.label!r}", node) for node in all_nodes), rebinding
)
prepared = [
(
@@ -830,22 +1069,176 @@ def _prepare_source_bindings(
for slot, source in rebinding
]
refuse_restriction_conflicts(nodes, rebinding=rebinding)
+ replacements = {id(slot): source for slot, source in rebinding}
+ require_distinct_slot_bindings(
+ (slot.name, replacements.get(id(slot), slot.bound_source)) for slot in slots
+ )
return prepared
- def _apply_source_bindings(
+ def _prospective_binding_nodes(
self,
prepared: Sequence[
tuple[SourceJobNode, cp.StreamProtocol | None, _DeclaredForm | None]
],
- ) -> None:
- """Commit validated slot replacements and invalidate dependent predictions."""
+ binding_slots: Iterable[SourceJobNode],
+ *,
+ rewire: tuple[StreamBase, tuple[cp.StreamProtocol, ...]] | None = None,
+ ) -> _ExecutionGraph:
+ """Resolve proposed upstreams and check live execution identities."""
+ # Use fresh copies for changed slots and affected steps. Inspecting the
+ # proposal must not invalidate live caches or advance modification times.
+ shadow: dict[int, cp.StreamProtocol] = {}
+ unbound: set[int] = set()
+ for slot, source, form in prepared:
+ candidate = SourceJobNode.from_stream(slot.as_node())
+ candidate._apply_binding(source, form) # pyright: ignore[reportPrivateUsage] # only the temporary slot is changed
+ shadow[id(slot)] = candidate
+
+ steps: list[tuple[str, ContentIdentifiableProtocol]] = []
+ slots: list[tuple[str, cp.StreamProtocol]] = []
+ # A loaded step uses its saved identity even when a formerly bound
+ # upstream source could not be rebuilt in this process.
+ saved_unbound = (
+ self._saved_run.get("unbound_sources") if self._saved_run else None
+ )
+ for slot in binding_slots:
+ candidate = shadow.get(id(slot), slot)
+ slots.append((slot.name, candidate))
+ if (
+ not _has_execution_binding(candidate)
+ if saved_unbound is None
+ else slot.name in saved_unbound
+ ):
+ unbound.add(id(slot))
+
+ nodes = cast(
+ "Iterable[JobNode | SideEffectJobNode]", self._persistent_node_map.values()
+ )
+ for node in nodes:
+ if isinstance(node, SourceJobNode):
+ continue
+ candidate: ContentIdentifiableProtocol = node
+ rewire_inputs = (
+ rewire[1] if rewire is not None and node is rewire[0] else None
+ )
+ upstreams = node.upstreams if rewire_inputs is None else rewire_inputs
+ if not self._loaded and (
+ rewire_inputs is not None or any(id(up) in shadow for up in upstreams)
+ ):
+ inputs = tuple(shadow.get(id(up), up) for up in upstreams)
+ if isinstance(node, SideEffectJobNode):
+ pod = node.producer
+ assert pod is not None # A live side-effect node has its pod.
+ invocation = SideEffectInvocation(pod, inputs, label=node.label)
+ elif isinstance(node, FunctionJobNode):
+ invocation = FunctionInvocation(
+ node.producer, inputs, label=node.label
+ )
+ else:
+ invocation = OperatorInvocation(
+ node.producer, inputs, label=node.label
+ )
+ replacement: cp.StreamProtocol = self._node_from_invocation(
+ invocation, inputs
+ )
+ if isinstance(node, OperatorJobNode) and isinstance(
+ replacement, OperatorJobNode
+ ):
+ replacement._cache_mode = node.cache_mode # pyright: ignore[reportPrivateUsage] # validate with the live node's cache mode
+ shadow[id(node)] = replacement
+ candidate = replacement
+ if any(id(up) in unbound for up in upstreams):
+ unbound.add(id(node))
+ else:
+ steps.append((graph_key(node), candidate))
+
+ resolved: dict[str, cp.StreamProtocol] = {
+ graph_key(node): shadow.get(id(node), cast("cp.StreamProtocol", node))
+ for node in chain(nodes, binding_slots)
+ }
+ unbound_keys = {
+ graph_key(node)
+ for node in chain(nodes, binding_slots)
+ if id(node) in unbound
+ }
+ if self._invocation_lut.keys() - self._persistent_node_map.keys():
+ import networkx as nx
+
+ # Resolve new branches even when inputs are unbound. Their declared
+ # schemas still determine what the candidate databases must store.
+ for key in nx.topological_sort(self._capture_graph):
+ if key in resolved:
+ continue
+ input_keys = self._invocation_input_keys[key]
+ inputs = tuple(resolved[up] for up in input_keys)
+ step: cp.StreamProtocol = self._node_from_invocation(
+ self._invocation_lut[key], inputs
+ )
+ resolved[key] = step
+ if any(up in unbound_keys for up in input_keys):
+ unbound_keys.add(key)
+ else:
+ steps.append((key, step))
+ refuse_restriction_conflicts(resolved.values())
+ return _ExecutionGraph(
+ resolved, unbound_keys, execution_roles_for(slots, steps)
+ )
+
+ @identity_transaction()
+ def _bind_sources(
+ self,
+ rebinding: Rebinding,
+ slots: Iterable[SourceJobNode],
+ *,
+ restoring: bool = False,
+ database_change: tuple[
+ ArrowDatabaseProtocol | None, ArrowDatabaseProtocol | None
+ ]
+ | None = None,
+ result_database_unresolved: bool = False,
+ ) -> Callable[[], None] | None:
+ """Validate and install a batch of job bindings as one transaction."""
+ slots = tuple(slots)
+ prepared = self._prepare_source_bindings(rebinding, slots)
+ has_pending_steps = bool(
+ self._invocation_lut.keys() - self._persistent_node_map.keys()
+ )
+ attach_databases = None
+ execution_graph = None
+ if prepared or database_change is not None:
+ with live_content_hashes():
+ execution_graph = self._prospective_binding_nodes(prepared, slots)
+ if not restoring:
+ execution_graph.refuse_shadowed_steps()
+ prospective = execution_graph.nodes
+ if database_change is not None or has_pending_steps:
+ database, result_database = database_change or (
+ self._database,
+ self._result_database,
+ )
+ if database is not None:
+ views = self._database_views(database, result_database)
+ self._require_storable_tables(prospective.values(), *views)
+ if database_change is not None:
+ attach_databases = self._prepare_database_attachments(
+ *views,
+ result_database_unresolved=result_database_unresolved,
+ )
+ elif result_database is not None:
+ for node in prospective.values():
+ if isinstance(node, FunctionJobNode):
+ node.require_storable_results(result_database)
if not prepared:
- return
- keys = {id(node): key for key, node in self._persistent_node_map.items()}
+ return attach_databases
for slot, source, form in prepared:
+ key = graph_key(slot)
+ if key not in self._persistent_node_map:
+ self._sources_as_captured.setdefault(key, slot.bound_source)
+ self._pending_source_slots[key] = slot
slot._apply_binding(source, form) # pyright: ignore[reportPrivateUsage] # install the validated row form
- slot._update_modified_time() # pyright: ignore[reportPrivateUsage] # the job owns the slot's binding
- self._rebound_source_keys.add(keys[id(slot)])
+ if not restoring:
+ slot._update_modified_time() # pyright: ignore[reportPrivateUsage] # the job owns the slot's binding
+ self._rebound_source_keys.add(key)
self._unresolved_sources.pop(slot.name, None)
if source is None:
self._sources.pop(slot.name, None)
@@ -857,6 +1250,10 @@ def _apply_source_bindings(
for node in self._persistent_node_map.values():
if isinstance(node, StreamBase):
node._forget_output_schema() # pyright: ignore[reportPrivateUsage] # the job owns its nodes' bindings
+ assert execution_graph is not None
+ self._publish_execution_graph(execution_graph)
+
+ return attach_databases
# ------------------------------------------------------------------
# _distribute_databases()
@@ -885,81 +1282,67 @@ def _database_views(
return pipeline_db, result_database
return pipeline_db, pipeline_db.at("_result")
+ @staticmethod
def _require_storable_tables(
- self,
- database: "ArrowDatabaseProtocol",
- result_database: "ArrowDatabaseProtocol | None",
+ nodes: Iterable[cp.StreamProtocol],
+ pipeline_db: ArrowDatabaseProtocol,
+ result_db: ArrowDatabaseProtocol,
) -> None:
- """Refuse databases that cannot store a table of one of the job's nodes.
-
- The same views as ``_distribute_databases`` gives the nodes. Nothing
- changes (ITL-1162).
-
- Args:
- database: The job database to check.
- result_database: The separate function-result database to check, if any.
-
- Raises:
- UnstorableColumnError: For the first node whose table a database
- cannot store, naming the node.
- """
- pipeline_db, result_db = self._database_views(database, result_database)
- for node in (self._persistent_node_map or {}).values():
+ """Refuse database views that cannot store a node's tables (ITL-1162)."""
+ for node in nodes:
if isinstance(node, FunctionJobNode):
- # Checked against the candidate databases only, never the job's
- # current binding state: a loaded job (the only one whose result
- # database can be unavailable) has function nodes without a function,
- # which this check skips by itself.
node.require_storable_tables(pipeline_db, result_db)
elif isinstance(node, OperatorJobNode):
node.require_storable_tables(pipeline_db, node.cache_mode)
elif isinstance(node, SideEffectJobNode):
node.require_storable_tables(pipeline_db)
- def _distribute_databases(self) -> None:
- """Wire live DB references to all FunctionJobNode and OperatorJobNode objects.
+ def _prepare_database_attachments(
+ self,
+ pipeline_db: ArrowDatabaseProtocol,
+ result_db: ArrowDatabaseProtocol,
+ *,
+ result_database_unresolved: bool,
+ ) -> Callable[[], None]:
+ """Prepare the live nodes' final database state for installation."""
+ attachments: list[Callable[[], None]] = []
+ for node in self._persistent_node_map.values():
+ if isinstance(node, FunctionJobNode):
+ if not result_database_unresolved:
+ attachments.append(
+ node._prepare_database_attachment(pipeline_db, result_db)
+ ) # pyright: ignore[reportPrivateUsage] # the job preflights its node attachments together
+ elif isinstance(node, OperatorJobNode):
+ attachments.append(
+ node._prepare_database_attachment(pipeline_db, node.cache_mode)
+ ) # pyright: ignore[reportPrivateUsage] # the job preflights its node attachments together
+ elif isinstance(node, SideEffectJobNode):
+ attachments.append(node._prepare_database_attachment(pipeline_db)) # pyright: ignore[reportPrivateUsage] # the job preflights its node attachments together
- Called by ``compile()`` when a database is already set, and by ``bind()``
- when *database* is changed.
+ def attach() -> None:
+ for install in attachments:
+ install()
+ self._node_database_views = (pipeline_db, result_db)
- Raises:
- RuntimeError: If ``_database`` is not set.
- """
+ return attach
+
+ def _distribute_databases(self) -> None:
+ """Validate and wire the database views of newly compiled or loaded nodes."""
if self._database is None:
raise RuntimeError(
"Cannot distribute databases: no database is set. "
"Call bind(database=...) or from_pipeline(..., database=...) first."
)
- # Every node is checked before any is attached, so a refused database
- # leaves every node as it was (ITL-1162), and so is a caching operator over
- # a restricted source (ITL-1218).
- refuse_restricted_operator_caches((self._persistent_node_map or {}).values())
- self._require_storable_tables(self._database, self._result_database)
- pipeline_db, result_db = self._database_views(
- self._database, self._result_database
+ nodes = self._persistent_node_map.values()
+ refuse_restricted_operator_caches(nodes)
+ views = self._database_views(self._database, self._result_database)
+ self._require_storable_tables(nodes, *views)
+ attach = self._prepare_database_attachments(
+ *views,
+ result_database_unresolved=self._unresolved_result_database is not None,
)
-
- nodes = (self._persistent_node_map or {}).values()
- for node in nodes:
- if isinstance(node, FunctionJobNode):
- if self._unresolved_result_database is not None:
- # Left without a database (see ``load``), never given ``_result``.
- continue
- node.attach_databases(
- pipeline_database=pipeline_db,
- result_database=result_db,
- )
- elif isinstance(node, OperatorJobNode):
- node.attach_databases(
- pipeline_database=pipeline_db,
- cache_mode=node.cache_mode,
- )
- elif isinstance(node, SideEffectJobNode):
- node.attach_databases(
- pipeline_database=pipeline_db,
- )
- self._node_database_views = (pipeline_db, result_db)
+ attach()
# ------------------------------------------------------------------
# _iter_function_job_nodes() / apply_node_config()
@@ -1017,10 +1400,8 @@ def as_pipeline(self) -> "Pipeline":
Walks ``_persistent_node_map`` topologically and rewires each job
node to a fresh blueprint node whose upstreams point at the
- already-built blueprint nodes in ``node_map`` (not at job nodes).
- This ensures that the content_hash of every node in the returned
- ``Pipeline`` is consistent with the hash keys in
- ``_persistent_node_map``.
+ already-built blueprint nodes in ``node_map``. Their slot names and
+ structure remain available independently of the job's bindings.
Returns:
A compiled ``Pipeline`` whose ``_persistent_node_map`` contains
@@ -1051,21 +1432,14 @@ def as_pipeline(self) -> "Pipeline":
persistent = self._persistent_node_map
- # Reverse lookup: job node Python id → its key in _persistent_node_map.
- # Required to wire blueprint upstreams to the correct hash key even when
- # job node identity (content_hash) differs from the map key.
- job_id_to_bp_hash: dict[int, str] = {
- id(job_node): bp_hash for bp_hash, job_node in persistent.items()
- }
-
- node_map: dict[str, IdentityChainProtocol] = {}
+ node_map: dict[str, Any] = {}
for node_hash, job_node in persistent.items():
if isinstance(job_node, SourceJobNode):
node_map[node_hash] = job_node.as_node()
elif isinstance(job_node, FunctionJobNode):
- upstream_bp_hash = job_id_to_bp_hash[id(job_node._input_stream)]
+ upstream_bp_hash = graph_key(job_node._input_stream)
node_map[node_hash] = FunctionNode(
function_pod=job_node._function_pod,
input_stream=node_map[upstream_bp_hash],
@@ -1076,7 +1450,7 @@ def as_pipeline(self) -> "Pipeline":
elif isinstance(job_node, OperatorJobNode):
blueprint_upstreams = tuple(
- node_map[job_id_to_bp_hash[id(s)]] for s in job_node._input_streams
+ node_map[graph_key(s)] for s in job_node._input_streams
)
node_map[node_hash] = OperatorNode(
operator=job_node._operator,
@@ -1089,14 +1463,14 @@ def as_pipeline(self) -> "Pipeline":
elif isinstance(job_node, LoadedSideEffectJobNode):
# No pod to wrap: the blueprint node is restored from the saved
# entry, with the saved blueprint identity (ITL-1094).
- upstream_bp_hash = job_id_to_bp_hash[id(job_node._input_stream)]
+ upstream_bp_hash = graph_key(job_node._input_stream)
node_map[node_hash] = LoadedSideEffectNode(
job_node._descriptor,
cast("cp.StreamProtocol", node_map[upstream_bp_hash]),
)
elif isinstance(job_node, SideEffectJobNode):
- upstream_bp_hash = job_id_to_bp_hash[id(job_node._input_stream)]
+ upstream_bp_hash = graph_key(job_node._input_stream)
node_map[node_hash] = SideEffectNode(
side_effect_pod=job_node._pod,
input_stream=node_map[upstream_bp_hash],
@@ -1106,12 +1480,9 @@ def as_pipeline(self) -> "Pipeline":
else:
node_map[node_hash] = job_node.as_node()
- # Remap captured keys to the corresponding blueprint declarations' hashes.
- old_to_new: dict[str, str] = {
- h: graph_hash(bp_node).to_string() for h, bp_node in node_map.items()
- }
- # Re-key node_map with declaration hashes.
- new_node_map: dict[str, object] = {
+ # The blueprint shares the job's structure and declared slot names.
+ old_to_new = {h: graph_key(bp_node) for h, bp_node in node_map.items()}
+ new_node_map: dict[str, GraphNode] = {
new_h: node_map[h] for h, new_h in old_to_new.items()
}
@@ -1130,9 +1501,14 @@ def as_pipeline(self) -> "Pipeline":
for u, v in self._graph_edges
if u in old_to_new and v in old_to_new
)
- bp_hash_graph.add_edges_from(new_graph_edges)
+ bp_hash_graph.add_edges_from(
+ (old_to_new[up], old_to_new[down], dict(self._hash_graph[up][down]))
+ for up, down in self._graph_edges
+ if up in old_to_new and down in old_to_new
+ )
pipeline = Pipeline(name=self._name, auto_compile=False)
+ pipeline._from_compiled_job = True
pipeline._hash_graph = bp_hash_graph
pipeline._graph_edges = new_graph_edges
pipeline._persistent_node_map = new_node_map
@@ -1143,20 +1519,20 @@ def as_pipeline(self) -> "Pipeline":
old_to_new[h]: node_map[h] for h in self._node_lut if h in old_to_new
}
pipeline._nodes = {
- label: node_map[job_id_to_bp_hash[id(job_node)]]
+ label: node_map[graph_key(job_node)]
for label, job_node in self._nodes.items()
- if id(job_node) in job_id_to_bp_hash
- and job_id_to_bp_hash[id(job_node)] in node_map
+ if graph_key(job_node) in node_map
}
# Build _node_graph (OrcaDAG with node objects as vertices).
# node_map here contains GraphNode objects (blueprint nodes).
- bp_dag: OrcaDAG = OrcaDAG()
- for node in pipeline._persistent_node_map.values():
+ bp_dag: OrcaDAG[GraphNode] = keyed_dag(default_node_key)
+ for key, node in new_node_map.items():
+ assign_graph_key(node, key)
bp_dag.add_node(node)
for up_h, down_h in new_graph_edges:
bp_dag.add_edge(new_node_map[up_h], new_node_map[down_h])
- pipeline._node_graph = bp_dag
+ pipeline._publish_compiled_dag(bp_dag)
pipeline._compiled = True
@@ -1214,21 +1590,13 @@ def is_complete(self) -> bool:
return self._database is not None and not self.unbound_sources
def is_runnable(self, node_label: str) -> bool:
- """Return whether a live job has all upstream inputs of *node_label* resolved.
-
- A loaded job is read-only and always returns ``False``.
-
- Uses hash-based traversal of ``_hash_graph`` combined with
- ``_persistent_node_map`` to check whether every upstream source slot
- is bound. This avoids relying on the object-identity graph
- (``_node_graph``), which breaks after ``bind()`` because
- ``SourceJobNode.__hash__()`` changes when ``bound_source`` is mutated.
+ """Return whether a compiled node has all its sources bound.
Args:
node_label: Label of the node to check.
Returns:
- ``True`` if the node can be executed with current bindings.
+ Whether the node can execute with the current bindings.
"""
if self._loaded or not self._compiled:
return False
@@ -1236,21 +1604,8 @@ def is_runnable(self, node_label: str) -> bool:
target = self._nodes.get(node_label)
if target is None:
return False
-
- # Build a reverse lookup: node object id → hash key.
- # _persistent_node_map covers SourceJobNode slots (all compiled paths)
- # and all node types for directly-compiled jobs.
- # _node_lut covers non-source nodes for loaded jobs, where
- # _persistent_node_map only holds SourceJobNodes.
- node_id_to_hash: dict[int, str] = {}
- for h, node in self._node_lut.items():
- node_id_to_hash[id(node)] = h
- for h, node in self._persistent_node_map.items():
- # _persistent_node_map wins on collision (it contains live job nodes)
- node_id_to_hash[id(node)] = h
-
- target_hash = node_id_to_hash.get(id(target))
- if target_hash is None:
+ target_hash = graph_key(target)
+ if target_hash not in self._hash_graph:
return False
import networkx as nx
@@ -1498,6 +1853,34 @@ async def run_async(
_warn_run_completion(summary)
return summary
+ def _project_run(self, exec_dag: OrcaDAG[JobNode]) -> tuple[OrcaDAG[JobNode], str]:
+ """Use main's content equality for both scheduling and the stored run URI."""
+ import hashlib
+
+ try:
+ exec_dag = legacy_execution_dag(exec_dag)
+ except NotImplementedError:
+ # Keep positioned replay when an old saved stub has a digest but
+ # no equality structure to select a representative.
+ hashes = {
+ node_key_in(exec_dag, node): node.content_hash().to_string()
+ for node in nodes_of(exec_dag)
+ }
+ upstream_hashes = {
+ hashes[node_key_in(exec_dag, upstream)]
+ for upstream, _ in exec_dag.edges()
+ }
+ leaf_hashes = sorted(set(hashes.values()) - upstream_hashes)
+ else:
+ leaf_hashes = sorted(
+ node.content_hash().to_string()
+ for node in nodes_of(exec_dag)
+ if not successors_of(exec_dag, node)
+ )
+
+ snapshot_hash = hashlib.sha256("\n".join(leaf_hashes).encode()).hexdigest()[:16]
+ return exec_dag, "/".join(self._name) + "@" + snapshot_hash
+
def _prepare_run(
self, commit_every_rows: int, *, load_only: bool = False
) -> "_PreparedRun":
@@ -1515,7 +1898,6 @@ def _prepare_run(
RuntimeError: As for ``run``.
OrcapodDatabaseError: If writes still pending from before the run cannot be committed.
"""
- import hashlib
if (
isinstance(commit_every_rows, bool)
@@ -1671,7 +2053,7 @@ def _prepare_run(
self._last_run_finished = False
# --- Build execution OrcaDAG from existing node objects (no cloning) ---
- exec_dag: OrcaDAG = OrcaDAG()
+ exec_dag: OrcaDAG[JobNode] = keyed_dag(default_node_key)
for node in runnable_nodes:
exec_dag.add_node(node)
for u_hash, v_hash in self._graph_edges:
@@ -1688,16 +2070,7 @@ def _prepare_run(
run_id = uuid.uuid4().hex[:16]
- # Snapshot hash: SHA-256 of the sink nodes' content hashes, for the run URI.
- # Each enters with its label (ITL-1154); the result is written into a name,
- # the run URI, and so is bare hex.
- leaf_hashes = sorted(
- node.content_hash().to_string()
- for node in exec_dag.nodes()
- if not exec_dag.successors(node) and hasattr(node, "content_hash")
- )
- snapshot_hash = hashlib.sha256("\n".join(leaf_hashes).encode()).hexdigest()[:16]
- pipeline_uri = "/".join(self._name) + "@" + snapshot_hash
+ exec_dag, pipeline_uri = self._project_run(exec_dag)
pipeline_db, result_db = self._database_views(
self._database, self._result_database
@@ -1706,10 +2079,10 @@ def _prepare_run(
# A source read under two restrictions, or a caching operator over a restricted
# source, is refused before any source is checked and before anything is
# computed or written (ITL-1218).
- refuse_restriction_conflicts(exec_dag.nodes())
+ refuse_restriction_conflicts(nodes_of(exec_dag))
# Every source first takes in any new data, moving its modified time, before
# the state rule judges any node (ITL-1102).
- unchecked = check_sources(exec_dag.nodes())
+ unchecked = check_sources(nodes_of(exec_dag))
# A restricted source under an aggregation is allowed, and said (ITL-1218).
warn_restricted_aggregation(exec_dag)
# The state rule (ITL-1095): a node that holds a current run is not run again.
@@ -2006,7 +2379,7 @@ def _finish_run(
load_only=load_only,
unchecked_sources=unchecked_sources,
ran_nothing=not plan.to_run,
- restricted_sources=restrictions_in_force(prepared.exec_dag.nodes()),
+ restricted_sources=restrictions_in_force(nodes_of(prepared.exec_dag)),
asynchronous=asynchronous,
lost_observer_events=lost_observer_events,
)
@@ -2422,6 +2795,7 @@ def load(
require_consistent_sources(
(f"slot {name!r}", source) for name, source in sources.items()
)
+ require_distinct_slot_bindings(sources.items())
# Reconstruct database
effective_database = database
@@ -2532,7 +2906,9 @@ def load(
from orcapod.core.nodes.source_node import SourceNode as _SourceNode
from orcapod.pipeline.loaded_side_effects import LoadedSideEffectJobNode
- job._sources = dict(sources)
+ job._sources = {
+ name: source for name, source in sources.items() if name not in slots
+ }
job._unresolved_sources = unresolved_sources
# Extract the live (data-inclusive) content hashes saved at run time.
@@ -2590,9 +2966,7 @@ def load(
for node_hash, bp_node in pipeline._persistent_node_map.items():
if isinstance(bp_node, _SourceNode):
# Keeps the loaded slot's saved hashes and saved type texts (ITL-1138).
- sjn = SourceJobNode._from_loaded_slot( # pyright: ignore[reportPrivateUsage] # the loader is the one caller
- bp_node, bound_source=sources.get(bp_node.name)
- )
+ sjn = SourceJobNode.from_stream(bp_node)
sjn._set_binding_owner(job) # pyright: ignore[reportPrivateUsage] # loading assigns the job's active slots
job._persistent_node_map[node_hash] = sjn
@@ -2655,13 +3029,8 @@ def load(
# Update _nodes to point to job nodes (FunctionJobNode/OperatorJobNode stubs)
# rather than blueprint nodes, so that job.nodes["label"].get_all_records()
# works on a loaded job.
- bp_id_to_hash: dict[int, str] = {
- id(bp): h for h, bp in pipeline._persistent_node_map.items()
- }
job._nodes = {
- label: job._persistent_node_map.get(
- bp_id_to_hash.get(id(bp_node), ""), bp_node
- )
+ label: job._persistent_node_map.get(graph_key(bp_node), bp_node)
for label, bp_node in pipeline._nodes.items()
}
@@ -2669,10 +3038,9 @@ def load(
# node map. This makes job.dag consistent with the compiled-job path
# (where compile() builds _node_graph from job nodes).
# Callers needing blueprint nodes for rendering use job.pipeline.dag.
- # Stored views read the persistent nodes directly. Check for shadowed
- # steps if a load-only run builds an execution graph to fill live views.
- job_dag: OrcaDAG = OrcaDAG()
- for node in job._persistent_node_map.values():
+ job_dag: OrcaDAG[JobNode] = keyed_dag(default_node_key)
+ for key, node in job._persistent_node_map.items():
+ assign_graph_key(node, key)
if isinstance(node, RunHoldingNode):
node._set_pipeline_job(job) # pyright: ignore[reportPrivateUsage] # restored node provenance
job_dag.add_node(node)
@@ -2681,7 +3049,18 @@ def load(
v_node = job._persistent_node_map.get(v_hash)
if u_node is not None and v_node is not None:
job_dag.add_edge(u_node, v_node)
- job._node_graph = job_dag
+ job._publish_compiled_dag(job_dag)
+
+ restored_slots = job._binding_slots()
+ job._bind_sources(
+ [
+ (slot, sources[name])
+ for name, slot in restored_slots.items()
+ if name in sources
+ ],
+ restored_slots.values(),
+ restoring=True,
+ )
if effective_database is not None:
job._distribute_databases()
diff --git a/src/orcapod/pipeline/node_run.py b/src/orcapod/pipeline/node_run.py
index a18f23049..bd563d367 100644
--- a/src/orcapod/pipeline/node_run.py
+++ b/src/orcapod/pipeline/node_run.py
@@ -33,6 +33,7 @@
from orcapod.utils.database_errors import flush_best_effort
if TYPE_CHECKING:
+ from orcapod.pipeline.dag import NodeT, OrcaDAG
from orcapod.protocols.database_protocols import ArrowDatabaseProtocol
@@ -280,11 +281,13 @@ class RunPlan:
dag: Any
held: Mapping[Any, Any]
to_run: list[Any]
- held_counts: dict[Any, int]
- held_rows: dict[Any, list[Any]]
+ held_counts: Mapping[Any, int]
+ held_rows: Mapping[Any, list[Any]]
-def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> RunPlan:
+def plan_run(
+ graph: OrcaDAG[Any], *, load_only: bool, outside: Sequence[Any] = ()
+) -> RunPlan:
"""Choose the nodes a run runs: the state rule of every job node's run (ITL-1095).
A node that holds a current run (``holds_current_run``) is not run; a source slot
@@ -308,7 +311,12 @@ def plan_run(graph: Any, *, load_only: bool, outside: Sequence[Any] = ()) -> Run
"""
from orcapod.core.nodes.source_node import SourceJobNode
from orcapod.core.nodes.staleness import RunHoldingNode
- from orcapod.pipeline.dag import OrcaDAG
+ from orcapod.pipeline.dag import (
+ NodeMap,
+ empty_dag_like,
+ predecessors_of,
+ successors_of,
+ )
order = list(graph.topological_sort())
@@ -343,31 +351,33 @@ def is_source(node: Any) -> bool:
included: list[Any] = []
for node in order:
feeds_a_run = any(
- any(successor is r for r in to_run) for successor in graph.successors(node)
+ any(successor is r for r in to_run)
+ for successor in successors_of(graph, node)
)
if any(node is r for r in to_run) or feeds_a_run:
included.append(node)
- dag: OrcaDAG[Any] = OrcaDAG()
+ dag = empty_dag_like(graph)
for node in included:
dag.add_node(node)
for node in to_run:
- for upstream in graph.predecessors(node):
+ for upstream in predecessors_of(graph, node):
dag.add_edge(upstream, node)
# A held node's output stream: what the sync orchestrator built from its rows for
# the nodes after it, exactly (ITL-1347, stage 2).
- held_rows = {
- node: list(node.iter_data())
- for node in included
- if not any(node is r for r in to_run) and not is_source(node)
- }
+ held_rows: NodeMap[Any, list[Any]] = NodeMap(dag)
+ for node in included:
+ if not any(node is r for r in to_run) and not is_source(node):
+ held_rows[node] = list(node.iter_data())
# The rows main held, built where a successor reads them (``RowsOnRead``,
# ``at_edge``), never while planning; an async run reads only the rows.
# The plan keeps no output it handed out (``keep=False``): the orchestrator drops
# each once the node's successors ran.
- held = StreamsOnRead(held_rows, _rows_on_read, keep=False)
+ held = StreamsOnRead(held_rows, _rows_on_read, keep=False, graph=dag)
# Counted from what each node holds: iterating an operator's rows would build a
# (Tag, Data) pair per row only to count them (ITL-1351).
- held_counts = {node: node.held_row_count() for node in current}
+ held_counts: NodeMap[Any, int] = NodeMap(graph)
+ for node in current:
+ held_counts[node] = node.held_row_count()
return RunPlan(dag, held, to_run, held_counts, held_rows)
@@ -396,6 +406,35 @@ def commit_run(databases: Sequence[ArrowDatabaseProtocol], ran: Sequence[Any]) -
raise
+def legacy_execution_dag(graph: OrcaDAG[NodeT]) -> OrcaDAG[NodeT]:
+ """Schedule the first representative of each legacy content identity."""
+ from orcapod.pipeline.dag import (
+ keyed_dag,
+ node_key_in,
+ nodes_of,
+ project_legacy_graph,
+ )
+
+ members = {node_key_in(graph, node): node for node in nodes_of(graph)}
+ aliases, representatives, edges = project_legacy_graph(
+ members,
+ (
+ (node_key_in(graph, up), node_key_in(graph, down))
+ for up, down in graph.edges()
+ ),
+ lambda _key, node: node,
+ )
+ if len(representatives) == len(aliases):
+ return graph
+
+ projected = keyed_dag(lambda node: aliases[node_key_in(graph, node)])
+ for key in representatives:
+ projected.add_node(members[key])
+ for up, down in edges:
+ projected.add_edge(members[up], members[down])
+ return projected
+
+
def run_with_dependencies(
target: Any, *, load_only: bool, unchecked_sources: Sequence[str] = ()
) -> RunSummary:
@@ -424,18 +463,22 @@ def run_with_dependencies(
ValueError: For a load-only run, if a node it would run reads an input that
computes or delivers when read (``refuse_unloadable_inputs``); nothing has run then.
"""
+ from orcapod.core.identity_chains import graph_key
from orcapod.core.nodes.source_node import SourceJobNode
- from orcapod.pipeline.dag import OrcaDAG
+ from orcapod.pipeline.dag import OrcaDAG, keyed_dag, nodes_of
from orcapod.pipeline.sync_orchestrator import SyncPipelineOrchestrator
- graph: OrcaDAG[Any] = OrcaDAG()
- active: set[int] = set()
- seen: set[int] = set()
+ compiled = target._compiled_graph_key is not None
+ # A standalone cascade can cross job boundaries. Walk its live objects and
+ # keep the caller's content equality when adding them to the temporary DAG.
+ graph: OrcaDAG[Any] = keyed_dag(graph_key) if compiled else OrcaDAG()
+ active: set[str | int] = set()
+ seen: set[str | int] = set()
outside: list[Any] = []
def visit(node: Any) -> None:
"""Add ``node`` and what it depends on, up to the sources of the job."""
- key = id(node)
+ key = graph_key(node) if compiled else id(node)
if key in active:
raise live_input_cycle_error()
if key in seen:
@@ -454,6 +497,12 @@ def visit(node: Any) -> None:
active.remove(key)
visit(target)
+ if compiled:
+ try:
+ graph = legacy_execution_dag(graph)
+ except NotImplementedError:
+ # Saved stubs can lack the equality structure used by the projection.
+ pass
plan = plan_run(graph, load_only=load_only, outside=outside)
databases = _databases(plan.to_run)
counter = RunCountingObserver()
@@ -479,5 +528,5 @@ def visit(node: Any) -> None:
target=target.label,
unchecked_sources=unchecked_sources,
ran_nothing=not plan.to_run,
- restricted_sources=restrictions_in_force(graph.nodes()),
+ restricted_sources=restrictions_in_force(nodes_of(graph)),
)
diff --git a/src/orcapod/pipeline/pod_invocation.py b/src/orcapod/pipeline/pod_invocation.py
index d7d394f90..9d06c1533 100644
--- a/src/orcapod/pipeline/pod_invocation.py
+++ b/src/orcapod/pipeline/pod_invocation.py
@@ -1,20 +1,18 @@
"""PodInvocation — minimal recording primitives for pipeline invocations.
These lightweight value objects capture a pod-plus-streams invocation at
-recording time. Bound capture keys use the structure and source chain,
-and unbound capture keys use the structure and name chain.
+recording time. Their graph addresses are computed from structure and upstream
+slot names, independently of display labels.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
-from weakref import ReferenceType
from orcapod.contexts import resolve_context
from orcapod.core.base import ContentIdentifiableBase, PipelineElementBase
from orcapod.core.output_bindings import require_current_outputs
from orcapod.core.identity_chains import (
- graph_hash,
pipeline_argument_group,
structural_argument_symmetry,
IdentityChainsMixin,
@@ -22,8 +20,6 @@
)
if TYPE_CHECKING:
- from collections.abc import Callable, MutableMapping
-
from orcapod.protocols.core_protocols import (
ArgumentGroup,
FunctionPodProtocol,
@@ -35,9 +31,6 @@
from orcapod.types import ContentHash
-CaptureStreamKeys = tuple["StreamProtocol | ReferenceType[StreamProtocol]", str]
-
-
class PodInvocation( # pyright: ignore[reportUnsafeMultipleInheritance] # Both hash bases use cooperative super().__init__.
ContentIdentifiableBase, PipelineElementBase, IdentityChainsMixin
):
@@ -127,34 +120,6 @@ def pipeline_identity_structure(self) -> Any:
pipeline_argument_group(self._pod, self._input_streams),
)
- def capture_keys(
- self,
- streams: MutableMapping[int, CaptureStreamKeys],
- input_key: Callable[[StreamProtocol], str],
- ) -> tuple[str, tuple[str, ...]]:
- """Compute graph keys bottom-up so deep captures stay stack-safe."""
- pending = [(stream, False) for stream in reversed(self.input_streams)]
- while pending:
- stream, expanded = pending.pop()
- stream_id = id(stream)
- if (previous := streams.get(stream_id)) is not None:
- owner = previous[0]
- if (owner() if isinstance(owner, ReferenceType) else owner) is stream:
- continue
- if (
- not expanded
- and stream.producer is not None
- and (inputs := stream.upstreams)
- ):
- pending.append((stream, True))
- pending.extend((upstream, False) for upstream in reversed(inputs))
- continue
- streams[stream_id] = (stream, input_key(stream))
-
- return graph_hash(self).to_string(), tuple(
- streams[id(stream)][1] for stream in self.input_streams
- )
-
class FunctionInvocation(PodInvocation):
"""Invocation of a function pod against a single input stream.
diff --git a/src/orcapod/pipeline/restrictions.py b/src/orcapod/pipeline/restrictions.py
index bfb2c51ac..37369de91 100644
--- a/src/orcapod/pipeline/restrictions.py
+++ b/src/orcapod/pipeline/restrictions.py
@@ -18,7 +18,7 @@
from __future__ import annotations
from collections.abc import Iterable, Mapping, Sequence
-from typing import TYPE_CHECKING, TypeAlias
+from typing import TYPE_CHECKING, TypeAlias, TypeVar
from orcapod.types import CacheMode, Condition
@@ -30,6 +30,9 @@
from orcapod.protocols.core_protocols import StreamProtocol
+_StreamT = TypeVar("_StreamT", bound="StreamProtocol")
+
+
Restriction: TypeAlias = tuple[Condition, int | None]
"""What a source reads under: its condition (the empty ``Condition`` for none) and its
row limit (``None`` for none). Two are one when the conditions are equal (``Condition``
@@ -187,6 +190,7 @@ def sources_read(
from orcapod.core.sources.base import RootSource
found: list[tuple[str, str, Restriction | None]] = []
+ # Hold each visited object so its identity stays unique throughout the walk.
visited: dict[int, StreamProtocol] = {}
pending = list(streams)
while pending:
@@ -469,7 +473,7 @@ def restrictions_in_force(
return found
-def warn_restricted_aggregation(dag: OrcaDAG[StreamProtocol]) -> None:
+def warn_restricted_aggregation(dag: OrcaDAG[_StreamT]) -> None:
"""Warn once when a restricted source feeds a ``GroupBy``, ``Batch`` or ``MergeJoin``.
Called by ``job.run()`` and ``run_async()`` before the run (ITL-1218). The
@@ -482,18 +486,24 @@ def warn_restricted_aggregation(dag: OrcaDAG[StreamProtocol]) -> None:
"""
import sys
+ from orcapod.pipeline.dag import ancestors_of, node_key_in, nodes_of
from orcapod.core.operators import Batch, GroupBy, MergeJoin
from orcapod.core.sources.display_names import node_display_names
from orcapod.errors import RestrictedAggregationWarning
from orcapod.utils.warning_utils import outside_orcapod_stacklevel, warn_at_frame
- position = {node: index for index, node in enumerate(dag.nodes())}
+ position = {
+ node_key_in(dag, node): index for index, node in enumerate(nodes_of(dag))
+ }
pairs: list[tuple[str, str, str]] = []
- for node in position:
+ for node in nodes_of(dag):
step = node.producer
if not isinstance(step, (GroupBy, Batch, MergeJoin)):
continue
- ancestors = sorted(dag.ancestors(node), key=position.__getitem__)
+ ancestors = sorted(
+ ancestors_of(dag, node),
+ key=lambda upstream: position[node_key_in(dag, upstream)],
+ )
pairs.extend(
(slot, node.label, type(step).__name__)
for slot in restrictions_in_force(ancestors)
@@ -501,7 +511,7 @@ def warn_restricted_aggregation(dag: OrcaDAG[StreamProtocol]) -> None:
if not pairs:
return
# A source is named by its assigned label; its id is then given once, at the end.
- shown = node_display_names(position)
+ shown = node_display_names(nodes_of(dag))
texts = {slot: shown[slot][0] for slot, _, _ in pairs if slot in shown}
legend = "".join(
f" {text!r} is {shown[slot][1]}." for slot, text in sorted(texts.items())
diff --git a/src/orcapod/pipeline/result.py b/src/orcapod/pipeline/result.py
index e4c7e9e65..419ef4438 100644
--- a/src/orcapod/pipeline/result.py
+++ b/src/orcapod/pipeline/result.py
@@ -2,11 +2,14 @@
from __future__ import annotations
-from collections.abc import Callable, Iterator, Mapping
+from collections.abc import Callable, Iterator, Mapping, MutableMapping
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any
+from orcapod.pipeline.dag import NodeMap
+
if TYPE_CHECKING:
+ from orcapod.pipeline.dag import GraphProtocol
from orcapod.protocols.core_protocols import StreamProtocol
@@ -29,6 +32,7 @@ def __init__(
build: Callable[[Any, Any], "StreamProtocol"],
*,
keep: bool = True,
+ graph: GraphProtocol[Any] | None = None,
) -> None:
"""Hold each node's rows and how a stream is built from them.
@@ -36,13 +40,18 @@ def __init__(
rows: Each node's rows.
build: Builds a node's stream from its rows, given ``(rows, node)``.
keep: Keep a stream once built, so a second read returns it again.
+ graph: The graph that owns the row keys, when available.
"""
- self._node_ids = {node: id(node) for node in rows}
- # A live node's content hash can move after binding. The same node must
- # still find the output of this run, including on its first lookup.
- self._entries = {
- id(node): (node, node_rows) for node, node_rows in rows.items()
- }
+ self._node_ids: MutableMapping[Any, int] = (
+ NodeMap(graph) if graph is not None else {}
+ )
+ # A rebind can change a live node's hash. Keep its run rows and the
+ # original node together so a first read can check its saved bindings.
+ self._entries: dict[int, tuple[Any, Any]] = {}
+ for node, node_rows in rows.items():
+ key = id(node)
+ self._node_ids[node] = key
+ self._entries[key] = (node, node_rows)
self._build = build
self._keep = keep
self._built: dict[int, StreamProtocol] = {}
diff --git a/src/orcapod/pipeline/run_summary.py b/src/orcapod/pipeline/run_summary.py
index 619ef0457..69c36e386 100644
--- a/src/orcapod/pipeline/run_summary.py
+++ b/src/orcapod/pipeline/run_summary.py
@@ -622,6 +622,7 @@ def run_node_summaries(
"""
from dataclasses import replace
+ from orcapod.pipeline.dag import predecessors_of
from orcapod.protocols.node_protocols import (
is_function_node,
is_side_effect_function_node,
@@ -633,7 +634,7 @@ def run_node_summaries(
summaries: list[NodeRunSummary] = []
for node in order:
above: set[int] = set()
- for upstream in dag.predecessors(node):
+ for upstream in predecessors_of(dag, node):
above |= skipping_above.get(id(upstream), set())
if getattr(upstream, "last_run_not_stored", 0):
above.add(id(upstream))
diff --git a/src/orcapod/pipeline/source_consistency.py b/src/orcapod/pipeline/source_consistency.py
index ea5ac9be8..1e6f17e82 100644
--- a/src/orcapod/pipeline/source_consistency.py
+++ b/src/orcapod/pipeline/source_consistency.py
@@ -3,9 +3,9 @@
from __future__ import annotations
from collections import Counter
-from collections.abc import Iterable
+from collections.abc import Iterable, Iterator
from dataclasses import dataclass
-from typing import TYPE_CHECKING, cast
+from typing import TYPE_CHECKING, TypeAlias, cast
from orcapod.errors import (
InconsistentSourceError,
@@ -26,6 +26,37 @@
from orcapod.types import ContentHash
SourceUse = tuple[str, "StreamProtocol"]
+Rewire: TypeAlias = "tuple[StreamProtocol, tuple[StreamProtocol, ...]]"
+
+
+def live_inputs(
+ stream: StreamProtocol, rebinding: Rebinding = ()
+) -> tuple[StreamProtocol, ...]:
+ """Follow live input provenance, including the origin of materialized rows."""
+ from orcapod.core.operators.static_output_pod import RowsOnRead
+ from orcapod.core.streams.arrow_table_stream import ArrowTableStream
+ from orcapod.pipeline.restrictions import streams_beneath
+
+ if isinstance(stream, RowsOnRead):
+ return (stream._node,) # pyright: ignore[reportPrivateUsage] # inspect provenance without building rows
+ if isinstance(stream, ArrowTableStream):
+ origin = stream._identity_origin # pyright: ignore[reportPrivateUsage] # row-backed identity retains its producer
+ if origin is not None:
+ return (origin,)
+ return streams_beneath(stream, rebinding)
+
+
+def walk_live_inputs(streams: Iterable[StreamProtocol]) -> Iterator[StreamProtocol]:
+ """Visit each reachable live input once, leaving stored-result origins opaque."""
+ pending = list(streams)
+ seen: dict[int, StreamProtocol] = {}
+ while pending:
+ stream = pending.pop()
+ if id(stream) in seen:
+ continue
+ seen[id(stream)] = stream
+ yield stream
+ pending.extend(live_inputs(stream))
def binding_dependency_error(
@@ -74,6 +105,7 @@ def _binding_dependency(
streams: Iterable[StreamProtocol],
binding: _Binding | None = None,
rebinding: Rebinding = (),
+ rewire: Rewire | None = None,
) -> StreamProtocol | None:
"""Walk live and stored-result dependencies before a read resolves them.
@@ -85,7 +117,11 @@ def _binding_dependency(
"""
from orcapod.core.nodes.source_node import SourceJobNode
from orcapod.core.sources.derived_source import DerivedSource
- from orcapod.pipeline.restrictions import streams_beneath
+
+ def dependencies(stream: StreamProtocol) -> tuple[StreamProtocol, ...]:
+ if rewire is not None and stream is rewire[0]:
+ return rewire[1]
+ return live_inputs(stream, rebinding)
pending = [(stream, binding, False) for stream in reversed(tuple(streams))]
active: dict[int, StreamProtocol] = {}
@@ -139,7 +175,7 @@ def _binding_dependency(
current_binding = _Binding(slot_owner, stream)
pending.extend(
(upstream, current_binding, False)
- for upstream in reversed(streams_beneath(stream, rebinding))
+ for upstream in reversed(dependencies(stream))
)
checked_origins: set[tuple[int, int]] = set()
@@ -162,7 +198,7 @@ def _binding_dependency(
):
ancestry.append(stored_origin)
else:
- ancestry.extend(reversed(streams_beneath(stream, rebinding)))
+ ancestry.extend(reversed(dependencies(stream)))
return None
@@ -176,10 +212,13 @@ def independent_source_dependency(
def require_live_source_bindings(
- streams: Iterable[StreamProtocol], rebinding: Rebinding = ()
+ streams: Iterable[StreamProtocol],
+ rebinding: Rebinding = (),
+ *,
+ rewire: Rewire | None = None,
) -> None:
"""Check live bindings before resolving schemas or hashes, reading rows or running."""
- _binding_dependency(streams, rebinding=rebinding)
+ _binding_dependency(streams, rebinding=rebinding, rewire=rewire)
def invocation_source_uses(invocations: Iterable[PodInvocation]) -> Iterable[SourceUse]:
@@ -284,6 +323,28 @@ def live_schemas(
return arrow_schema_identity(*schemas, source.data_context)
+def require_distinct_slot_bindings(
+ slots: Iterable[tuple[str, StreamProtocol | None]],
+) -> None:
+ """Refuse one object assigned to two slots in a job."""
+ from orcapod.core.sources.base import RootSource
+
+ seen: dict[int, str] = {}
+ for name, source in slots:
+ if source is None:
+ continue
+ first = seen.setdefault(id(source), name)
+ if first != name:
+ identity = (
+ source.source_id if isinstance(source, RootSource) else source.label
+ )
+ raise InconsistentSourceError(
+ f"Source {identity!r} would be read by slots {first!r} and {name!r}. "
+ "One source object on two slots is not supported yet (ITL-1559, "
+ "step 6). Read it through one slot and branch from that slot."
+ )
+
+
def require_consistent_sources(
uses: Iterable[SourceUse],
rebinding: Rebinding = (),
diff --git a/src/orcapod/pipeline/sync_orchestrator.py b/src/orcapod/pipeline/sync_orchestrator.py
index 5167ea901..4e2baaa94 100644
--- a/src/orcapod/pipeline/sync_orchestrator.py
+++ b/src/orcapod/pipeline/sync_orchestrator.py
@@ -11,8 +11,14 @@
from typing import TYPE_CHECKING, Any, Literal
from orcapod.errors import OrcapodDatabaseError, TypeIdentityError
+from orcapod.pipeline.dag import (
+ NodeMap,
+ node_key_in,
+ operand_key_in,
+ predecessors_of,
+ successors_of,
+)
from orcapod.pipeline.result import OrchestratorResult
-from orcapod.utils.database_errors import keep_database_error
from orcapod.protocols.node_protocols import (
is_function_node,
is_operator_node,
@@ -20,13 +26,14 @@
is_side_effect_node,
is_source_node,
)
+from orcapod.utils.database_errors import keep_database_error
if TYPE_CHECKING:
- from collections.abc import Mapping
+ from collections.abc import Hashable, Mapping, MutableMapping
from orcapod.pipeline.dag import GraphProtocol
- from orcapod.protocols.observability_protocols import ExecutionObserverProtocol
from orcapod.protocols.core_protocols import StreamProtocol
+ from orcapod.protocols.observability_protocols import ExecutionObserverProtocol
logger = logging.getLogger(__name__)
@@ -99,14 +106,17 @@ def run(
# changes how the graph finds that node afterwards.
neighbours = (
{
- id(n): (list(graph.predecessors(n)), list(graph.successors(n)))
+ node_key_in(graph, n): (
+ list(predecessors_of(graph, n)),
+ list(successors_of(graph, n)),
+ )
for n in topo_order
}
if materialize_results
else {}
)
- outputs: dict[Any, StreamProtocol] = {}
- processed: set[Any] = set()
+ outputs: NodeMap[Any, StreamProtocol] = NodeMap(graph)
+ processed: set[Hashable] = set()
held_streams = held if held is not None else {}
for node in topo_order:
@@ -143,12 +153,14 @@ def run(
f"Unknown node type: {getattr(node, 'node_type', None)!r}"
)
- processed.add(node)
+ processed.add(node_key_in(graph, node))
if not materialize_results:
self._gc_outputs(node, graph, outputs, processed)
else:
- self._release_built_inputs(node, neighbours, outputs, processed)
+ self._release_built_inputs(
+ node, graph, neighbours, outputs, processed
+ )
if not materialize_results:
outputs.clear()
@@ -174,10 +186,10 @@ def run(
def _single_input(
node: Any,
graph: "GraphProtocol[Any]",
- outputs: dict[Any, StreamProtocol],
+ outputs: MutableMapping[Any, StreamProtocol],
) -> StreamProtocol:
"""The output stream of a node's one predecessor (function and side-effect nodes)."""
- predecessors = list(graph.predecessors(node))
+ predecessors = list(predecessors_of(graph, node))
if len(predecessors) != 1:
raise ValueError(
f"FunctionNode expects exactly 1 upstream, got {len(predecessors)}"
@@ -190,21 +202,26 @@ def _single_input(
def _ordered_inputs(
node: Any,
graph: "GraphProtocol[Any]",
- outputs: dict[Any, StreamProtocol],
+ outputs: MutableMapping[Any, StreamProtocol],
) -> list[StreamProtocol]:
"""The output streams of an operator node's predecessors, in ``node.upstreams`` order."""
from orcapod.core.nodes.operator_node import ordered_operator_inputs
from orcapod.core.operators.static_output_pod import at_edge
- predecessors = ordered_operator_inputs(node, graph.predecessors(node))
+ predecessors = ordered_operator_inputs(
+ node,
+ predecessors_of(graph, node),
+ key=lambda upstream: operand_key_in(graph, upstream),
+ )
return [at_edge(outputs[p]) for p in predecessors]
@staticmethod
def _release_built_inputs(
current_node: Any,
- neighbours: dict[int, tuple[list[Any], list[Any]]],
- outputs: dict[Any, StreamProtocol],
- processed: set[Any],
+ graph: "GraphProtocol[Any]",
+ neighbours: dict[Hashable, tuple[list[Any], list[Any]]],
+ outputs: MutableMapping[Any, StreamProtocol],
+ processed: set[Hashable],
) -> None:
"""Keep a retained output read by all its successors as its rows only.
@@ -214,17 +231,18 @@ def _release_built_inputs(
Args:
current_node: The node that just ran.
- neighbours: Each node's predecessors and successors, by ``id``, taken
- before the run.
+ graph: The graph whose keys index the nodes' results.
+ neighbours: Each node's predecessors and successors, taken before the run.
outputs: The retained outputs.
processed: The nodes that ran.
"""
from orcapod.core.operators.static_output_pod import RowsOnRead
- for pred in neighbours[id(current_node)][0]:
+ for pred in neighbours[node_key_in(graph, current_node)][0]:
output = outputs.get(pred)
if isinstance(output, RowsOnRead) and all(
- succ in processed for succ in neighbours[id(pred)][1]
+ node_key_in(graph, succ) in processed
+ for succ in neighbours[node_key_in(graph, pred)][1]
):
output.release_built()
@@ -232,15 +250,16 @@ def _release_built_inputs(
def _gc_outputs(
current_node: Any,
graph: "GraphProtocol[Any]",
- outputs: dict[Any, StreamProtocol],
- processed: set[Any],
+ outputs: MutableMapping[Any, StreamProtocol],
+ processed: set[Hashable],
) -> None:
"""Drop output streams no unprocessed successor still needs."""
- for pred in graph.predecessors(current_node):
+ for pred in predecessors_of(graph, current_node):
if pred not in outputs:
continue
all_successors_done = all(
- succ in processed for succ in graph.successors(pred)
+ node_key_in(graph, succ) in processed
+ for succ in successors_of(graph, pred)
)
if all_successors_done:
del outputs[pred]
diff --git a/src/orcapod/protocols/pipeline_protocols.py b/src/orcapod/protocols/pipeline_protocols.py
index 4d39cc75b..f60d5f248 100644
--- a/src/orcapod/protocols/pipeline_protocols.py
+++ b/src/orcapod/protocols/pipeline_protocols.py
@@ -39,7 +39,7 @@ def name(self) -> tuple[str, ...]:
@property
def nodes(self) -> dict[str, NodeT]:
- """Copy of the compiled label -> node mapping."""
+ """Copy of the compiled nodes, keyed by label."""
...
@property
diff --git a/src/orcapod/side_effects.py b/src/orcapod/side_effects.py
index 46d70d5f3..11ca9537e 100644
--- a/src/orcapod/side_effects.py
+++ b/src/orcapod/side_effects.py
@@ -1216,16 +1216,30 @@ def attach_databases(
# A database that cannot store the invocation log refuses it now,
# before anything is delivered or changes (ITL-1162).
self.require_storable_tables(pipeline_database)
- self._pipeline_database = pipeline_database
- self._unlisted_store_reported = False
- self._current_log_checked = False
- if pipeline_database is not None:
- self._table_path = self.node_uri + (
+ attach = self._prepare_database_attachment(pipeline_database)
+ attach()
+
+ def _prepare_database_attachment(
+ self, pipeline_database: ArrowDatabaseProtocol | None
+ ) -> Callable[[], None]:
+ """Prepare the invocation log path after its storage checks pass."""
+ table_path = (
+ self.node_uri
+ + (
f"schema:{self.pipeline_hash().to_hex()}",
TRACKING_DB_SCHEMA_VERSION,
)
- else:
- self._table_path = None
+ if pipeline_database is not None
+ else None
+ )
+
+ def attach() -> None:
+ self._pipeline_database = pipeline_database
+ self._unlisted_store_reported = False
+ self._current_log_checked = False
+ self._table_path = table_path
+
+ return attach
# ------------------------------------------------------------------
# Sync execution
diff --git a/test-specification/unit/test_tracker.py b/test-specification/unit/test_tracker.py
index 7e1a7b197..54e11366a 100644
--- a/test-specification/unit/test_tracker.py
+++ b/test-specification/unit/test_tracker.py
@@ -38,7 +38,9 @@ def _make_stream(n: int = 3) -> ArrowTableSource:
"x": pa.array([i * 10 for i in range(n)], type=pa.int64()),
}
)
- return ArrowTableSource(table, tag_columns=["id"], infer_nullable=True)
+ return ArrowTableSource(
+ table, tag_columns=["id"], tag_only_columns=True, infer_nullable=True
+ )
class TestBasicTrackerManager:
@@ -127,6 +129,4 @@ def test_compile_builds_graph(self):
tracker.record_function_pod_invocation(pod, spec)
tracker.compile()
- graph = tracker.graph
- assert graph is not None
- assert graph.number_of_nodes() >= 1
+ assert len(tracker.dag) >= 1
diff --git a/tests/test_core/data_function/test_function_record.py b/tests/test_core/data_function/test_function_record.py
index e85b3c507..5d23ad484 100644
--- a/tests/test_core/data_function/test_function_record.py
+++ b/tests/test_core/data_function/test_function_record.py
@@ -448,7 +448,10 @@ def test_a_function_without_source_works_in_a_job_and_stores_a_null(
label="typed_in",
)
job.run(orchestrator=orchestrator())
- assert sorted(d["v"] for _, d in job.nodes["typed_in"].iter_data()) == [10, 20]
+ assert sorted(d["v"] for _, d in job.nodes["typed_in"].iter_data()) == [
+ 10,
+ 20,
+ ]
result_path = next(p for p in database.list_table_paths() if "_result" in p)
stored = database.get_all_records(result_path)
assert stored is not None
diff --git a/tests/test_core/data_tags/test_tag_by.py b/tests/test_core/data_tags/test_tag_by.py
index 8218112df..4644e9ac7 100644
--- a/tests/test_core/data_tags/test_tag_by.py
+++ b/tests/test_core/data_tags/test_tag_by.py
@@ -419,8 +419,14 @@ def test_in_a_job_a_function_node_stores_the_new_tag_marked(
tagged = TagBy("session")(computed, label="tag_by")
double.pod(tagged, label="double")
job.run(orchestrator=orchestrator())
- assert job.nodes["tag_by"].keys() == (("unit", "session"), ("unit", "session"))
- assert job.nodes["double"].keys() == (("unit", "session"), ("unit", "session", "y"))
+ assert job.nodes["tag_by"].keys() == (
+ ("unit", "session"),
+ ("unit", "session"),
+ )
+ assert job.nodes["double"].keys() == (
+ ("unit", "session"),
+ ("unit", "session", "y"),
+ )
rows = sorted(job.nodes["double"].as_table().to_pylist(), key=lambda r: r["unit"])
assert [(r["unit"], r["session"], r["y"]) for r in rows] == [
(1, "s0", "s0s0"),
diff --git a/tests/test_core/operators/test_index_pick_arrow_types.py b/tests/test_core/operators/test_index_pick_arrow_types.py
index be7690233..21b13547a 100644
--- a/tests/test_core/operators/test_index_pick_arrow_types.py
+++ b/tests/test_core/operators/test_index_pick_arrow_types.py
@@ -25,7 +25,7 @@
import polars as pl
import pytest
-from orcapod import PipelineJob, contexts
+from orcapod import contexts
from orcapod.channels import Channel
from orcapod.contexts import DataContext, get_default_type_converter
from orcapod.core.operators import (
@@ -35,6 +35,7 @@
MapData,
MapTags,
Pick,
+ PolarsFilter,
SelectDataColumns,
SelectTagColumns,
)
@@ -42,7 +43,6 @@
from orcapod.core.nodes.operator_node import OperatorJobNode
from orcapod.core.sources import ArrowTableSource, DictSource
from orcapod.core.streams import ArrowTableStream
-from orcapod.databases import InMemoryArrowDatabase
from orcapod.errors import InputValidationError
from orcapod.logical_types.base_logical_type import BaseLogicalType
from orcapod.logical_types.registry import (
@@ -689,20 +689,15 @@ async def test_rewired_projection_uses_current_input(
expected: object,
expected_type: type,
) -> None:
- """Schema prediction and both job paths follow a rewired upstream description."""
+ """Schema prediction and both node execution paths follow a rewired descriptor."""
original = DictSource(
[{"c": old_value, "x": 1}], data_schema={"c": old_type, "x": int}
)
current = DictSource(
[{"c": current_value, "x": 1}], data_schema={"c": current_type, "x": int}
)
- job = PipelineJob(name="rewired", database=InMemoryArrowDatabase())
- with job:
- filtered = original.polars_filter(x=1, label="upstream")
- _ = op(filtered, label="projection")
- upstream, node = job.nodes["upstream"], job.nodes["projection"]
- assert isinstance(upstream, OperatorJobNode)
- assert isinstance(node, OperatorJobNode)
+ upstream = OperatorJobNode(PolarsFilter(constraints={"x": 1}), (original,))
+ node = OperatorJobNode(op, (upstream,))
_ = upstream.pipeline_hash()
upstream.upstreams = (current,)
assert op.output_schema(upstream)[1]["c"] is expected_type
diff --git a/tests/test_core/operators/test_semijoin_tag_keys.py b/tests/test_core/operators/test_semijoin_tag_keys.py
index 3d0828a97..652402c5f 100644
--- a/tests/test_core/operators/test_semijoin_tag_keys.py
+++ b/tests/test_core/operators/test_semijoin_tag_keys.py
@@ -428,11 +428,9 @@ async def test_empty_right_after_operator_node_is_rewired() -> None:
"""A node rewired to an unkeyed pair passes through its left rows."""
left, other, right = _shared_operator_inputs(False, False)
empty = right.polars_filter(u=0)
- job = PipelineJob(name="rewired_semijoin", database=InMemoryArrowDatabase())
- with job:
- _ = SemiJoin()(left, empty, label="step")
- node = job.nodes["step"]
- assert isinstance(node, OperatorJobNode)
+ op = SemiJoin()
+ op.validate_inputs(left, empty)
+ node = OperatorJobNode(op, (left, empty))
node.upstreams = (other, empty)
actual = await _execute_node_rows(node, other, empty, run_async=True)
@@ -467,12 +465,11 @@ async def _execute_node_rows(
async def test_rewired_semijoin_warns_once_for_the_same_names(run_async: bool) -> None:
"""Filtering an input keeps the ignored names and does not repeat their warning."""
left, right = left_source(), right_same_tag_other_y()
- job = PipelineJob(name="rewired_warning", database=InMemoryArrowDatabase())
- with pytest.warns(SemiJoinIgnoredColumnWarning) as record, job:
- _ = SemiJoin()(left, right, label="step")
+ op = SemiJoin()
+ with pytest.warns(SemiJoinIgnoredColumnWarning) as record:
+ op.validate_inputs(left, right)
assert_warned_once(list(record), [("y", "data", "data")])
- node = job.nodes["step"]
- assert isinstance(node, OperatorJobNode)
+ node = OperatorJobNode(op, (left, right))
filtered = left.polars_filter(x=10)
assert filtered.pipeline_hash() != left.pipeline_hash()
node.upstreams = (filtered, right)
@@ -488,11 +485,10 @@ async def test_rewired_semijoin_warns_once_for_the_same_names(run_async: bool) -
async def test_rewired_semijoin_new_warning_is_retried(run_async: bool) -> None:
"""A new ignored name warns, including after each failed attempt to warn."""
left, right = left_source(), right_same_tag_other_y()
- job = PipelineJob(name="rewired_new_warning", database=InMemoryArrowDatabase())
- with job:
- _ = SemiJoin()(left, right_tags_only(), label="step")
- node = job.nodes["step"]
- assert isinstance(node, OperatorJobNode)
+ op = SemiJoin()
+ tags_only = right_tags_only()
+ op.validate_inputs(left, tags_only)
+ node = OperatorJobNode(op, (left, tags_only))
filtered = left.polars_filter(x=10)
node.upstreams = (filtered, right)
diff --git a/tests/test_core/sources/test_spiraldb_table_source_where.py b/tests/test_core/sources/test_spiraldb_table_source_where.py
index d6de06ffc..eef44e4d6 100644
--- a/tests/test_core/sources/test_spiraldb_table_source_where.py
+++ b/tests/test_core/sources/test_spiraldb_table_source_where.py
@@ -1182,10 +1182,10 @@ def first(amplitude: float | None) -> float | None:
@pytest.mark.parametrize(
"prebuilt_first", [False, True], ids=["captured first", "prebuilt first"]
)
- def test_a_stream_with_the_hash_of_an_equal_captured_output_is_accepted(
+ def test_a_stream_with_the_hash_of_a_captured_output_is_refused(
self, project, tmp_path, prebuilt_first
):
- """Prebuilt and captured projections can reuse one restricted source."""
+ """Refuse a restricted projection that would shadow a captured step."""
@function_pod(output_keys="a")
def first(amplitude: float | None) -> float | None:
@@ -1200,9 +1200,17 @@ def first(amplitude: float | None) -> float | None:
with job:
if prebuilt_first:
first.pod(outside, label="first")
- events.select_data_columns(["amplitude"])
- if not prebuilt_first:
- first.pod(outside, label="first")
+ with pytest.raises(
+ InconsistentSourceError, match="share a legacy execution identity"
+ ):
+ events.select_data_columns(["amplitude"])
+ else:
+ inside = events.select_data_columns(["amplitude"])
+ with pytest.raises(
+ InconsistentSourceError, match="share a legacy execution identity"
+ ):
+ first.pod(outside, label="first")
+ first.pod(inside, label="first")
job.run()
@@ -1998,13 +2006,11 @@ def test_execute_over_unrestricted_streams_still_caches(
assert len(fake_spiral_sdk.scan_log) == scans
-def _proxy_for(source: SpiralDBTableSource) -> Any:
+def _proxy_for(source: SpiralDBTableSource, *, system_tags: bool = True) -> Any:
"""A ``SourceProxy`` standing in for ``source``'s identity, unbound."""
from orcapod.core.sources.source_proxy import SourceProxy
- # With the system-tag columns, as a slot needs them (a loaded job's proxy has its
- # node's schema).
- tag_schema, data_schema = source.output_schema(columns={"system_tags": True})
+ tag_schema, data_schema = source.output_schema(columns={"system_tags": system_tags})
return SourceProxy(
source_id=source.source_id,
content_hash_str=source.content_hash().to_string(),
@@ -2030,9 +2036,9 @@ class TestRestrictionThroughWrappers:
"""
@staticmethod
- def _bound_proxy(restriction: str) -> Any:
+ def _bound_proxy(restriction: str, *, system_tags: bool = True) -> Any:
restricted = _RESTRICTIONS[restriction](_events())
- proxy = _proxy_for(_events())
+ proxy = _proxy_for(_events(), system_tags=system_tags)
proxy.bind(restricted)
return proxy
@@ -2105,7 +2111,7 @@ def test_the_summary_and_the_walk_see_through_a_proxy(self, project):
def test_a_proxy_and_a_source_restricted_two_ways_are_refused_at_capture(
self, project, tmp_path, order
):
- proxy = self._bound_proxy("a condition") # subject_id='m1'
+ proxy = self._bound_proxy("a condition", system_tags=False)
other = _events().where(subject_id="m2")
first, second = (proxy, other) if order == "proxy first" else (other, proxy)
job = PipelineJob(
diff --git a/tests/test_core/test_order_invariance.py b/tests/test_core/test_order_invariance.py
index f304cf75d..3c670a03c 100644
--- a/tests/test_core/test_order_invariance.py
+++ b/tests/test_core/test_order_invariance.py
@@ -1531,13 +1531,15 @@ def _double_reading(reading: int | None) -> int:
return (reading or 0) * 2
-@pytest.mark.parametrize("first_source", ["a", "step_1"])
+@pytest.mark.parametrize("first_source", ["a", "_double_reading_2"])
def test_explicit_suffixes_remain_addressable_in_every_definition_order(
first_source: str,
) -> None:
- """A generated suffix never shadows a node with its own label."""
- definitions = ((first_source, 1, "step"), ("b", 2, "step"), ("c", 3, "step_1"))
+ """A generated suffix never shadows a slot name or an explicit step label."""
+ explicit = "_double_reading_1"
+ definitions = ((first_source, 1, None), ("b", 2, None), ("c", 3, explicit))
results: dict[str, dict[str, Any]] = {}
+ suffixes = (3, 4) if first_source == "_double_reading_2" else (2, 3)
for order in itertools.permutations(definitions):
job = PipelineJob(name="labels", database=InMemoryArrowDatabase())
with job:
@@ -1545,8 +1547,10 @@ def test_explicit_suffixes_remain_addressable_in_every_definition_order(
source = ListSource("reading", [value], source_id=name)
_ = _double_reading.pod(source, label=label)
summary = job.run()
- assert set(summary.nodes) == {"step_1", "step_2", "step_3"}
- assert job.nodes["step_1"].as_table()["doubled"].to_pylist() == [6]
+ assert set(summary.nodes) == {explicit} | {
+ f"_double_reading_{number}" for number in suffixes
+ }
+ assert job.nodes[explicit].as_table()["doubled"].to_pylist() == [6]
results["".join(name for name, _, _ in order)] = {
"labels": list(job.nodes),
"rows": {
@@ -1561,15 +1565,16 @@ def test_explicit_suffixes_remain_addressable_in_every_definition_order(
def test_identical_invocations_keep_the_smallest_explicit_label(
labels: tuple[str | None, str],
) -> None:
- """Invocations deduplicate whichever label was recorded first."""
+ """Step 3 keeps main's smallest explicit label."""
for order in (labels, labels[::-1]):
source = ListSource("reading", [2], source_id="readings")
job = PipelineJob(name="labels", database=InMemoryArrowDatabase())
with job:
for label in order:
_ = _double_reading.pod(source, label=label)
- assert list(job.nodes) == ["readings", "label_a"]
- assert list(job.run().nodes) == ["label_a"]
+ smallest = min(label for label in order if label is not None)
+ assert list(job.nodes) == ["readings", smallest]
+ assert list(job.run().nodes) == [smallest]
def _restricted_job_run(root: Path, names: Sequence[str]) -> None:
diff --git a/tests/test_core/test_tracker.py b/tests/test_core/test_tracker.py
index 2abd451a1..bc8b723cb 100644
--- a/tests/test_core/test_tracker.py
+++ b/tests/test_core/test_tracker.py
@@ -23,6 +23,7 @@
from orcapod import side_effect_pod
from orcapod.core.function_pod import FunctionPod, function_pod
+from orcapod.core.identity_chains import graph_key
from orcapod.core.nodes import FunctionNode, OperatorNode, SourceNode
from orcapod.core.nodes.source_node import SourceJobNode
from orcapod.core.operators import Join, SelectTagColumns
@@ -590,7 +591,8 @@ def test_record_function_pod_stores_edge(self):
tracker.compile()
assert len(tracker._graph_edges) == 1
upstream_hash, node_hash = tracker._graph_edges[0]
- assert upstream_hash == stream.content_hash().to_string()
+ (source_node,) = tracker.source_pods.values()
+ assert upstream_hash == graph_key(source_node)
assert node_hash in tracker._node_lut
def test_record_function_pod_stores_upstream_stream(self):
@@ -602,17 +604,18 @@ def test_record_function_pod_stores_upstream_stream(self):
with _make_pipeline(tracker_manager=mgr) as tracker:
tracker.record_function_pod_invocation(pod, stream)
- # Raw stream is preserved in _source_streams during/after recording
- stream_hash = stream.content_hash().to_string()
- assert stream_hash in tracker._source_streams
- assert tracker._source_streams[stream_hash] is stream
+ # Recording preserves the raw stream under its named capture key.
+ (capture_key,) = tracker._source_streams
+ assert capture_key in tracker._source_streams
+ assert tracker._source_streams[capture_key] is stream
# After compile(), _upstreams holds a SourceNode wrapper (schema-only)
tracker.compile()
from orcapod.core.nodes.source_node import SourceNode
- assert stream_hash in tracker._upstreams
- assert isinstance(tracker._upstreams[stream_hash], SourceNode)
+ (source_node,) = tracker.source_pods.values()
+ assert isinstance(source_node, SourceNode)
+ assert tracker._upstreams[graph_key(source_node)] is source_node
def test_record_operator_pod_creates_operator_node(self):
stream = _make_stream()
diff --git a/tests/test_databases/test_delta_list_binary_commits.py b/tests/test_databases/test_delta_list_binary_commits.py
index 3c7e9243a..13004339b 100644
--- a/tests/test_databases/test_delta_list_binary_commits.py
+++ b/tests/test_databases/test_delta_list_binary_commits.py
@@ -67,7 +67,8 @@ def _stored_form(table: pa.Table) -> list[tuple[str, str, bool]]:
def _values(job: PipelineJob) -> list[Any]:
return sorted(
- (row.as_dict()["ids"] for _, row in job.nodes["node"].iter_data()), key=repr
+ (row.as_dict()["ids"] for _, row in job.nodes["node"].iter_data()),
+ key=repr,
)
diff --git a/tests/test_databases/test_unstorable_columns.py b/tests/test_databases/test_unstorable_columns.py
index 552ad52d9..8f036b470 100644
--- a/tests/test_databases/test_unstorable_columns.py
+++ b/tests/test_databases/test_unstorable_columns.py
@@ -478,7 +478,10 @@ def test_refused_database_bind_changes_nothing(self, tmp_path: pathlib.Path):
CALLS.clear()
_ = job.run()
assert CALLS == []
- assert sorted(job.nodes["dbl"].as_table()["double"].to_pylist()) == [2, 4]
+ assert sorted(job.nodes["dbl"].as_table()["double"].to_pylist()) == [
+ 2,
+ 4,
+ ]
assert sqlite.list_table_paths() == []
diff --git a/tests/test_hashing/test_identity_chains.py b/tests/test_hashing/test_identity_chains.py
index 1cefe7e45..5a540da13 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
+import json
from collections import Counter
from itertools import permutations
from pathlib import Path
@@ -410,13 +411,13 @@ def test_slots_keep_their_names_across_bindings(reverse: bool, run_async: bool)
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})
+ replacement = _source("reading-three", reverse, shift=200)
+ job.bind(sources={"y_slot": replacement})
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"].content_hash() == job.nodes["y_first"].content_hash()
+ new_content, same_name = _hashes(y_node)
+ assert new_content not in (x_content, y_content)
+ assert same_name == y_name
@pytest.mark.parametrize("reverse", [False, True])
@@ -735,11 +736,16 @@ class UnregisteredJoin(Join):
original = job.nodes["joined"]
path = tmp_path / "job.json"
job.save(path)
+ saved_nodes = json.loads(path.read_text())["pipeline"]["nodes"]
+ (saved_key,) = (
+ key for key, node in saved_nodes.items() if node["label"] == "joined"
+ )
if missing_builtin:
monkeypatch.delitem(OPERATOR_REGISTRY, "Join")
for _ in range(2):
loaded = PipelineJob.load(path, database=job.database)
node = loaded.nodes["joined"]
+ assert loaded._hash_graph.nodes[f"legacy:{saved_key}"]["label"] == node.label
assert node.producer is None
assert node.pipeline_hash() == original.pipeline_hash()
assert node.content_hash() == original.content_hash()
@@ -884,16 +890,16 @@ def structural_argument_symmetry(
return SymmetricGroup(((a, b), (d, c)))
allow_synthetic_symmetry(ReversedPairJoin)
- source = _data_tags("reading")
+ sources = {name: _data_tags(f"reading_{name}") for name in "abcd"}
job = PipelineJob(name="nested_pairs", database=InMemoryArrowDatabase())
with job:
- for name in "abcd":
+ for name, source in sources.items():
_ = SelectDataColumns(["x", "y"])(
SourceNode.from_stream(source, name=name), label=f"out_{name}"
)
- job.bind(dict.fromkeys("abcd", source))
+ job.bind(dict(sources))
a, b, c, d = (cast("StreamProtocol", job.nodes[name]) for name in "abcd")
- assert a == b == c == d
+ assert len({a, b, c, d}) == 4
symmetry = ReversedPairJoin().structural_argument_symmetry((a, b, c, d))
assert isinstance(symmetry, SymmetricGroup) and len(symmetry.members) == 2
return ReversedPairJoin()(a, b, c, d), ReversedPairJoin()(d, c, b, a)
@@ -1188,15 +1194,26 @@ def count_visit(
monkeypatch.setattr(identity_chains, "_hash", count_hash)
monkeypatch.setattr(identity_chains.IdentityWalk, "visit", count_visit)
+ # Capture computes keys from slot declarations. Prime the compiled node's
+ # names separately so this read isolates how the live source chain is pooled.
+ _ = result.node_hash()
+ hashes.clear()
+ visits.clear()
before = _hashes(result)
- assert set(hashes) <= {identity_chains.CONTENT_HASH_LABEL, NODE_HASH_LABEL}
+ assert len({id(element) for element in visits}) == 51
+ assert Counter(hashes) == {
+ SOURCE_CHAIN_HASH_LABEL: 51,
+ identity_chains.CONTENT_HASH_LABEL: 1,
+ }
hashes.clear()
visits.clear()
assert _hashes(result) == before
assert hashes == []
assert visits == [result, result]
- visits.clear()
job.bind(sources={"reading": _source("rebound", False)})
+ # Binding validates prospective nodes separately from this live identity read.
+ hashes.clear()
+ visits.clear()
after = _hashes(result)
assert after[0] != before[0]
assert after[1] == before[1]
@@ -1553,7 +1570,9 @@ def test_name_entry_memo_respects_semantic_types_after_rebind(
term = 1
job.bind({"reading": _source("rebound", False)})
expected = _chain(
- NAME_CHAIN_HASH_LABEL, ("test", term), job.nodes["reading"].name_chain()
+ NAME_CHAIN_HASH_LABEL,
+ ("test", term),
+ job.nodes["reading"].name_chain(),
)
assert first != expected
assert result.name_chain() == expected
@@ -1679,18 +1698,16 @@ def test_capture_distinguishes_joins_by_multiplicity(
)
-def test_capture_keys_follow_a_rewired_join() -> None:
- """A key memo must pick up a changed repeat count through a held stream."""
+def test_identity_follows_a_rewired_join() -> None:
+ """Rewiring an operator changes its cached structural and name identities."""
from orcapod.core.nodes.operator_node import OperatorNode
a, b = _data_tags("a"), _data_tags("b")
stream = OperatorNode(Join(), (a, b), label="external")
- graph = Pipeline("rewired")
- with graph:
- _ = stream.select_tag_columns(["region", "item"], label="original")
- stream.upstreams = (a, b, b)
- _ = stream.select_tag_columns(["region", "item"], label="rewired")
- assert {"original", "rewired"} <= set(graph.nodes)
+ before = stream.pipeline_hash(), stream.node_hash()
+ stream.upstreams = (a, b, b)
+ assert stream.pipeline_hash() != before[0]
+ assert stream.node_hash() != before[1]
@pytest.mark.parametrize("reverse", [False, True])
diff --git a/tests/test_hashing/test_logical_type_forms.py b/tests/test_hashing/test_logical_type_forms.py
index c35ad1db5..561c5515c 100644
--- a/tests/test_hashing/test_logical_type_forms.py
+++ b/tests/test_hashing/test_logical_type_forms.py
@@ -767,11 +767,12 @@ def test_a_saved_slot_loads_and_binds(
assert typed_arrow_schemas(loaded_slot) == typed_arrow_schemas(source)
for tags_or_data in typed_arrow_schemas(loaded_slot):
assert tags_or_data.empty_table().num_rows == 0, label
- # The loaded slot itself binds the source and runs.
- job = PipelineJob(name="nested", database=InMemoryArrowDatabase())
- with job:
- MapData({"x": "z"})(loaded_slot, label="renamed")
- job.bind(sources={"src": self._stream(table)})
+ # The operator-only blueprint can instantiate its own bound job slot.
+ job = PipelineJob.from_pipeline(
+ loaded,
+ database=InMemoryArrowDatabase(),
+ sources={"src": self._stream(table)},
+ )
job.run()
assert job.nodes["renamed"].as_table().num_rows == 2, label
diff --git a/tests/test_hashing/test_schema_hash_storage_form.py b/tests/test_hashing/test_schema_hash_storage_form.py
index efa1fe6c7..3eb64f1f6 100644
--- a/tests/test_hashing/test_schema_hash_storage_form.py
+++ b/tests/test_hashing/test_schema_hash_storage_form.py
@@ -882,8 +882,8 @@ def test_a_job_has_one_identity_bound_run_saved_and_loaded(
"""Every slot form, sync and async, before and after a save and load."""
table = _table(kind, tmp_path / "values")
seen: dict[tuple[str, str], tuple[Any, ...]] = {}
- for label, slot in self._slots(kind, tmp_path).items():
- for path in ("sync", "async"):
+ for path in ("sync", "async"):
+ for label, slot in self._slots(kind, tmp_path).items():
root = tmp_path / _safe(label) / path
database = DeltaTableDatabase(root / "db")
job = PipelineJob(name="forms", database=database)
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/01.json b/tests/test_pipeline/fixtures/itl_1559_capture/01.json
new file mode 100644
index 000000000..4f979eae9
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/01.json
@@ -0,0 +1,228 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p": "content_hash_v1:f6b6c60d781657ad2c98d5e1eb7d8522624a8b6c218d58c6546640d2388ec3e9"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc": {
+ "node_type": "function",
+ "label": "p",
+ "content_hash": "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc",
+ "pipeline_hash": "semantic_v1:a5150e9d49abbbd7e9ea55c7e21eeba1ddf2c8682cffe89af5d993402e789def",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc"
+ ],
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/01.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/01.listings.json
new file mode 100644
index 000000000..1a62ef347
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/01.listings.json
@@ -0,0 +1,47 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d"
+ ]
+ ],
+ "d": [
+ [
+ "a"
+ ],
+ [
+ "p"
+ ]
+ ],
+ "p": [
+ [
+ "d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d",
+ "p"
+ ],
+ "edges": [
+ [
+ "a",
+ "d"
+ ],
+ [
+ "d",
+ "p"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d",
+ "p"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/02.json b/tests/test_pipeline/fixtures/itl_1559_capture/02.json
new file mode 100644
index 000000000..4f979eae9
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/02.json
@@ -0,0 +1,228 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p": "content_hash_v1:f6b6c60d781657ad2c98d5e1eb7d8522624a8b6c218d58c6546640d2388ec3e9"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc": {
+ "node_type": "function",
+ "label": "p",
+ "content_hash": "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc",
+ "pipeline_hash": "semantic_v1:a5150e9d49abbbd7e9ea55c7e21eeba1ddf2c8682cffe89af5d993402e789def",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "node_hash_v1:92cb8fe1f32af45ec96755d075498083a090aeeba7dda06937025714dff652bc"
+ ],
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/02.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/02.listings.json
new file mode 100644
index 000000000..1a62ef347
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/02.listings.json
@@ -0,0 +1,47 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d"
+ ]
+ ],
+ "d": [
+ [
+ "a"
+ ],
+ [
+ "p"
+ ]
+ ],
+ "p": [
+ [
+ "d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d",
+ "p"
+ ],
+ "edges": [
+ [
+ "a",
+ "d"
+ ],
+ [
+ "d",
+ "p"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d",
+ "p"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/03.json b/tests/test_pipeline/fixtures/itl_1559_capture/03.json
new file mode 100644
index 000000000..a44655274
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/03.json
@@ -0,0 +1,162 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/03.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/03.listings.json
new file mode 100644
index 000000000..6f8e4d770
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/03.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d"
+ ]
+ ],
+ "d": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d"
+ ],
+ "edges": [
+ [
+ "a",
+ "d"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/04.json b/tests/test_pipeline/fixtures/itl_1559_capture/04.json
new file mode 100644
index 000000000..07307ed38
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/04.json
@@ -0,0 +1,162 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d1": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d1",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/04.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/04.listings.json
new file mode 100644
index 000000000..845c585ba
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/04.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d1"
+ ]
+ ],
+ "d1": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d1"
+ ],
+ "edges": [
+ [
+ "a",
+ "d1"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d1"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/05.json b/tests/test_pipeline/fixtures/itl_1559_capture/05.json
new file mode 100644
index 000000000..98040449e
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/05.json
@@ -0,0 +1,228 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "t": "content_hash_v1:f014602f68253d9531c81a896d34ba8d5293d7f62ab4f603e075c7ee2bb27331"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce": {
+ "node_type": "function",
+ "label": "t",
+ "content_hash": "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce",
+ "pipeline_hash": "semantic_v1:bb10ba62f2d80dbe9d36382f27882d0ceff948c4be9d76ed41a4ba084740f2e5",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "tripled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "triple",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "tripled": ""
+ },
+ "output_keys": [
+ "tripled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ],
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/05.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/05.listings.json
new file mode 100644
index 000000000..66483edf0
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/05.listings.json
@@ -0,0 +1,46 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d",
+ "t"
+ ]
+ ],
+ "d": [
+ [
+ "a"
+ ],
+ []
+ ],
+ "t": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d",
+ "t"
+ ],
+ "edges": [
+ [
+ "a",
+ "d"
+ ],
+ [
+ "a",
+ "t"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d",
+ "t"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/10.json b/tests/test_pipeline/fixtures/itl_1559_capture/10.json
new file mode 100644
index 000000000..741e10859
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/10.json
@@ -0,0 +1,142 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "p": "content_hash_v1:cfa6a046aaa47c801089493961dc731e0056066436922bec6d75a87e1183db84"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3": {
+ "node_type": "source",
+ "label": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f": {
+ "node_type": "function",
+ "label": "p",
+ "content_hash": "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/10.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/10.listings.json
new file mode 100644
index 000000000..96374de01
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/10.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": [
+ [],
+ [
+ "p"
+ ]
+ ],
+ "p": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ],
+ "edges": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ]
+ ],
+ "labels": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ],
+ "source_pods": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/11.json b/tests/test_pipeline/fixtures/itl_1559_capture/11.json
new file mode 100644
index 000000000..8b4488ca3
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/11.json
@@ -0,0 +1,142 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "p1": "content_hash_v1:cfa6a046aaa47c801089493961dc731e0056066436922bec6d75a87e1183db84"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3": {
+ "node_type": "source",
+ "label": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f": {
+ "node_type": "function",
+ "label": "p1",
+ "content_hash": "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/11.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/11.listings.json
new file mode 100644
index 000000000..7b16ba02d
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/11.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": [
+ [],
+ [
+ "p1"
+ ]
+ ],
+ "p1": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p1"
+ ],
+ "edges": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p1"
+ ]
+ ],
+ "labels": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p1"
+ ],
+ "source_pods": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/13.json b/tests/test_pipeline/fixtures/itl_1559_capture/13.json
new file mode 100644
index 000000000..e85fd28ff
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/13.json
@@ -0,0 +1,250 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "p1": "content_hash_v1:cfa6a046aaa47c801089493961dc731e0056066436922bec6d75a87e1183db84",
+ "p2": "content_hash_v1:b600d4aa445115f3b1890bb175edfb964a63fc4b6836475a813406bc2e976f01"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3": {
+ "node_type": "source",
+ "label": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:03e2dedbaecb5febac126cc5ade4fe8545406f65d8e8a4910c0adfaa8fd57262": {
+ "node_type": "source",
+ "label": "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd",
+ "content_hash": "node_hash_v1:03e2dedbaecb5febac126cc5ade4fe8545406f65d8e8a4910c0adfaa8fd57262",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f": {
+ "node_type": "function",
+ "label": "p1",
+ "content_hash": "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:751fc57332b4dfb4fe4cff4802a62fb2826bdb8acf658db9fd85f57674632299": {
+ "node_type": "function",
+ "label": "p2",
+ "content_hash": "node_hash_v1:751fc57332b4dfb4fe4cff4802a62fb2826bdb8acf658db9fd85f57674632299",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:03e2dedbaecb5febac126cc5ade4fe8545406f65d8e8a4910c0adfaa8fd57262",
+ "node_hash_v1:751fc57332b4dfb4fe4cff4802a62fb2826bdb8acf658db9fd85f57674632299"
+ ],
+ [
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "source_type": "unknown"
+ },
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/13.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/13.listings.json
new file mode 100644
index 000000000..7ae3c7d5a
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/13.listings.json
@@ -0,0 +1,54 @@
+{
+ "adjacency": {
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": [
+ [],
+ [
+ "p1"
+ ]
+ ],
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd": [
+ [],
+ [
+ "p2"
+ ]
+ ],
+ "p1": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ []
+ ],
+ "p2": [
+ [
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd",
+ "p1",
+ "p2"
+ ],
+ "edges": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p1"
+ ],
+ [
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd",
+ "p2"
+ ]
+ ],
+ "labels": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd",
+ "p1",
+ "p2"
+ ],
+ "source_pods": [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "double:e0516ed5597cb6662b1637511b916695afb23b4622529c1ff892e3b67783e7bd"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/14.json b/tests/test_pipeline/fixtures/itl_1559_capture/14.json
new file mode 100644
index 000000000..945678a85
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/14.json
@@ -0,0 +1,270 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "t": "content_hash_v1:f014602f68253d9531c81a896d34ba8d5293d7f62ab4f603e075c7ee2bb27331",
+ "p": "content_hash_v1:cfa6a046aaa47c801089493961dc731e0056066436922bec6d75a87e1183db84"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3": {
+ "node_type": "source",
+ "label": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce": {
+ "node_type": "function",
+ "label": "t",
+ "content_hash": "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce",
+ "pipeline_hash": "semantic_v1:bb10ba62f2d80dbe9d36382f27882d0ceff948c4be9d76ed41a4ba084740f2e5",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "tripled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "triple",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "tripled": ""
+ },
+ "output_keys": [
+ "tripled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f": {
+ "node_type": "function",
+ "label": "p",
+ "content_hash": "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:70fdb8d188f5eca7572e2ba2d8a3c14e423f50b43da7fb0f13fe6e37263e3bc3",
+ "node_hash_v1:ad82425d55db03e40b6ac42ab2459c571dd84098daeaede32ab9aac876d89c9f"
+ ],
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:aff06e6423fc60a5c22e60f2f0d2e1ba0fa56a049b4f327935253865fa3400ce"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/14.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/14.listings.json
new file mode 100644
index 000000000..7fa3e2038
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/14.listings.json
@@ -0,0 +1,54 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "t"
+ ]
+ ],
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": [
+ [],
+ [
+ "p"
+ ]
+ ],
+ "p": [
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ []
+ ],
+ "t": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p",
+ "t"
+ ],
+ "edges": [
+ [
+ "a",
+ "t"
+ ],
+ [
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ]
+ ],
+ "labels": [
+ "a",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p",
+ "t"
+ ],
+ "source_pods": [
+ "a",
+ "double:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/17.json b/tests/test_pipeline/fixtures/itl_1559_capture/17.json
new file mode 100644
index 000000000..9663126ec
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/17.json
@@ -0,0 +1,142 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:f3bbe273d9603d29ae4954a5e814b40488f5cef370e8c54606b1207313206f25"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:feba1f4c1d16539779a13646344587c4f21be6c68a4de49f5f07310e224dbc32": {
+ "node_type": "source",
+ "label": "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b",
+ "content_hash": "node_hash_v1:feba1f4c1d16539779a13646344587c4f21be6c68a4de49f5f07310e224dbc32",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:ee6238b9842149a0a7dc93a478833025fc6ede25b8648df1ed8d1bfb7d24e47e": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:ee6238b9842149a0a7dc93a478833025fc6ede25b8648df1ed8d1bfb7d24e47e",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:feba1f4c1d16539779a13646344587c4f21be6c68a4de49f5f07310e224dbc32",
+ "node_hash_v1:ee6238b9842149a0a7dc93a478833025fc6ede25b8648df1ed8d1bfb7d24e47e"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/17.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/17.listings.json
new file mode 100644
index 000000000..688aa6564
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/17.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b": [
+ [],
+ [
+ "d"
+ ]
+ ],
+ "d": [
+ [
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b",
+ "d"
+ ],
+ "edges": [
+ [
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b",
+ "d"
+ ]
+ ],
+ "labels": [
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b",
+ "d"
+ ],
+ "source_pods": [
+ "ArrowTableStream:aab359adba4433b4364aede005addcbd6955e7dfc267e7dd9a43bdb935d9833b"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.json b/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.json
new file mode 100644
index 000000000..a759bf1dc
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.json
@@ -0,0 +1,221 @@
+{
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "p"
+ ]
+ },
+ "nodes": {
+ "content_hash_v1:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d": {
+ "node_type": "source",
+ "label": "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "content_hash": "content_hash_v1:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "content_hash_v1:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee": {
+ "node_type": "source",
+ "label": "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "content_hash": "content_hash_v1:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "content_hash_v1:00515ffeb3aad710a1a9a3bba430ee985c03ec89079219d17612fe041a299a50": {
+ "node_type": "function",
+ "label": "d1",
+ "content_hash": "content_hash_v1:00515ffeb3aad710a1a9a3bba430ee985c03ec89079219d17612fe041a299a50",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "content_hash_v1:ad988d55dea720996903cb533e91489d3a17319a3f8476edda73f7260ce7838f": {
+ "node_type": "function",
+ "label": "d2",
+ "content_hash": "content_hash_v1:ad988d55dea720996903cb533e91489d3a17319a3f8476edda73f7260ce7838f",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "content_hash_v1:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "content_hash_v1:ad988d55dea720996903cb533e91489d3a17319a3f8476edda73f7260ce7838f"
+ ],
+ [
+ "content_hash_v1:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "content_hash_v1:00515ffeb3aad710a1a9a3bba430ee985c03ec89079219d17612fe041a299a50"
+ ]
+ ]
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.listings.json
new file mode 100644
index 000000000..3606427fb
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/18-blueprint.listings.json
@@ -0,0 +1,54 @@
+{
+ "adjacency": {
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d": [
+ [],
+ [
+ "d2"
+ ]
+ ],
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee": [
+ [],
+ [
+ "d1"
+ ]
+ ],
+ "d1": [
+ [
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee"
+ ],
+ []
+ ],
+ "d2": [
+ [
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "d1",
+ "d2"
+ ],
+ "edges": [
+ [
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "d2"
+ ],
+ [
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "d1"
+ ]
+ ],
+ "labels": [
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee",
+ "d1",
+ "d2"
+ ],
+ "source_pods": [
+ "ArrowTableStream:8e0fe3d4db3fca4751876bed8cc463fd4909a759006ae03f606ba7ad4dd57b5d",
+ "ArrowTableStream:d3fa04d76061b1b428d5d900a3ee234141916a5c7d6aff2ee0f6b69e0966a1ee"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/18-job.json b/tests/test_pipeline/fixtures/itl_1559_capture/18-job.json
new file mode 100644
index 000000000..954383375
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/18-job.json
@@ -0,0 +1,250 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d1": "content_hash_v1:40ab2683cfbd9218e865178201dcb858a37fe327c09fd85ea8851c10a1bb4933",
+ "d2": "content_hash_v1:3f3bae9549aca5427ef55fcac324d241a104c587e6b10e2b7253f6102e0deb27"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:e070f24ad4798121dc0abff686d6ee51abc8e1c1bc4b62368aa450d9b5135cc9": {
+ "node_type": "source",
+ "label": "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "content_hash": "node_hash_v1:e070f24ad4798121dc0abff686d6ee51abc8e1c1bc4b62368aa450d9b5135cc9",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:bdb164b023a995a548f81f3f53fd1714c498cc3ffdc692dde8387a6b11a19425": {
+ "node_type": "source",
+ "label": "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87",
+ "content_hash": "node_hash_v1:bdb164b023a995a548f81f3f53fd1714c498cc3ffdc692dde8387a6b11a19425",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:81c7d53b759756a687b79806022d7501b758dd36cf0092abb6767ed8c20042d8": {
+ "node_type": "function",
+ "label": "d1",
+ "content_hash": "node_hash_v1:81c7d53b759756a687b79806022d7501b758dd36cf0092abb6767ed8c20042d8",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:c30e194b3550b18ad569537e52e4c1f5bf133bf7390a3500c673152a9b6f64b9": {
+ "node_type": "function",
+ "label": "d2",
+ "content_hash": "node_hash_v1:c30e194b3550b18ad569537e52e4c1f5bf133bf7390a3500c673152a9b6f64b9",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:bdb164b023a995a548f81f3f53fd1714c498cc3ffdc692dde8387a6b11a19425",
+ "node_hash_v1:c30e194b3550b18ad569537e52e4c1f5bf133bf7390a3500c673152a9b6f64b9"
+ ],
+ [
+ "node_hash_v1:e070f24ad4798121dc0abff686d6ee51abc8e1c1bc4b62368aa450d9b5135cc9",
+ "node_hash_v1:81c7d53b759756a687b79806022d7501b758dd36cf0092abb6767ed8c20042d8"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d": {
+ "source_type": "unknown"
+ },
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87": {
+ "source_type": "unknown"
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/18-job.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/18-job.listings.json
new file mode 100644
index 000000000..76cf99360
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/18-job.listings.json
@@ -0,0 +1,54 @@
+{
+ "adjacency": {
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d": [
+ [],
+ [
+ "d1"
+ ]
+ ],
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87": [
+ [],
+ [
+ "d2"
+ ]
+ ],
+ "d1": [
+ [
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d"
+ ],
+ []
+ ],
+ "d2": [
+ [
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87",
+ "d1",
+ "d2"
+ ],
+ "edges": [
+ [
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "d1"
+ ],
+ [
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87",
+ "d2"
+ ]
+ ],
+ "labels": [
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87",
+ "d1",
+ "d2"
+ ],
+ "source_pods": [
+ "ArrowTableStream:ceaeb081da1e09dc546b2ae166441b96f24bb49455027ab9f0ca8347901bbd3d",
+ "ArrowTableStream:d431671c584652b34169b42d0b5a46e277a6c89d84539205c2603c838c6afa87"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/29.json b/tests/test_pipeline/fixtures/itl_1559_capture/29.json
new file mode 100644
index 000000000..533949186
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/29.json
@@ -0,0 +1,160 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "p": "content_hash_v1:b88e9021205e546d7fa3792878ee3c2e3310d6e5c7e27a821c8612857330bf65"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:023e2b1f549d78b2ec0d8981a0b97c64ce40ca10c4dc01e2a41961d0b118f740": {
+ "node_type": "source",
+ "label": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "node_hash_v1:023e2b1f549d78b2ec0d8981a0b97c64ce40ca10c4dc01e2a41961d0b118f740",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:290f934cad97faa08f37bd3f52cf504e0b24802262e33cba9a5a302ac22c0d91": {
+ "node_type": "function",
+ "label": "p",
+ "content_hash": "node_hash_v1:290f934cad97faa08f37bd3f52cf504e0b24802262e33cba9a5a302ac22c0d91",
+ "pipeline_hash": "semantic_v1:d7e01a4bb8c79bea25653e1ba804a693c1945257cf8bf39214901e883413f464",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "plus": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "plus",
+ "768789a29a3d95a24e13295ed9c62f7a3c079cf5c281b2518afdb2cfe0d960b7",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "plus",
+ "version": "v0.0",
+ "input_data_schema": {
+ "doubled": ""
+ },
+ "output_data_schema": {
+ "plus": ""
+ },
+ "output_keys": [
+ "plus"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:023e2b1f549d78b2ec0d8981a0b97c64ce40ca10c4dc01e2a41961d0b118f740",
+ "node_hash_v1:290f934cad97faa08f37bd3f52cf504e0b24802262e33cba9a5a302ac22c0d91"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "source_type": "derived",
+ "tags_as_data": null,
+ "record_id_columns": null,
+ "source_name": null,
+ "source_name_given": false,
+ "source_version": 1,
+ "full_source_id": "derived_v1:content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "content_hash": "semantic_v1:dde9ea170765573a9f0a7d0c80f1ff15372266cca09e29147c66d8afda8e044b",
+ "pipeline_hash": "semantic_v1:43bcb03c8074d4a8a705659562a951d7770a37034bc7b0ba5a3a0483cfed42db",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "doubled": "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_pipeline/fixtures/itl_1559_capture/29.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/29.listings.json
new file mode 100644
index 000000000..d0ec6c973
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/29.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": [
+ [],
+ [
+ "p"
+ ]
+ ],
+ "p": [
+ [
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ],
+ "edges": [
+ [
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ]
+ ],
+ "labels": [
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "p"
+ ],
+ "source_pods": [
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/32.json b/tests/test_pipeline/fixtures/itl_1559_capture/32.json
new file mode 100644
index 000000000..bda3ba6be
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/32.json
@@ -0,0 +1,175 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "d": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "cached",
+ "inner_source": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "cache_database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "cache_path_prefix": [],
+ "cache_path": [
+ "source",
+ "node:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06"
+ ]
+ }
+ },
+ "database": {
+ "type": "in_memory",
+ "base_path": [],
+ "max_hierarchy_depth": 10
+ },
+ "result_database": null
+ }
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/32.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/32.listings.json
new file mode 100644
index 000000000..6f8e4d770
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/32.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "d"
+ ]
+ ],
+ "d": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "d"
+ ],
+ "edges": [
+ [
+ "a",
+ "d"
+ ]
+ ],
+ "labels": [
+ "a",
+ "d"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/34.json b/tests/test_pipeline/fixtures/itl_1559_capture/34.json
new file mode 100644
index 000000000..1cbb2a243
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/34.json
@@ -0,0 +1,182 @@
+{
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "p"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:ce7293c3a49023394ff310314fb540886bb8f8eafb01eec32b1a9f2936bed0de": {
+ "node_type": "source",
+ "label": "x",
+ "content_hash": "node_hash_v1:ce7293c3a49023394ff310314fb540886bb8f8eafb01eec32b1a9f2936bed0de",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "x"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "x",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:f58aedadaf48140ce2d72faff20e22b7862a2264a1caffb960798e6908d1987a": {
+ "node_type": "function",
+ "label": "d",
+ "content_hash": "node_hash_v1:f58aedadaf48140ce2d72faff20e22b7862a2264a1caffb960798e6908d1987a",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ },
+ "node_hash_v1:00025577626231a33218aff7440e835648ed2b1d48613cfce16f97d59a85cb8d": {
+ "node_type": "function",
+ "label": "t",
+ "content_hash": "node_hash_v1:00025577626231a33218aff7440e835648ed2b1d48613cfce16f97d59a85cb8d",
+ "pipeline_hash": "semantic_v1:bb10ba62f2d80dbe9d36382f27882d0ceff948c4be9d76ed41a4ba084740f2e5",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "tripled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "triple",
+ "26c5b4f8dba9c129958188b3ce9866ab893778107af663614edef70d99bda9ce",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "triple",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "tripled": ""
+ },
+ "output_keys": [
+ "tripled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:ce7293c3a49023394ff310314fb540886bb8f8eafb01eec32b1a9f2936bed0de",
+ "node_hash_v1:00025577626231a33218aff7440e835648ed2b1d48613cfce16f97d59a85cb8d"
+ ],
+ [
+ "node_hash_v1:ce7293c3a49023394ff310314fb540886bb8f8eafb01eec32b1a9f2936bed0de",
+ "node_hash_v1:f58aedadaf48140ce2d72faff20e22b7862a2264a1caffb960798e6908d1987a"
+ ]
+ ]
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/34.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/34.listings.json
new file mode 100644
index 000000000..f848453b7
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/34.listings.json
@@ -0,0 +1,46 @@
+{
+ "adjacency": {
+ "d": [
+ [
+ "x"
+ ],
+ []
+ ],
+ "t": [
+ [
+ "x"
+ ],
+ []
+ ],
+ "x": [
+ [],
+ [
+ "d",
+ "t"
+ ]
+ ]
+ },
+ "dag_nodes": [
+ "d",
+ "t",
+ "x"
+ ],
+ "edges": [
+ [
+ "x",
+ "d"
+ ],
+ [
+ "x",
+ "t"
+ ]
+ ],
+ "labels": [
+ "d",
+ "t",
+ "x"
+ ],
+ "source_pods": [
+ "x"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/39.json b/tests/test_pipeline/fixtures/itl_1559_capture/39.json
new file mode 100644
index 000000000..efa4c2bb9
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/39.json
@@ -0,0 +1,117 @@
+{
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "p"
+ ]
+ },
+ "nodes": {
+ "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06": {
+ "node_type": "source",
+ "label": "a_1",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d": {
+ "node_type": "function",
+ "label": "a",
+ "content_hash": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ ]
+ ]
+}
\ No newline at end of file
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/39.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/39.listings.json
new file mode 100644
index 000000000..038a82521
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/39.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [
+ "a_1"
+ ],
+ []
+ ],
+ "a_1": [
+ [],
+ [
+ "a"
+ ]
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "a_1"
+ ],
+ "edges": [
+ [
+ "a_1",
+ "a"
+ ]
+ ],
+ "labels": [
+ "a",
+ "a_1"
+ ],
+ "source_pods": [
+ "a_1"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/40.json b/tests/test_pipeline/fixtures/itl_1559_capture/40.json
new file mode 100644
index 000000000..106580511
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/40.json
@@ -0,0 +1,135 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "joined": "content_hash_v1:ba4a21beffd0c8dabebe0539e860b7a69384c6dff040fc047ee5f313e6b26d2d"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:23967682b53d285b51783e77b5470979c8995883b60b8ff99371c3b0fec5ec8e": {
+ "node_type": "operator",
+ "label": "joined",
+ "content_hash": "node_hash_v1:23967682b53d285b51783e77b5470979c8995883b60b8ff99371c3b0fec5ec8e",
+ "pipeline_hash": "semantic_v1:71aebb377ecd458be3c23a73ea8a1f2592a99dfb9683779336532d3ea6f64f61",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "large_list"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "MergeJoin",
+ "cc4a3c03deacdd328626d12e95ace2f5d8a27ca8f6180a22872addf92cf46627"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "inputs": [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16"
+ ],
+ "operator_config": {
+ "class_name": "MergeJoin",
+ "module_path": "orcapod.core.operators.merge_join",
+ "config": {}
+ },
+ "table_scope": "pipeline_hash"
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:23967682b53d285b51783e77b5470979c8995883b60b8ff99371c3b0fec5ec8e"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/40.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/40.listings.json
new file mode 100644
index 000000000..4fb222864
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/40.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "joined"
+ ]
+ ],
+ "joined": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "joined"
+ ],
+ "edges": [
+ [
+ "a",
+ "joined"
+ ]
+ ],
+ "labels": [
+ "a",
+ "joined"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/fixtures/itl_1559_capture/41.json b/tests/test_pipeline/fixtures/itl_1559_capture/41.json
new file mode 100644
index 000000000..f8bc6e562
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/41.json
@@ -0,0 +1,162 @@
+{
+ "orcapod_pipeline_job_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "run": {
+ "run_id": null,
+ "status": "pending",
+ "unbound_sources": [],
+ "node_job_content_hashes": {
+ "r1": "content_hash_v1:9c688e7b2050ad0a8e14ea19c828666be9c15f6669ae86e5ef5df13e7408276d"
+ }
+ },
+ "pipeline": {
+ "orcapod_pipeline_version": "0.4.0",
+ "orcapod_version": "0.4.0",
+ "pipeline": {
+ "name": [
+ "j"
+ ]
+ },
+ "nodes": {
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16": {
+ "node_type": "source",
+ "label": "a",
+ "content_hash": "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "source_node",
+ "a"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "source_config": {
+ "source_type": "node",
+ "name": "a",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "reconstructable": true
+ },
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31": {
+ "node_type": "function",
+ "label": "r1",
+ "content_hash": "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31",
+ "pipeline_hash": "semantic_v1:3f38efb79eae73777a4311d6e45034306ca4f746993e94463842e387535c5a89",
+ "output_schema": {
+ "tag": {
+ "id": "int64"
+ },
+ "data": {
+ "doubled": "int64"
+ },
+ "nullable": {
+ "tag": [],
+ "data": []
+ }
+ },
+ "node_uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_context_key": "std:v1:default",
+ "config": null,
+ "function_config": {
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "data_function": {
+ "data_function_type_id": "python.function.v1",
+ "uri": [
+ "double",
+ "ba1e0a0db33c4ca8ffd67ba2b02ce05a00f0fd5b9d16ab8153cc540fd67e55be",
+ "v0",
+ "python.function.v1"
+ ],
+ "config": {
+ "module_path": "tests.test_pipeline.test_capture_boundary",
+ "callable_name": "double",
+ "version": "v0.0",
+ "input_data_schema": {
+ "x": ""
+ },
+ "output_data_schema": {
+ "doubled": ""
+ },
+ "output_keys": [
+ "doubled"
+ ]
+ }
+ },
+ "pod_config": null,
+ "ctx_arg_name": null
+ },
+ "table_scope": "pipeline_hash",
+ "fall_through_tags": []
+ }
+ },
+ "edges": [
+ [
+ "node_hash_v1:f6670297e16eb187ef9ec9e5b94d4c68b6c4d4fad99f8cc58030398384811f16",
+ "node_hash_v1:4c2443bb40b15db0579e4b5adde4f8e790da8ca93eac62ae8a59c4cd3000ce31"
+ ]
+ ]
+ },
+ "bindings": {
+ "sources": {
+ "a": {
+ "source_type": "dict",
+ "tag_columns": [
+ "id"
+ ],
+ "tag_only_columns": true,
+ "source_name": "a",
+ "source_name_given": true,
+ "source_version": 1,
+ "full_source_id": "dict_v1:a",
+ "content_hash": "semantic_v1:d6645922d3eabe76dad679f19ebd7eaf710833654d1dfcc7b626eae517a5df06",
+ "pipeline_hash": "semantic_v1:bd8fa9c8d8b1336fff848b879c81bbb559fad9d675b0dcc620d2cefa17e1da15",
+ "tag_schema": {
+ "id": "int64"
+ },
+ "data_schema": {
+ "x": "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_pipeline/fixtures/itl_1559_capture/41.listings.json b/tests/test_pipeline/fixtures/itl_1559_capture/41.listings.json
new file mode 100644
index 000000000..77b1b45c4
--- /dev/null
+++ b/tests/test_pipeline/fixtures/itl_1559_capture/41.listings.json
@@ -0,0 +1,33 @@
+{
+ "adjacency": {
+ "a": [
+ [],
+ [
+ "r1"
+ ]
+ ],
+ "r1": [
+ [
+ "a"
+ ],
+ []
+ ]
+ },
+ "dag_nodes": [
+ "a",
+ "r1"
+ ],
+ "edges": [
+ [
+ "a",
+ "r1"
+ ]
+ ],
+ "labels": [
+ "a",
+ "r1"
+ ],
+ "source_pods": [
+ "a"
+ ]
+}
diff --git a/tests/test_pipeline/loaded_job/test_loaded_side_effect_nodes.py b/tests/test_pipeline/loaded_job/test_loaded_side_effect_nodes.py
index a6bba0ab2..65f8b8371 100644
--- a/tests/test_pipeline/loaded_job/test_loaded_side_effect_nodes.py
+++ b/tests/test_pipeline/loaded_job/test_loaded_side_effect_nodes.py
@@ -227,7 +227,12 @@ def test_saving_a_loaded_job_keeps_its_side_effect_nodes(
assert second["nodes"][key] == descriptor
assert set(second["nodes"]) == set(first["nodes"])
assert sorted(map(tuple, second["edges"])) == sorted(map(tuple, first["edges"]))
- assert set(PipelineJob.load(again).nodes) == {"s", "delivered", "down", "tail"}
+ assert set(PipelineJob.load(again).nodes) == {
+ "s",
+ "delivered",
+ "down",
+ "tail",
+ }
def test_pipeline_load_restores_side_effect_nodes(
diff --git a/tests/test_pipeline/loaded_job/test_saved_credentials.py b/tests/test_pipeline/loaded_job/test_saved_credentials.py
index b3a3a0bc0..f2ba1bbfd 100644
--- a/tests/test_pipeline/loaded_job/test_saved_credentials.py
+++ b/tests/test_pipeline/loaded_job/test_saved_credentials.py
@@ -1039,20 +1039,8 @@ def test_password_removal_preserves_source_object_consistency(
assert first.content_hash() == second.content_hash()
with pytest.raises(InconsistentSourceError, match="distinct source objects"):
job.bind(sources={a: first, b: second})
-
- job.bind(sources={a: first, b: first})
- job.save(path)
- loaded = PipelineJob.load(path)
- assert loaded.sources[a] is loaded.sources[b]
-
- # Older files that explicitly recorded different credentials still take
- # separate rebuild paths and are subject to the normal consistency check.
- legacy = json.loads(path.read_text())
- legacy["bindings"]["sources"][a]["dsn"] = _dsn()
- legacy["bindings"]["sources"][b]["dsn"] = _dsn("other-password")
- _ = path.write_text(json.dumps(legacy))
- with pytest.raises(InconsistentSourceError, match="distinct source objects"):
- _ = PipelineJob.load(path)
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ job.bind(sources={a: first, b: first})
second = PostgreSQLTableSource(
_dsn("other-password"),
@@ -1066,3 +1054,19 @@ def test_password_removal_preserves_source_object_consistency(
assert loaded.sources[a] is not loaded.sources[b]
assert loaded.sources[a].content_hash() == first.content_hash()
assert loaded.sources[b].content_hash() == second.content_hash()
+
+ # Repeated saved configs rebuild one object and hit step 3's binding check.
+ legacy = json.loads(path.read_text())
+ configs = legacy["bindings"]["sources"]
+ configs[b] = dict(configs[a])
+ _ = path.write_text(json.dumps(legacy))
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ _ = PipelineJob.load(path)
+
+ # Legacy configs with different credentials rebuild distinct objects with
+ # one content identity and hit the existing source-consistency check.
+ configs[a]["dsn"] = _dsn()
+ configs[b]["dsn"] = _dsn("other-password")
+ _ = path.write_text(json.dumps(legacy))
+ with pytest.raises(InconsistentSourceError, match="distinct source objects"):
+ _ = PipelineJob.load(path)
diff --git a/tests/test_pipeline/test_bind_narrower_source.py b/tests/test_pipeline/test_bind_narrower_source.py
index 14bc4c427..9cb36fc45 100644
--- a/tests/test_pipeline/test_bind_narrower_source.py
+++ b/tests/test_pipeline/test_bind_narrower_source.py
@@ -360,7 +360,10 @@ def test_narrower_then_nullable_runs_append_to_one_path(
second = job.run(orchestrator=orchestrator())
assert second.ok
assert set(database.list_table_paths(())) == paths
- assert sorted(job.nodes["inc"].as_table().column("z").to_pylist()) == [0, 4]
+ assert sorted(job.nodes["inc"].as_table().column("z").to_pylist()) == [
+ 0,
+ 4,
+ ]
stored = [database.get_all_records(path) for path in paths if path[-1] == "pdb_v2"]
assert [None if table is None else table.num_rows for table in stored] == [4]
@@ -529,7 +532,12 @@ def test_columns_follow_the_declared_order(a_type: Any) -> None:
for _, data in asyncio.run(_collect(node)):
assert data.as_table().column_names == ["a", "b", "c"]
assert node.head(1).table.column_names == ["id", "a", "b", "c"]
- assert job.nodes["renamed"].as_table().column_names == ["id", "a2", "b", "c"]
+ assert job.nodes["renamed"].as_table().column_names == [
+ "id",
+ "a2",
+ "b",
+ "c",
+ ]
def _mapped_stream() -> Any:
diff --git a/tests/test_pipeline/test_bind_type_check.py b/tests/test_pipeline/test_bind_type_check.py
index a5aa391a4..4485bcca2 100644
--- a/tests/test_pipeline/test_bind_type_check.py
+++ b/tests/test_pipeline/test_bind_type_check.py
@@ -188,7 +188,10 @@ def test_an_accepted_rebind_runs_and_stores_the_new_rows(
job.bind(sources={"src": _ints(source_id="other", start=10)})
_ = job.run()
# Results of the first source (x 1, 2) would be [1, 2].
- assert sorted(job.nodes["const"].as_table().column("z").to_pylist()) == [10, 11]
+ assert sorted(job.nodes["const"].as_table().column("z").to_pylist()) == [
+ 10,
+ 11,
+ ]
def _two_by_two_slot_job() -> PipelineJob:
diff --git a/tests/test_pipeline/test_capture_boundary.py b/tests/test_pipeline/test_capture_boundary.py
new file mode 100644
index 000000000..6d8ad3cc4
--- /dev/null
+++ b/tests/test_pipeline/test_capture_boundary.py
@@ -0,0 +1,2944 @@
+"""The capture decisions in the ITL-1559 step 3 specification."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import operator
+import re
+from collections.abc import Callable, Iterable
+from contextlib import nullcontext
+from copy import deepcopy
+from functools import partial
+from pathlib import Path
+from typing import TYPE_CHECKING, Any, cast
+
+import networkx as nx
+import pyarrow as pa
+import pytest
+
+import orcapod
+
+from orcapod import Pipeline, PipelineJob, SourceNode, function_pod
+from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNode
+from orcapod.core.operators import MergeJoin, SelectDataColumns
+from orcapod.core.nodes.source_node import SourceJobNode, slot_name_for
+from orcapod.core.sources.source_proxy import SourceProxy
+from orcapod.core.streams.arrow_table_stream import ArrowTableStream
+from orcapod.databases import InMemoryArrowDatabase
+from orcapod.errors import (
+ InconsistentSourceError,
+ SourceSlotNameCollisionError,
+ SourceSpecMismatchError,
+ UnboundSourceError,
+ UndefinedGraphMembershipError,
+)
+from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator
+from orcapod.pipeline.dag import OrcaDAG
+from orcapod.pipeline.base import ExecutionRoles, InvocationGraph
+from orcapod.pipeline.networkx_backend import NetworkxBackend
+from orcapod.pipeline.observer import NoOpObserver
+from orcapod.pipeline.pod_invocation import OperatorInvocation, PodInvocation
+from orcapod.side_effects import SideEffectPod
+from orcapod.sources import ArrowTableSource, CachedSource, DictSource
+from orcapod.types import Schema, SchemaLike
+from orcapod.utils.schema_utils import ReservedColumnNameError
+
+if TYPE_CHECKING:
+ from orcapod.protocols.core_protocols import StreamProtocol
+ from orcapod.protocols.observability_protocols import ExecutionObserverProtocol
+
+
+@function_pod(output_keys="doubled")
+def double(x: int) -> int:
+ return 2 * x
+
+
+@function_pod(output_keys="tripled")
+def triple(x: int) -> int:
+ return 3 * x
+
+
+@function_pod(output_keys="x")
+def echo(x: int) -> int:
+ return x
+
+
+@function_pod(output_keys="plus")
+def plus(doubled: int) -> int:
+ return doubled + 1
+
+
+def src(name: str = "a", base: int = 3, **kwargs) -> DictSource:
+ return DictSource(
+ [{"id": 1, "x": base}, {"id": 2, "x": base + 1}],
+ source_id=name,
+ tag_columns=["id"],
+ tag_only_columns=True,
+ **kwargs,
+ )
+
+
+def blueprint() -> Pipeline:
+ with Pipeline("p") as graph:
+ double.pod(src("slot", 0), label="output")
+ return graph
+
+
+def instance(source: DictSource | None = None) -> PipelineJob:
+ return PipelineJob.from_pipeline(
+ blueprint(),
+ database=InMemoryArrowDatabase(),
+ sources={"slot": source} if source is not None else None,
+ )
+
+
+def new_job() -> PipelineJob:
+ return PipelineJob("j", database=InMemoryArrowDatabase())
+
+
+def snapshot(graph: Pipeline | PipelineJob) -> tuple[object, ...]:
+ return (
+ tuple(
+ (
+ tuple((key, dict(attrs)) for key, attrs in topology.nodes(data=True)),
+ tuple(
+ (up, down, dict(attrs))
+ for up, down, attrs in topology.edges(data=True)
+ ),
+ dict(topology.graph),
+ )
+ for topology in (vars(graph)["_capture_graph"], vars(graph)["_hash_graph"])
+ ),
+ tuple(
+ (name, tuple((key, id(value)) for key, value in vars(graph)[name].items()))
+ for name in (
+ "_invocation_lut",
+ "_invocation_input_keys",
+ "_source_streams",
+ "_capture_leaves",
+ "_capture_nodes",
+ "_captured_calls",
+ )
+ + (("_captured_wire_keys",) if isinstance(graph, Pipeline) else ())
+ ),
+ tuple((label, id(node)) for label, node in graph.nodes.items()),
+ tuple((name, id(source)) for name, source in graph.sources.items())
+ if isinstance(graph, PipelineJob)
+ else (),
+ )
+
+
+def refused(
+ graph: Pipeline | PipelineJob,
+ capture: Callable[[], object],
+ message: str,
+ error: type[Exception] = InconsistentSourceError,
+) -> None:
+ before = snapshot(graph)
+ with pytest.raises(error) as caught:
+ _ = capture()
+ assert str(caught.value) == message
+ assert snapshot(graph) == before
+
+
+def foreign(slot: str = "slot", graph: str = "pipeline") -> str:
+ return (
+ f"Capturing source slot {slot!r} from outside this {graph} is not supported "
+ "yet (ITL-1559). Pass the source itself, or use node.as_source() to read "
+ "another job's stored results."
+ )
+
+
+def shared(first: str, second: str) -> str:
+ return (
+ f"Source 'dict_v1:a' would be read by slots {first!r} and {second!r}. "
+ "One source object on two slots is not supported yet (ITL-1559, step 6). "
+ "Read it through one slot and branch from that slot."
+ )
+
+
+def taken(name: str, first: str, second: str) -> str:
+ return (
+ f"Slot {name!r} already holds {first}; {second} is another object under "
+ "the same name. A slot holds exactly one source object until source "
+ "equivalence is defined (ITL-1553). Pass the same object again, or declare "
+ "the second one under its own slot name with "
+ "SourceNode.from_stream(stream, name=...)."
+ )
+
+
+def raw(source: DictSource, *, tagged: bool = True) -> ArrowTableStream:
+ table = source.as_table(columns={"system_tags": tagged})
+ if not tagged:
+ return ArrowTableStream(table, tag_columns=["id"])
+ return ArrowTableStream._from_derived_table( # pyright: ignore[reportPrivateUsage] # the source generated the system tags
+ table, tag_columns=["id"]
+ )
+
+
+def test_r06_one_object_two_slots_bind_refused() -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(SourceNode.from_stream(source, name="a"), label="ra")
+ double.pod(SourceNode.from_stream(src("b"), name="b"), label="rb")
+ refused(job, lambda: job.bind(sources={"a": source, "b": source}), shared("a", "b"))
+
+
+def test_r07_one_object_two_slots_capture_refused() -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(SourceNode.from_stream(source, name="x"))
+ refused(
+ job,
+ lambda: double.pod(SourceNode.from_stream(source, name="y")),
+ shared("x", "y"),
+ )
+
+
+def test_r12_prebuilt_equal_builds_refused() -> None:
+ source = src()
+ first, second = double.pod(source), double.pod(source)
+ name = slot_name_for(first)
+ with new_job() as job:
+ plus.pod(first, label="p1")
+ leaf = f"prebuilt stream {name!r}"
+ refused(job, lambda: plus.pod(second, label="p2"), taken(name, leaf, leaf))
+
+
+def test_r19_raw_two_equal_refused() -> None:
+ source = src()
+ first, second = raw(source), raw(source)
+ name = slot_name_for(first)
+ with new_job() as job:
+ double.pod(first)
+ leaf = f"raw stream {name!r}"
+ refused(job, lambda: triple.pod(second), taken(name, leaf, leaf))
+
+
+def test_r21_other_job_bound_node_refused() -> None:
+ job = instance(src())
+ with Pipeline("p") as graph:
+ refused(graph, lambda: plus.pod(job.output), foreign())
+
+
+def test_r22_other_job_unbound_node_refused() -> None:
+ job = instance()
+ with Pipeline("p") as graph:
+ refused(graph, lambda: plus.pod(job.output), foreign())
+
+
+def test_r23_instances_same_binding_refused() -> None:
+ template = blueprint()
+ source = src()
+ jobs = [
+ PipelineJob.from_pipeline(template, sources={"slot": source}) for _ in range(2)
+ ]
+ with Pipeline("p") as graph:
+ for job in jobs:
+ refused(graph, lambda: plus.pod(job.output), foreign())
+
+
+def test_r24_instances_other_binding_refused() -> None:
+ template = blueprint()
+ jobs = [
+ PipelineJob.from_pipeline(template, sources={"slot": source})
+ for source in (src(), src("b", 8))
+ ]
+ with Pipeline("p") as graph:
+ for job in jobs:
+ refused(graph, lambda: plus.pod(job.output), foreign())
+
+
+def test_r25_other_job_bound_slot_refused() -> None:
+ job = instance(src())
+ with Pipeline("p") as graph:
+ refused(graph, lambda: triple.pod(job.slot), foreign())
+
+
+def test_r26_other_job_unbound_slot_refused() -> None:
+ job = instance()
+ with Pipeline("p") as graph:
+ refused(graph, lambda: triple.pod(job.slot), foreign())
+
+
+def test_r27_instance_slots_other_binding_refused() -> None:
+ template = blueprint()
+ jobs = [
+ PipelineJob.from_pipeline(template, sources={"slot": source})
+ for source in (src(), src("b", 8))
+ ]
+ with Pipeline("p") as graph:
+ for job in jobs:
+ refused(graph, lambda: double.pod(job.slot), foreign())
+
+
+def test_r28_loaded_job_node_refused(tmp_path: Path, receiver) -> None:
+ job = instance(src())
+ job.run()
+ path = tmp_path / "job.json"
+ job.save(path)
+ loaded = PipelineJob.load(path, database=job.database)
+ graph, kind = receiver
+ prebuilt = SelectDataColumns(["doubled"])(loaded.output)
+ with graph:
+ refused(graph, lambda: plus.pod(loaded.output), foreign(graph=kind))
+ refused(graph, lambda: double.pod(loaded.slot), foreign(graph=kind))
+ refused(graph, lambda: plus.pod(prebuilt), foreign(graph=kind))
+
+
+def test_r35_slot_name_other_leaf_refused() -> None:
+ first, second = (
+ SourceNode.from_stream(source, name="x") for source in (src(), src("b", 8))
+ )
+ with Pipeline("p") as graph:
+ double.pod(first)
+ refused(
+ graph,
+ lambda: triple.pod(second),
+ taken("x", "declared slot 'x'", "declared slot 'x'"),
+ )
+
+
+def test_r37_slot_and_root_name_blueprint_refused() -> None:
+ with Pipeline("p") as graph:
+ double.pod(SourceNode.from_stream(src("b", 8), name="x"))
+ refused(
+ graph,
+ lambda: triple.pod(src("x")),
+ taken("x", "declared slot 'x'", "source 'dict_v1:x'"),
+ )
+
+
+def test_r38_slot_and_root_name_job_refused() -> None:
+ with new_job() as job:
+ double.pod(SourceNode.from_stream(src("b", 8), name="x"))
+ refused(
+ job,
+ lambda: triple.pod(src("x")),
+ taken("x", "declared slot 'x'", "source 'dict_v1:x'"),
+ )
+
+
+def test_r52_standalone_job_slot_into_blueprint_refused() -> None:
+ slot = SourceJobNode.from_stream(src(), name="slot")
+ with Pipeline("p") as graph:
+ refused(graph, lambda: double.pod(slot), foreign())
+
+
+def test_r08_equal_content_objects_refused() -> None:
+ for base in (3, 10):
+ with new_job() as job:
+ double.pod(src(), label="d")
+ refused(
+ job,
+ lambda: triple.pod(src(base=base), label="t"),
+ "Source 'dict_v1:a' has distinct source objects with one content hash "
+ "in step 'd' and step 't'. Build the source once and reuse the object. "
+ "If the source ID contributes to the hash, give each source its own source_id.",
+ )
+
+
+@pytest.mark.parametrize("graph_type", [Pipeline, PipelineJob])
+def test_r09_one_name_other_keys_refused(graph_type) -> None:
+ with graph_type("p") as graph:
+ double.pod(src(), label="d")
+ refused(
+ graph,
+ lambda: triple.pod(src(record_id_columns=["id"]), label="t"),
+ "Source 'dict_v1:a' has different key columns (record_id_columns) in "
+ "step 'd' and step 't'. Give the sources different source_id values. "
+ "ITL-1506 tracks distinct readings in distinct named slots.",
+ )
+
+
+def test_r15_prebuilt_over_own_slot_refused() -> None:
+ with new_job() as job:
+ double.pod(src(), label="d")
+ prebuilt = triple.pod(job.a)
+ with job:
+ refused(
+ job,
+ lambda: identity.pod(prebuilt),
+ "Capturing a prebuilt stream over source slot 'a' is not supported yet "
+ "(ITL-1559). Build the step inside the job from its slot, or pass the "
+ "source itself.",
+ )
+
+
+def test_r16_raw_without_system_tags_refused() -> None:
+ upstream = raw(src(), tagged=False)
+ with new_job() as job:
+ refused(
+ job,
+ lambda: double.pod(upstream),
+ missing_system_tags(slot_name_for(upstream)),
+ SourceSpecMismatchError,
+ )
+
+
+@pytest.mark.parametrize("bound", [False, True])
+def test_r20_other_job_into_job_refused(bound: bool) -> None:
+ inner = instance(src() if bound else None)
+ with new_job() as job:
+ refused(job, lambda: plus.pod(inner.output), foreign(graph="job"))
+ refused(job, lambda: triple.pod(inner.slot), foreign(graph="job"))
+
+
+def test_r30_two_derived_objects_refused() -> None:
+ inner = instance(src())
+ inner.run()
+ first, second = inner.output.as_source(), inner.output.as_source()
+ with new_job() as job:
+ plus.pod(first, label="p1")
+ refused(
+ job,
+ lambda: plus.pod(second, label="p2"),
+ f"Source {first.source_id!r} has distinct source objects with one content "
+ "hash in step 'p1' and step 'p2'. Build the source once and reuse the object. "
+ "If the source ID contributes to the hash, give each source its own source_id.",
+ )
+
+
+def test_r31_loaded_derived_source_refused(tmp_path: Path) -> None:
+ inner = instance(src())
+ inner.run()
+ path = tmp_path / "inner.json"
+ inner.save(path)
+ loaded = PipelineJob.load(path, database=inner.database)
+ upstream = loaded.output.as_source()
+ with new_job() as job:
+ refused(
+ job,
+ lambda: plus.pod(upstream),
+ missing_system_tags(upstream.source_name),
+ SourceSpecMismatchError,
+ )
+
+
+def test_r33_cached_and_wrapped_refused() -> None:
+ source = src()
+ cache = CachedSource(source, cache_database=InMemoryArrowDatabase())
+ with new_job() as job:
+ double.pod(cache, label="d")
+ refused(
+ job,
+ lambda: triple.pod(source, label="t"),
+ "Source 'dict_v1:a' has distinct source objects with one content hash "
+ "in step 'd' and step 't'. Build the source once and reuse the object. "
+ "If the source ID contributes to the hash, give each source its own source_id.",
+ )
+
+
+def test_r36_slot_name_other_schema_refused() -> None:
+ with Pipeline("p") as graph:
+ double.pod(SourceNode.from_stream(src(), name="x"), label="d")
+ other = SourceNode(
+ name="x", tag_schema=Schema({}), data_schema=Schema({"x": int})
+ )
+ refused(
+ graph,
+ lambda: triple.pod(other, label="t"),
+ "Pipeline 'p' has 2 source nodes all named 'x' but with different schemas. "
+ "Assign distinct source_id values to the conflicting sources so each slot "
+ "has a unique, stable identity.",
+ )
+
+
+@function_pod(output_keys="value")
+def identity(tripled: int) -> int:
+ return tripled
+
+
+def missing_system_tags(name: str) -> str:
+ return (
+ f"SourceNode '{name}' is not compatible with the provided source. "
+ "a source must carry exactly one source-id and one record-id system-tag "
+ "column and no other, not []: a stream without system-tag columns "
+ "(a raw ArrowTableStream) cannot be bound or used as a pipeline's input; "
+ "wrap its table as a source, e.g. ArrowTableSource(stream.as_table(), "
+ "tag_columns=[...]) (binding such a stream is planned, ITL-1127)"
+ )
+
+
+def listings(graph: Pipeline | PipelineJob) -> dict[str, Any]:
+ dag = cast("OrcaDAG[Any]", graph.dag)
+ return {
+ "labels": sorted(graph.nodes),
+ "dag_nodes": sorted(node.label for node in dag.nodes()),
+ "edges": sorted([up.label, down.label] for up, down in dag.edges()),
+ "adjacency": {
+ node.label: [
+ sorted(up.label for up in dag.predecessors(node)),
+ sorted(down.label for down in dag.successors(node)),
+ ]
+ for node in dag.nodes()
+ },
+ "source_pods": sorted(graph.source_pods),
+ }
+
+
+@pytest.fixture(autouse=True)
+def saved_writer_version(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The main fixtures use one version string so this metadata can be compared
+ # byte for byte when installed from a different Git revision.
+ monkeypatch.setattr(orcapod, "__version__", "0.4.0")
+
+
+@pytest.fixture(params=["sync", "async"])
+def mode(request: pytest.FixtureRequest) -> str:
+ return request.param
+
+
+class Addresses(NoOpObserver):
+ def __init__(self) -> None:
+ self.starts: dict[str, str] = {}
+ self.ends: dict[str, str] = {}
+
+ def on_node_start(
+ self, node_label: str, node_hash: str, tag_schema: SchemaLike | None = None
+ ) -> None:
+ self.starts[node_label] = node_hash
+
+ def on_node_end(self, node_label: str, node_hash: str) -> None:
+ self.ends[node_label] = node_hash
+
+
+def run(
+ job: PipelineJob, mode: str, *, observer: ExecutionObserverProtocol | None = None
+) -> None:
+ if mode == "async":
+ asyncio.run(job.run_async(observer=observer))
+ else:
+ job.run(observer=observer)
+
+
+def accepted(
+ row: str,
+ graph: Pipeline | PipelineJob,
+ tmp_path: Path,
+ *,
+ slots: set[str],
+ labels: set[str],
+ mode: str = "sync",
+ rows: dict[str, tuple[str, list[int]]] | None = None,
+) -> None:
+ path = tmp_path / f"{row}.json"
+ graph.save(path)
+ baseline = Path(__file__).with_name("fixtures") / "itl_1559_capture"
+ saved_main = (baseline / path.name).read_bytes()
+ assert path.read_bytes() == saved_main
+ assert listings(graph) == json.loads(
+ (baseline / f"{row}.listings.json").read_text()
+ )
+ assert set(graph.nodes) == labels
+ assert {node.name for node in graph.source_pods.values()} == slots
+ assert set(graph._hash_graph.nodes) == {
+ node.node_hash().to_string() for node in graph.nodes.values()
+ }
+ assert len(graph.dag) == len(labels)
+ if rows is not None:
+ assert isinstance(graph, PipelineJob)
+ observer = Addresses()
+ run(graph, mode, observer=observer)
+ assert observer.starts == observer.ends
+ expected = json.loads(saved_main)["run"]["node_job_content_hashes"]
+ assert {
+ label: digest
+ for label, digest in observer.starts.items()
+ if label in expected
+ } == expected
+ for label, (column, values) in rows.items():
+ assert (
+ graph.nodes[label]
+ .as_table(columns={"sort_by_tags": True})[column]
+ .to_pylist()
+ == values
+ )
+
+
+def test_r01_step_inside_graph(tmp_path: Path, mode: str) -> None:
+ with new_job() as job:
+ step = double.pod(src(), label="d")
+ plus.pod(step, label="p")
+ accepted(
+ "01",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d", "p"},
+ mode=mode,
+ rows={"d": ("doubled", [6, 8]), "p": ("plus", [7, 9])},
+ )
+
+
+def test_r02_own_node_later_capture(tmp_path: Path, mode: str) -> None:
+ with new_job() as job:
+ double.pod(src(), label="d")
+ with job:
+ plus.pod(job.d, label="p")
+ accepted(
+ "02",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d", "p"},
+ mode=mode,
+ rows={"p": ("plus", [7, 9])},
+ )
+
+
+def test_r03_root_once(tmp_path: Path, mode: str) -> None:
+ with new_job() as job:
+ double.pod(src(), label="d")
+ accepted(
+ "03",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d"},
+ mode=mode,
+ rows={"d": ("doubled", [6, 8])},
+ )
+
+
+def test_r04_same_object_same_pod(tmp_path: Path, mode: str) -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(source, label="d1")
+ double.pod(source, label="d2")
+ accepted(
+ "04",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d1"},
+ mode=mode,
+ rows={"d1": ("doubled", [6, 8])},
+ )
+
+
+def test_r05_same_object_two_pods(tmp_path: Path, mode: str) -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(source, label="d")
+ triple.pod(source, label="t")
+ accepted(
+ "05",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d", "t"},
+ mode=mode,
+ rows={"d": ("doubled", [6, 8]), "t": ("tripled", [9, 12])},
+ )
+
+
+def test_r10_prebuilt_once(tmp_path: Path, mode: str) -> None:
+ leaf = double.pod(src())
+ with new_job() as job:
+ plus.pod(leaf, label="p")
+ name = slot_name_for(leaf)
+ accepted(
+ "10",
+ job,
+ tmp_path,
+ slots={name},
+ labels={name, "p"},
+ mode=mode,
+ rows={"p": ("plus", [7, 9])},
+ )
+
+
+def test_r11_prebuilt_same_object_twice(tmp_path: Path, mode: str) -> None:
+ leaf = double.pod(src())
+ with new_job() as job:
+ plus.pod(leaf, label="p1")
+ plus.pod(leaf, label="p2")
+ name = slot_name_for(leaf)
+ accepted(
+ "11",
+ job,
+ tmp_path,
+ slots={name},
+ labels={name, "p1"},
+ mode=mode,
+ rows={"p1": ("plus", [7, 9])},
+ )
+
+
+def test_r13_prebuilt_other_content(tmp_path: Path, mode: str) -> None:
+ first, second = double.pod(src()), double.pod(src("b", 8))
+ with new_job() as job:
+ plus.pod(first, label="p1")
+ plus.pod(second, label="p2")
+ slots = {slot_name_for(first), slot_name_for(second)}
+ accepted(
+ "13",
+ job,
+ tmp_path,
+ slots=slots,
+ labels=slots | {"p1", "p2"},
+ mode=mode,
+ rows={"p1": ("plus", [7, 9]), "p2": ("plus", [17, 19])},
+ )
+
+
+def test_r14_prebuilt_and_its_root(tmp_path: Path, mode: str) -> None:
+ source = src()
+ leaf = double.pod(source)
+ with new_job() as job:
+ triple.pod(source, label="t")
+ plus.pod(leaf, label="p")
+ slots = {"a", slot_name_for(leaf)}
+ accepted(
+ "14",
+ job,
+ tmp_path,
+ slots=slots,
+ labels=slots | {"p", "t"},
+ mode=mode,
+ rows={"p": ("plus", [7, 9]), "t": ("tripled", [9, 12])},
+ )
+
+
+def test_r17_raw_once(tmp_path: Path, mode: str) -> None:
+ upstream = raw(src())
+ with new_job() as job:
+ double.pod(upstream, label="d")
+ name = slot_name_for(upstream)
+ accepted(
+ "17",
+ job,
+ tmp_path,
+ slots={name},
+ labels={name, "d"},
+ mode=mode,
+ rows={"d": ("doubled", [6, 8])},
+ )
+
+
+@pytest.mark.parametrize("job_graph", [False, True])
+def test_r18_raw_two_distinct(tmp_path: Path, mode: str, job_graph: bool) -> None:
+ graph = new_job() if job_graph else Pipeline("p")
+ table = src().as_table(columns={"system_tags": job_graph})
+ wrap = (
+ ArrowTableStream._from_derived_table # pyright: ignore[reportPrivateUsage] # the source generated the system tags
+ if job_graph
+ else ArrowTableStream
+ )
+ first, second = (wrap(table.slice(i, 1), tag_columns=["id"]) for i in range(2))
+ with graph:
+ double.pod(first, label="d1")
+ double.pod(second, label="d2")
+ slots = {slot_name_for(first), slot_name_for(second)}
+ accepted(
+ "18-job" if job_graph else "18-blueprint",
+ graph,
+ tmp_path,
+ slots=slots,
+ labels=slots | {"d1", "d2"},
+ mode=mode,
+ rows={"d1": ("doubled", [6]), "d2": ("doubled", [8])} if job_graph else None,
+ )
+
+
+def test_r29_derived_source(tmp_path: Path, mode: str) -> None:
+ inner = instance(src())
+ run(inner, mode)
+ upstream = inner.output.as_source()
+ with new_job() as job:
+ plus.pod(upstream, label="p")
+ name = upstream.source_name
+ accepted(
+ "29",
+ job,
+ tmp_path,
+ slots={name},
+ labels={name, "p"},
+ mode=mode,
+ rows={"p": ("plus", [7, 9])},
+ )
+
+
+def test_r32_cached_source(tmp_path: Path, mode: str) -> None:
+ upstream = CachedSource(src(), cache_database=InMemoryArrowDatabase())
+ with new_job() as job:
+ double.pod(upstream, label="d")
+ accepted(
+ "32",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "d"},
+ mode=mode,
+ rows={"d": ("doubled", [6, 8])},
+ )
+
+
+def test_r34_slot_name_same_leaf(tmp_path: Path, mode: str) -> None:
+ source = src()
+ with Pipeline("p") as graph:
+ double.pod(SourceNode.from_stream(source, name="x"), label="d")
+ triple.pod(SourceNode.from_stream(source, name="x"), label="t")
+ accepted("34", graph, tmp_path, slots={"x"}, labels={"x", "d", "t"})
+ job = PipelineJob.from_pipeline(
+ graph, database=InMemoryArrowDatabase(), sources={"x": source}
+ )
+ run(job, mode)
+ assert job.d.as_table()["doubled"].to_pylist() == [6, 8]
+ assert job.t.as_table()["tripled"].to_pylist() == [9, 12]
+
+
+def test_r39_slot_name_equals_step_label(tmp_path: Path, mode: str) -> None:
+ with Pipeline("p") as graph:
+ double.pod(src(), label="a")
+ accepted("39", graph, tmp_path, slots={"a"}, labels={"a", "a_1"})
+ job = PipelineJob.from_pipeline(
+ graph, database=InMemoryArrowDatabase(), sources={"a": src()}
+ )
+ run(job, mode)
+ assert job.a.as_table()["doubled"].to_pylist() == [6, 8]
+
+
+def test_r40_merge_join_repeated_input(tmp_path: Path, mode: str) -> None:
+ source = src()
+ with new_job() as job:
+ MergeJoin()(source, source, label="joined")
+ accepted("40", job, tmp_path, slots={"a"}, labels={"a", "joined"})
+ assert job._hash_graph[job.a.node_hash().to_string()][
+ job.joined.node_hash().to_string()
+ ]["positions"] == (0, 1)
+
+ run(job, mode)
+ assert job.joined.as_table().num_rows == 2
+
+
+def test_r41_label_kept_as_main(tmp_path: Path, mode: str) -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(source, label="r1")
+ double.pod(source, label="r2")
+ double.pod(source)
+ accepted(
+ "41",
+ job,
+ tmp_path,
+ slots={"a"},
+ labels={"a", "r1"},
+ mode=mode,
+ rows={"r1": ("doubled", [6, 8])},
+ )
+
+
+def check_foreign(first: PipelineJob, second: PipelineJob) -> None:
+ for node in (second.output, second.slot):
+ with pytest.raises(UndefinedGraphMembershipError):
+ _ = node in first.dag
+ with pytest.raises(KeyError):
+ _ = first.dag.predecessors(second.output)
+ with pytest.raises(KeyError):
+ _ = first.dag.successors(second.slot)
+ with pytest.raises(KeyError):
+ _ = first.dag.ancestors(second.output)
+
+
+def check_own(
+ graph: Pipeline | PipelineJob, label: str = "output", slot: str = "slot"
+) -> None:
+ output = graph.nodes[label]
+ source = graph.nodes[slot]
+ assert output is getattr(graph, label)
+ assert source is getattr(graph, slot)
+ for node in (output, source):
+ assert node in graph.dag
+ assert node in graph.dag.nodes()
+ assert any(node is source for node in graph.dag.predecessors(output))
+ assert any(node is output for node in graph.dag.successors(source))
+ assert any(node is source for node in graph.dag.ancestors(output))
+
+
+def test_r42_foreign_object_lookup() -> None:
+ check_foreign(instance(src("first")), instance(src("second", 7)))
+
+
+def test_r43_instances_different_sources() -> None:
+ first, second = instance(src("first")), instance(src("second", 7))
+ assert first.output != second.output
+ assert hash(first.output) != hash(second.output)
+ assert first.nodes["output"] is first.output
+ check_foreign(first, second)
+
+
+def test_r44_instances_same_source_object() -> None:
+ source = src()
+ first, second = instance(source), instance(source)
+ assert first.output == second.output
+ assert hash(first.output) == hash(second.output)
+ check_own(first)
+ check_foreign(first, second)
+
+
+def test_r45_instances_equal_source_objects() -> None:
+ first, second = instance(src()), instance(src())
+ assert first.output == second.output
+ assert hash(first.output) == hash(second.output)
+ check_own(first)
+ check_foreign(first, second)
+
+
+def test_r46_unbound_instances() -> None:
+ first, second = instance(), instance()
+ assert first.output == second.output
+ assert hash(first.output) == hash(second.output)
+ check_own(first)
+ check_foreign(first, second)
+
+
+def test_r47_bound_and_unbound_instance() -> None:
+ first, second = instance(src()), instance()
+ assert first.output != second.output
+ assert hash(first.output) != hash(second.output)
+ check_foreign(first, second)
+
+
+def test_r48_own_node_after_from_pipeline_bind() -> None:
+ check_own(instance(src()))
+
+
+def test_r49_own_node_captured_job() -> None:
+ with new_job() as job:
+ double.pod(src(), label="d")
+ check_own(job, "d", "a")
+
+
+def test_r50_own_node_unbound_then_bind() -> None:
+ job = instance()
+ output = job.output
+ check_own(job)
+ job.bind(sources={"slot": src()})
+ check_own(job)
+ assert job.output is output
+
+
+def test_r51_blueprint_membership() -> None:
+ graph = blueprint()
+ job = PipelineJob.from_pipeline(graph)
+ check_own(graph)
+ for node in (job.output, job.slot):
+ with pytest.raises(UndefinedGraphMembershipError):
+ _ = node in graph.dag
+ with pytest.raises(KeyError):
+ _ = graph.dag.predecessors(job.output)
+
+
+@pytest.mark.parametrize("kind", [Pipeline, PipelineJob])
+@pytest.mark.parametrize("compile_between", [False, True])
+@pytest.mark.parametrize("explicit_first", [True, False], ids=["r53", "r54"])
+def test_r53_r54_mixed_capture_refused(
+ kind, compile_between: bool, explicit_first: bool
+) -> None:
+ graph = kind("mixed", auto_compile=False)
+ source = src()
+ declaration = SourceNode.from_stream(source, name="a")
+ declared = partial(double.pod, declaration, label="declared")
+ direct = partial(triple.pod, source, label="direct")
+ first, second = (declared, direct) if explicit_first else (direct, declared)
+ with graph:
+ first()
+ if compile_between:
+ graph.compile()
+ with graph:
+ refused(
+ graph,
+ second,
+ "The same source object is already declared under slot 'a'. Use the "
+ "slot declaration or capture the source directly (ITL-1559).",
+ )
+ graph.compile()
+ assert set(graph.nodes) == {"a", "declared" if explicit_first else "direct"}
+
+
+@pytest.fixture(params=["pipeline", "job"])
+def receiver(request: pytest.FixtureRequest) -> tuple[Pipeline | PipelineJob, str]:
+ kind = str(request.param)
+ return (Pipeline("outer") if kind == "pipeline" else new_job()), kind
+
+
+@pytest.mark.parametrize("entry", ["pod", "record", "operator"])
+def test_r55_foreign_blueprint_node_refused(receiver, entry: str) -> None:
+ outer, kind = receiver
+ upstream = blueprint()
+ captures = {
+ "pod": lambda: plus.pod(upstream.output),
+ "record": lambda: outer.record_function_pod_invocation(
+ plus.pod, upstream.output
+ ),
+ "operator": lambda: SelectDataColumns(["doubled"])(upstream.output),
+ }
+ with outer:
+ refused(outer, captures[entry], foreign(graph=kind))
+
+
+def test_r56_foreign_blueprint_slot_refused(receiver) -> None:
+ outer, kind = receiver
+ upstream = blueprint()
+ with outer:
+ refused(outer, lambda: double.pod(upstream.slot), foreign(graph=kind))
+
+
+def test_r57_foreign_blueprint_invocation_stream_refused(receiver) -> None:
+ outer, kind = receiver
+ with Pipeline("inner", auto_compile=False):
+ step = double.pod(src("slot"), label="output")
+ with outer:
+ refused(outer, lambda: plus.pod(step), foreign(graph=kind))
+
+
+def test_r58_prebuilt_over_foreign_blueprint_refused(receiver) -> None:
+ outer, kind = receiver
+ upstream = blueprint()
+ step = SelectDataColumns(["doubled"])(upstream.output)
+ with outer:
+ refused(outer, lambda: plus.pod(step), foreign(graph=kind))
+
+
+@pytest.mark.parametrize("form", ["output", "slot", "prebuilt"])
+def test_r59_loaded_blueprint_object_refused(
+ tmp_path: Path, receiver, form: str
+) -> None:
+ outer, kind = receiver
+ path = tmp_path / "blueprint.json"
+ blueprint().save(path)
+ loaded = Pipeline.load(path)
+ stream = (
+ loaded.nodes[form]
+ if form != "prebuilt"
+ else SelectDataColumns(["doubled"])(loaded.output)
+ )
+ pod = double.pod if form == "slot" else plus.pod
+ with outer:
+ refused(outer, lambda: pod(stream), foreign(graph=kind))
+
+
+def test_r60_unknown_capture_input_refused(receiver) -> None:
+ outer, _ = receiver
+ refused(
+ outer,
+ lambda: outer.record_function_pod_invocation(double.pod, cast(Any, object())),
+ "Capturing an input of type 'object' is not supported yet (ITL-1559). "
+ "Pass a source or a supported stream.",
+ )
+
+
+def test_r61_capture_into_loaded_blueprint_refused(tmp_path: Path) -> None:
+ with Pipeline("inner") as original:
+ SelectDataColumns(["x"])(src("slot"), label="output")
+ path = tmp_path / "blueprint.json"
+ original.save(path)
+ loaded = Pipeline.load(path)
+ with loaded:
+ refused(
+ loaded,
+ lambda: double.pod(loaded.output),
+ "Capturing into a loaded pipeline is not supported yet (ITL-1559). "
+ "Rebuild the pipeline from its original code before adding steps.",
+ )
+
+
+def test_r62_capture_into_loaded_job_refused(tmp_path: Path) -> None:
+ original = instance(src())
+ original.run()
+ path = tmp_path / "job.json"
+ original.save(path)
+ loaded = PipelineJob.load(path, database=original.database)
+ before = snapshot(loaded)
+ with loaded:
+ refused(
+ loaded,
+ lambda: plus.pod(loaded.output),
+ "Capturing into a loaded job is not supported yet (ITL-1559). "
+ "Rebuild the job from its original code before adding steps.",
+ )
+ assert snapshot(loaded) == before
+
+
+def test_r63_side_effect_over_root(mode: str) -> None:
+ delivered = []
+
+ def deliver(x: int, ctx) -> None:
+ delivered.append(x)
+
+ with new_job() as job:
+ SideEffectPod(deliver)(src(), label="delivery")
+ run(job, mode)
+ assert sorted(delivered) == [3, 4]
+
+
+def test_r64_stored_source_with_promoted_tags(mode: str) -> None:
+ upstream = instance(src())
+ run(upstream, mode)
+ source = upstream.output.as_source(
+ source_id="derived", tags_as_data={"id": "tag_copy"}
+ )
+
+ @function_pod(output_keys="out")
+ def increment(tag_copy: int) -> int:
+ return tag_copy + 1
+
+ with new_job() as job:
+ increment.pod(source, label="increment")
+ run(job, mode)
+ assert sorted(job.increment.as_table()["out"].to_pylist()) == [2, 3]
+
+
+@pytest.mark.parametrize("explicit_first", [True, False])
+def test_r66_same_leaf_different_mixed_slot_names_refused(
+ receiver, explicit_first: bool
+) -> None:
+ graph, _ = receiver
+ source = src()
+ declaration = SourceNode.from_stream(source, name="alias")
+ name_order = ("alias", "a") if explicit_first else ("a", "alias")
+ first, second = (declaration, source) if explicit_first else (source, declaration)
+ with graph:
+ double.pod(first, label="first")
+ refused(graph, lambda: triple.pod(second), shared(*name_order))
+
+
+@pytest.mark.parametrize(
+ "case",
+ [
+ test_r01_step_inside_graph,
+ test_r02_own_node_later_capture,
+ test_r03_root_once,
+ test_r04_same_object_same_pod,
+ test_r05_same_object_two_pods,
+ test_r10_prebuilt_once,
+ test_r11_prebuilt_same_object_twice,
+ test_r13_prebuilt_other_content,
+ test_r14_prebuilt_and_its_root,
+ test_r17_raw_once,
+ pytest.param(partial(test_r18_raw_two_distinct, job_graph=True), id="r18_job"),
+ pytest.param(
+ partial(test_r18_raw_two_distinct, job_graph=False), id="r18_blueprint"
+ ),
+ test_r29_derived_source,
+ test_r32_cached_source,
+ test_r34_slot_name_same_leaf,
+ test_r39_slot_name_equals_step_label,
+ test_r40_merge_join_repeated_input,
+ test_r41_label_kept_as_main,
+ ],
+ ids=lambda test: test.__name__,
+)
+def test_graph_layer_uses_no_node_equality(
+ case: Callable[[Path, str], None],
+ tmp_path: Path,
+ mode: str,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from contextvars import ContextVar
+
+ from orcapod.core.nodes.source_node import SourceNodeBase
+ from orcapod.core.streams.base import StreamBase
+ from orcapod.pipeline import dag, graph
+ from orcapod.pipeline.pod_invocation import PodInvocation
+
+ projecting = ContextVar("projecting", default=False)
+
+ def allow_projection(project):
+ def projected(*args, **kwargs):
+ token = projecting.set(True)
+ try:
+ return project(*args, **kwargs)
+ finally:
+ projecting.reset(token)
+
+ return projected
+
+ def guard(method):
+ def checked(node, *args):
+ assert projecting.get(), f"{type(node).__name__}.{method.__name__}"
+ return method(node, *args)
+
+ return checked
+
+ project_legacy = allow_projection(dag.project_legacy_graph)
+ monkeypatch.setattr(dag, "project_legacy_graph", project_legacy)
+ monkeypatch.setattr(graph, "project_legacy_graph", project_legacy)
+ # Public frozensets use public node equality. The separate listing property
+ # checks these snapshots against main without intercepting their equality.
+ monkeypatch.setitem(globals(), "listings", allow_projection(listings))
+ for cls in (StreamBase, SourceNodeBase, PodInvocation):
+ monkeypatch.setattr(cls, "__hash__", guard(cls.__hash__))
+ monkeypatch.setattr(cls, "__eq__", guard(cls.__eq__))
+ case(tmp_path, mode)
+ loaded: Pipeline | PipelineJob
+ for path in tmp_path.glob("*.json"):
+ descriptor = json.loads(path.read_text())
+ if "orcapod_pipeline_job_version" in descriptor:
+ loaded = PipelineJob.load(path, database=InMemoryArrowDatabase())
+ _ = loaded.run(load_only=True)
+ for node in loaded.dag:
+ if not isinstance(node, SourceJobNode):
+ node.clear_cache()
+ else:
+ loaded = Pipeline.load(path)
+ assert sorted(node.label for node in loaded.dag) == sorted(loaded.nodes)
+
+
+def test_keys_fixed_at_capture(tmp_path: Path) -> None:
+ with Pipeline("fixed", auto_compile=False) as graph:
+ double.pod(src(), label="d")
+ keys = set(graph._hash_graph.nodes)
+ graph.compile()
+ assert set(graph._hash_graph.nodes) == keys
+ job = PipelineJob.from_pipeline(graph, database=InMemoryArrowDatabase())
+ path = tmp_path / "keys.json"
+ job.save(path)
+ wire_keys = set(json.loads(path.read_text())["pipeline"]["nodes"])
+ for source in (src(), src("rebound", 8)):
+ job.bind(sources={"a": source})
+ job.compile()
+ assert set(job._hash_graph.nodes) == keys
+ job.save(path)
+ assert set(json.loads(path.read_text())["pipeline"]["nodes"]) == wire_keys
+
+
+@pytest.mark.parametrize("outside_first", [False, True])
+def test_r67_slot_and_step_legacy_alias_refused(receiver, outside_first: bool) -> None:
+ graph, _ = receiver
+ source = src()
+ outside = double.pod(source)
+ with graph:
+ inside = partial(double.pod, source, label="inside")
+ use_outside = partial(plus.pod, outside, label="after_outside")
+ if outside_first:
+ use_outside()
+ else:
+ plus.pod(inside(), label="after_inside")
+ refused(
+ graph,
+ inside if outside_first else use_outside,
+ f"Slot {slot_name_for(outside)!r} and an in-graph step share a legacy execution "
+ "identity. Capture the step inside the graph and reuse its output (ITL-1559).",
+ )
+
+
+def test_r74_equal_prebuilt_streams_with_different_inferred_names(
+ receiver: tuple[Pipeline | PipelineJob, str], mode: str
+) -> None:
+ graph, _ = receiver
+ source = src()
+ first = double.pod(source, label="first")
+ second = double.pod(source, label="second")
+ first_name, second_name = slot_name_for(first), slot_name_for(second)
+ assert first_name != second_name
+ assert first.content_hash() == second.content_hash()
+
+ @function_pod(output_keys="final")
+ def finish(plus: int) -> int:
+ return 10 * plus
+
+ with graph:
+ _ = plus.pod(first, label="p")
+
+ def capture_second() -> None:
+ _ = finish.pod(plus.pod(second, label="t"), label="out")
+
+ refused(
+ graph,
+ capture_second,
+ f"Slots {first_name!r} and {second_name!r} share a legacy execution identity. "
+ "Bind distinct sources to the slots, or read through one slot "
+ "and branch from it (ITL-1559).",
+ )
+ job = (
+ graph
+ if isinstance(graph, PipelineJob)
+ else PipelineJob.from_pipeline(
+ graph, sources={first_name: first}, database=InMemoryArrowDatabase()
+ )
+ )
+ run(job, mode)
+ assert job.p.as_table(columns={"sort_by_tags": True})["plus"].to_pylist() == [7, 9]
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("incoming_role", ["step", "slot"])
+def test_rewired_job_input_cannot_alias_later_capture(
+ mode: str, incoming_role: str
+) -> None:
+ left, right = src("left"), src("right", 9)
+ project = SelectDataColumns(["x"])
+ name = "outside"
+ outside = OperatorJobNode(project, (right,), label=name)
+ slot_name = slot_name_for(outside)
+ with new_job() as job:
+ double.pod(outside, label="outside_result")
+ outside.upstreams = (left,)
+
+ incoming = project(left, label="incoming") if incoming_role == "slot" else None
+ message = (
+ f"Slots {slot_name!r} and {slot_name_for(incoming)!r} share a legacy execution "
+ "identity. Bind distinct sources to the slots, or read through one slot "
+ "and branch from it (ITL-1559)."
+ if incoming is not None
+ else f"Slot {slot_name!r} and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559)."
+ )
+
+ def capture() -> None:
+ with job:
+ step = project(left, label="incoming") if incoming is None else incoming
+ double.pod(step, label="inside_result")
+
+ refused(job, capture, message)
+ with job:
+ double.pod(project(right, label="distinct"), label="distinct_result")
+ run(job, mode)
+ assert job.distinct_result.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [18, 20]
+
+
+@pytest.mark.parametrize("incoming_role", ["step", "slot"])
+def test_rewire_refuses_an_existing_execution_alias(incoming_role: str) -> None:
+ left, right = src("left"), src("right", 9)
+ project = SelectDataColumns(["x"])
+ outside = OperatorJobNode(project, (right,), label="outside")
+ incoming = project(left, label="incoming") if incoming_role == "slot" else None
+ with new_job() as job:
+ double.pod(outside, label="first")
+ second = project(left, label="incoming") if incoming is None else incoming
+ triple.pod(second, label="second")
+
+ before = snapshot(job)
+ identity = outside.content_hash()
+ with pytest.raises(
+ InconsistentSourceError, match="share a legacy execution identity"
+ ):
+ outside.upstreams = (left,)
+ assert snapshot(job) == before
+ assert outside.upstreams[0] is right
+ assert outside.content_hash() == identity
+
+
+@pytest.mark.parametrize("incoming_role", ["step", "slot"])
+def test_stored_result_rebind_cannot_alias_later_capture(incoming_role: str) -> None:
+ with new_job() as upstream:
+ echo.pod(src("origin"), label="result")
+ assert upstream.run().ok
+ stored = upstream.result.as_source(source_id="stored")
+ project = SelectDataColumns(["x"])
+ outside = project(stored, label="outside")
+ slot_name = slot_name_for(outside)
+ with new_job() as job:
+ double.pod(outside, label="held")
+
+ upstream.bind(sources={"origin": src("replacement", 9)})
+ incoming = project(stored, label="incoming") if incoming_role == "slot" else None
+ before = snapshot(job)
+ with pytest.raises(
+ InconsistentSourceError, match="share a legacy execution identity"
+ ) as caught:
+ if incoming is None:
+ job.record_operator_pod_invocation(project, (stored,), label="incoming")
+ else:
+ job.record_operator_pod_invocation(project, (incoming,), label="consumer")
+ assert slot_name in str(caught.value)
+ assert snapshot(job) == before
+
+
+def test_r74_invocation_import_validates_its_slots(
+ receiver: tuple[Pipeline | PipelineJob, str],
+) -> None:
+ graph, _ = receiver
+ source = src()
+ first = double.pod(source, label="first")
+ second = double.pod(source, label="second")
+ records = InvocationGraph((), {"first": first, "second": second})
+ with pytest.raises(
+ InconsistentSourceError, match="share a legacy execution identity"
+ ):
+ _ = type(graph).from_invocations(records)
+
+
+def test_r74_prepared_invocation_validates_current_records(
+ receiver: tuple[Pipeline | PipelineJob, str],
+) -> None:
+ graph, _ = receiver
+ source = src()
+ first = double.pod(source, label="first")
+ second = double.pod(source, label="second")
+ select = SelectDataColumns(["doubled"])
+ publish = graph.prepare_invocation(OperatorInvocation(select, (second,), "t"))
+ graph.record_operator_pod_invocation(select, (first,), label="p")
+ refused(
+ graph,
+ publish,
+ f"Slots {slot_name_for(first)!r} and {slot_name_for(second)!r} share a legacy "
+ "execution identity. Bind distinct sources to the slots, or read through "
+ "one slot and branch from it (ITL-1559).",
+ )
+
+
+def test_r68_implicit_name_matches_one_of_two_explicit_slots() -> None:
+ source = src()
+ with Pipeline("outer") as graph:
+ double.pod(SourceNode.from_stream(source, name="a"), label="first")
+ double.pod(SourceNode.from_stream(source, name="alias"), label="second")
+ refused(graph, lambda: triple.pod(source), shared("alias", "a"))
+
+
+@pytest.mark.parametrize("owner", ["pipeline", "job"])
+@pytest.mark.parametrize("form", ["recorded", "prebuilt", "compiled"])
+@pytest.mark.parametrize("entry", ["from_pipeline", "bind", "setter"])
+def test_r69_foreign_live_binding_refused(owner: str, form: str, entry: str) -> None:
+ project = SelectDataColumns(["x"])
+ # Each case has a different receiver and a live producer over an independent root.
+ with Pipeline("inner") if owner == "pipeline" else new_job() as inner:
+ recorded = project(src("foreign_root"), label="step")
+ upstream = {
+ "recorded": recorded,
+ "prebuilt": project(recorded),
+ "compiled": inner.step,
+ }[form]
+ outer = blueprint()
+ job = PipelineJob.from_pipeline(outer)
+ captures = {
+ "from_pipeline": lambda: PipelineJob.from_pipeline(
+ outer, sources={"slot": upstream}
+ ),
+ "bind": lambda: job.bind(sources={"slot": upstream}),
+ "setter": lambda: setattr(job.slot, "bound_source", upstream),
+ }
+ if owner == "job" and form == "compiled":
+ refused(
+ job,
+ captures[entry],
+ "Binding source slot 'slot' to a source that depends on source slot "
+ "'foreign_root' is not supported yet (ITL-1559). Pass the underlying "
+ "source, or use a non-slot node's as_source() to read stored results.",
+ SourceSpecMismatchError,
+ )
+ else:
+ refused(job, captures[entry], foreign("foreign_root", "job"))
+
+
+@pytest.mark.parametrize("own_slot", [False, True])
+def test_r70_capture_into_job_derived_blueprint_refused(own_slot: bool) -> None:
+ with new_job() as job:
+ SelectDataColumns(["x"])(src(), label="first")
+ graph = job.pipeline
+ before = snapshot(graph)
+ with graph:
+ refused(
+ graph,
+ lambda: double.pod(graph.a if own_slot else src("b")),
+ "Capturing into a job-derived pipeline is not supported yet "
+ "(ITL-1559). Rebuild the pipeline from its original code before adding steps.",
+ )
+ graph.compile()
+ assert snapshot(graph) == before
+
+
+@pytest.mark.parametrize("compile_first", [False, True])
+def test_r71_foreign_declaration_refused_at_capture(
+ receiver, compile_first: bool
+) -> None:
+ outer, kind = receiver
+ slot = SourceNode.from_stream(src(), name="slot")
+ with Pipeline("inner", auto_compile=compile_first) as inner:
+ double.pod(slot)
+ refused(
+ outer,
+ lambda: outer.record_function_pod_invocation(double.pod, slot),
+ foreign(graph=kind),
+ )
+ if not compile_first:
+ inner.compile()
+ assert any(node is inner.nodes["slot"] for node in inner.dag.nodes())
+
+
+@pytest.mark.parametrize("prebuilt_first", [False, True])
+def test_r72_slot_and_step_name_collision_refused(
+ receiver, prebuilt_first: bool
+) -> None:
+ graph, _ = receiver
+ outside = SelectDataColumns(["x"])(src())
+ name = slot_name_for(outside)
+ slot = partial(double.pod, outside, label="output")
+ step = partial(double.pod, src("b", 8), label=name)
+ with graph:
+ first, second = (slot, step) if prebuilt_first else (step, slot)
+ first()
+ before = snapshot(graph)
+ with pytest.raises(
+ InconsistentSourceError, match="another object under the same name"
+ ):
+ second()
+ assert snapshot(graph) == before
+
+
+def test_r72_generated_step_name_is_reserved(receiver) -> None:
+ graph, _ = receiver
+ with graph:
+ double.pod(src("left"), label="shared")
+ double.pod(src("right", 8), label="shared")
+ with graph:
+ before = snapshot(graph)
+ with pytest.raises(
+ InconsistentSourceError, match="Name 'shared_1' already holds step"
+ ):
+ triple.pod(src("shared_1"))
+ assert snapshot(graph) == before
+ assert {"shared_1", "shared_2"} <= set(graph.nodes)
+
+
+def test_r72_step_cannot_take_previously_captured_input_name(receiver) -> None:
+ graph, _ = receiver
+ source = src("taken")
+ with graph:
+ double.pod(source, label="output")
+ refused(
+ graph,
+ lambda: triple.pod(source, label="taken"),
+ "Name 'taken' already holds source 'dict_v1:taken'; step 'taken' is "
+ "another object under the same name. Use the original object or "
+ "choose a distinct name (ITL-1559).",
+ )
+
+
+CAPTURE_NAME = echo.pod.label
+CAPTURE_KINDS = (
+ "root",
+ "prebuilt",
+ "arrow",
+ "node",
+ "automatic_node",
+ "explicit_slot",
+ "implicit_slot",
+ "foreign_job_node",
+ "foreign_job_slot",
+ "foreign_blueprint_node",
+ "foreign_blueprint_slot",
+ "derived",
+ "cached",
+ "loaded_node",
+)
+FOREIGN_CAPTURE_KINDS = {
+ kind for kind in CAPTURE_KINDS if kind.startswith("foreign")
+} | {"loaded_node"}
+STEP_CAPTURE_KINDS = {"node", "automatic_node"}
+
+
+def claim_named_capture(
+ job: PipelineJob, kind: str, ordinal: int, mode: str, tmp_path: Path
+) -> tuple[StreamProtocol, DictSource | None]:
+ """Offer a stream with the matrix's shared name and return any binding needed for execution."""
+ value = 3 + 5 * ordinal
+ project = SelectDataColumns(["x"])
+ if kind == "root":
+ return src(CAPTURE_NAME, value), None
+ source = src(f"matrix_upstream_{ordinal}", value)
+ if kind == "prebuilt":
+ return project(source), None
+ if kind == "arrow":
+ return raw(source), None
+ if kind == "node":
+ with job:
+ return project(source, label=CAPTURE_NAME), None
+ if kind == "automatic_node":
+ with job:
+ return echo.pod(source), None
+ if kind == "explicit_slot":
+ return SourceNode.from_stream(source, name=CAPTURE_NAME), source
+ if kind == "implicit_slot":
+ stream = raw(source)
+ with job:
+ project(stream, label="claim_implicit_slot")
+ return next(
+ node for node in job.source_pods.values() if node.bound_source is stream
+ ), None
+ if kind == "cached":
+ return CachedSource(
+ src(CAPTURE_NAME, value), cache_database=InMemoryArrowDatabase()
+ ), None
+ foreign_graph = Pipeline("foreign") if "blueprint" in kind else new_job()
+ with foreign_graph:
+ if kind == "derived":
+ echo.pod(source, label=CAPTURE_NAME)
+ elif kind.endswith("_slot"):
+ project(src(CAPTURE_NAME, value), label="upstream")
+ else:
+ project(source, label=CAPTURE_NAME)
+ if kind == "derived":
+ run(cast(PipelineJob, foreign_graph), mode)
+ return foreign_graph.nodes[CAPTURE_NAME].as_source(source_id=CAPTURE_NAME), None
+ if kind == "loaded_node":
+ path = tmp_path / f"foreign-{ordinal}.json"
+ foreign_graph.save(path)
+ foreign_graph = PipelineJob.load(path)
+ return foreign_graph.nodes[CAPTURE_NAME], None
+
+
+CAPTURE_PAIRS = [
+ pytest.param(
+ holder,
+ incoming,
+ False,
+ id=(
+ f"accepted-{holder}-then-{incoming}"
+ if {holder, incoming} <= STEP_CAPTURE_KINDS
+ else f"{holder}-then-{incoming}"
+ ),
+ )
+ for holder in CAPTURE_KINDS
+ for incoming in CAPTURE_KINDS
+] + [
+ pytest.param(
+ kind,
+ kind,
+ True,
+ id=f"same-{kind}" if kind in FOREIGN_CAPTURE_KINDS else f"accepted-same-{kind}",
+ )
+ for kind in CAPTURE_KINDS
+]
+
+
+@pytest.mark.parametrize(("holder", "incoming", "same"), CAPTURE_PAIRS)
+def test_capture_namespace_cross_product(
+ holder: str,
+ incoming: str,
+ same: bool,
+ mode: str,
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from orcapod.pipeline import base
+
+ both_steps = {holder, incoming} <= STEP_CAPTURE_KINDS
+ if not same and not both_steps:
+ # Distinct non-root kinds normally derive different hash suffixes.
+ # Give them the same candidate name without equating their contents.
+ monkeypatch.setattr(
+ base,
+ "slot_name_for",
+ lambda stream: (
+ slot_name_for(stream)
+ if isinstance(stream, base.RootSource)
+ else CAPTURE_NAME
+ ),
+ )
+ job = new_job()
+ held, binding = claim_named_capture(job, holder, 0, mode, tmp_path)
+ if holder in FOREIGN_CAPTURE_KINDS:
+ before = snapshot(job)
+ with pytest.raises(InconsistentSourceError, match="from outside this job"):
+ with job:
+ double.pod(held, label="first_branch")
+ assert snapshot(job) == before
+ return
+
+ with job:
+ double.pod(held, label="first_branch")
+ if same:
+ triple.pod(held, label="second_branch")
+ if not same:
+ assert CAPTURE_NAME in job.nodes
+ if not same:
+ if both_steps:
+ candidate, _ = claim_named_capture(job, incoming, 1, mode, tmp_path)
+ with job:
+ triple.pod(candidate, label="second_branch")
+ else:
+ before = snapshot(job)
+ message = (
+ "from outside this job"
+ if incoming in FOREIGN_CAPTURE_KINDS
+ else "already holds|different sources would take|distinct source objects"
+ )
+ with pytest.raises(
+ (InconsistentSourceError, SourceSlotNameCollisionError), match=message
+ ):
+ candidate, _ = claim_named_capture(job, incoming, 1, mode, tmp_path)
+ with job:
+ triple.pod(candidate, label="second_branch")
+ assert snapshot(job) == before
+
+ if binding is not None:
+ job.bind(sources={CAPTURE_NAME: binding})
+ run(job, mode)
+ # Main returns these values for the accepted same-object cases and for
+ # independently named computations with duplicate step display labels.
+ assert job.first_branch.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [6, 8]
+ if same or both_steps:
+ expected = [9, 12] if same else [24, 27]
+ assert (
+ job.second_branch.as_table(columns={"sort_by_tags": True})[
+ "tripled"
+ ].to_pylist()
+ == expected
+ )
+ else:
+ assert "second_branch" not in job.nodes
+
+
+@pytest.mark.parametrize(
+ "row",
+ [
+ "01",
+ "02",
+ "03",
+ "04",
+ "05",
+ "10",
+ "11",
+ "13",
+ "14",
+ "17",
+ "18-blueprint",
+ "18-job",
+ "29",
+ "32",
+ "34",
+ "39",
+ "40",
+ "41",
+ ],
+)
+def test_public_listings_equal_main(row: str) -> None:
+ baseline = Path(__file__).with_name("fixtures") / "itl_1559_capture"
+ path = baseline / f"{row}.json"
+ expected = json.loads((baseline / f"{row}.listings.json").read_text())
+ if "orcapod_pipeline_job_version" in json.loads(path.read_text()):
+ graph = PipelineJob.load(path, database=InMemoryArrowDatabase())
+ else:
+ graph = Pipeline.load(path)
+ assert listings(graph) == expected
+ assert sorted(node.label for node in graph.dag) == expected["dag_nodes"]
+ assert (
+ sorted(node.label for node in graph.dag.topological_sort())
+ == expected["dag_nodes"]
+ )
+ for label, node in graph.nodes.items():
+ assert getattr(graph, label) is node
+ assert any(listed is node for listed in graph.dag.nodes())
+ assert node in graph.dag
+ assert node in graph.dag.nodes()
+
+
+@pytest.mark.parametrize(
+ "kind",
+ ["different", "same_object", "equal_objects", "unbound", "mixed"],
+)
+def test_public_equality_equals_main(kind: str) -> None:
+ source = src()
+ first = None if kind == "unbound" else source
+ second = {
+ "different": src("other", 7),
+ "same_object": source,
+ "equal_objects": src(),
+ "unbound": None,
+ "mixed": None,
+ }[kind]
+ left, right = instance(first).output, instance(second).output
+ same_content = kind in {"same_object", "equal_objects", "unbound"}
+ assert (left == right) == same_content
+ assert (hash(left) == hash(right)) == same_content
+ for node, binding in ((left, first), (right, second)):
+ if binding is None:
+ with pytest.raises(UnboundSourceError):
+ node.content_hash()
+ digest = node.node_hash()
+ else:
+ digest = node.content_hash()
+ assert hash(node) == hash(digest.to_int())
+
+
+def test_refusals_record_nothing() -> None:
+ source = src()
+ with new_job() as job:
+ double.pod(source, label="before")
+ refused(
+ job,
+ lambda: triple.pod(src(), label="refused"),
+ "Source 'dict_v1:a' has distinct source objects with one content hash "
+ "in step 'before' and step 'refused'. Build the source once and reuse the object. "
+ "If the source ID contributes to the hash, give each source its own source_id.",
+ )
+ triple.pod(source, label="after")
+ assert set(job.nodes) == {"a", "before", "after"}
+ assert job.sources["a"] is source
+
+
+@pytest.mark.parametrize("kind", [Pipeline, PipelineJob])
+def test_r39_automatic_step_shares_its_new_slot_name(
+ kind: type[Pipeline] | type[PipelineJob], mode: str
+) -> None:
+ source = src(double.pod.label)
+ with Pipeline("automatic") if kind is Pipeline else new_job() as graph:
+ double.pod(source)
+ name = double.pod.label
+ step, slot = (
+ (f"{name}_1", f"{name}_2") if kind is Pipeline else (f"{name}_2", f"{name}_1")
+ )
+ assert isinstance(graph.nodes[slot], (SourceNode, SourceJobNode))
+ assert graph.nodes[step].upstreams[0] is graph.nodes[slot]
+ job = (
+ PipelineJob.from_pipeline(
+ graph, database=InMemoryArrowDatabase(), sources={name: source}
+ )
+ if isinstance(graph, Pipeline)
+ else graph
+ )
+ run(job, mode)
+ assert job.nodes[step].as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [6, 8]
+
+
+@pytest.mark.parametrize("outer_kind", [Pipeline, PipelineJob])
+@pytest.mark.parametrize("inner_kind", [Pipeline, PipelineJob])
+def test_r71_stacked_capture_refuses_without_recording(outer_kind, inner_kind) -> None:
+ outer = outer_kind("outer", auto_compile=False)
+ inner = inner_kind("inner", auto_compile=False)
+ slot = SourceNode.from_stream(src(), name="slot")
+ before_outer = snapshot(outer)
+ with outer, inner:
+ refused(
+ inner,
+ lambda: double.pod(slot, label="refused"),
+ foreign(graph="job" if inner_kind is PipelineJob else "pipeline"),
+ )
+ assert snapshot(outer) == before_outer
+ with inner:
+ double.pod(slot, label="accepted")
+ inner.compile()
+ assert set(inner.nodes) == {"slot", "accepted"}
+
+
+@pytest.mark.parametrize("entry", ["from_pipeline", "bind", "setter"])
+@pytest.mark.parametrize(
+ "collision",
+ [
+ "slot_step",
+ "same_object",
+ "equal_prebuilt",
+ "equal_raw",
+ "distinct_prebuilt",
+ "distinct_raw",
+ ],
+)
+def test_bind_namespace_cross_product(entry: str, collision: str, mode: str) -> None:
+ source = src("replacement")
+ original = src("a", 8)
+ distinct = collision.startswith("distinct")
+ other = src("other", 11) if distinct else source
+ if collision == "slot_step":
+ replacement, bound_b = source, double.pod(source)
+ elif collision.endswith("prebuilt"):
+ replacement, bound_b = (
+ SelectDataColumns(["x"])(source),
+ SelectDataColumns(["x"])(other),
+ )
+ elif collision.endswith("raw"):
+ replacement, bound_b = raw(source), raw(other)
+ else:
+ replacement = bound_b = source
+
+ db = InMemoryArrowDatabase()
+ with Pipeline("late_collision") as graph:
+ a = SourceNode.from_stream(original, name="a")
+ b = SourceNode.from_stream(bound_b, name="b")
+ inside = double.pod(a, label="inside")
+ plus.pod(inside, label="after_inside")
+ (plus if collision == "slot_step" else triple).pod(b, label="after_outside")
+
+ def message(a_name: str, b_name: str) -> str:
+ if collision == "slot_step":
+ return (
+ f"Slot {b_name!r} and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559)."
+ )
+ first, second = sorted((a_name, b_name))
+ if collision == "same_object":
+ return (
+ f"Source 'dict_v1:replacement' would be read by slots {first!r} and {second!r}. "
+ "One source object on two slots is not supported yet (ITL-1559, "
+ "step 6). Read it through one slot and branch from that slot."
+ )
+ return (
+ f"Slots {first!r} and {second!r} share a legacy execution identity. Bind distinct "
+ "sources to the slots, or read through one slot and branch from it (ITL-1559)."
+ )
+
+ if entry == "from_pipeline":
+
+ def instantiate() -> PipelineJob:
+ return PipelineJob.from_pipeline(
+ graph, sources={"a": replacement, "b": bound_b}, database=db
+ )
+
+ if not distinct:
+ refused(graph, instantiate, message("a", "b"))
+ return
+ job = instantiate()
+ else:
+ with new_job() as job:
+ inside = double.pod(original, label="inside")
+ plus.pod(inside, label="after_inside")
+ (plus if collision == "slot_step" else triple).pod(
+ bound_b, label="after_outside"
+ )
+ slot_a = job.a
+ slot_b = next(
+ slot for slot in job.source_pods.values() if slot.bound_source is bound_b
+ )
+ before_times = (slot_a.last_modified, slot_b.last_modified)
+
+ def bind() -> None:
+ if entry == "bind":
+ job.bind(sources={"a": replacement}, database=db)
+ else:
+ slot_a.bound_source = replacement
+
+ if distinct:
+ bind()
+ else:
+ refused(job, bind, message("a", slot_b.name))
+ assert slot_a.bound_source is original and slot_b.bound_source is bound_b
+ assert (slot_a.last_modified, slot_b.last_modified) == before_times
+ assert job.database is not db
+
+ run(job, mode)
+ assert job.after_inside.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == ([7, 9] if distinct else [17, 19])
+ if collision == "slot_step":
+ assert job.after_outside.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == [7, 9]
+ else:
+ assert job.after_outside.as_table(columns={"sort_by_tags": True})[
+ "tripled"
+ ].to_pylist() == ([33, 36] if distinct else [9, 12])
+
+
+@pytest.mark.parametrize("entry", ["bind", "setter"])
+def test_r67_rebind_checks_current_step_identity(entry: str, mode: str) -> None:
+ original = src("a", 8)
+ replacement = src("replacement")
+ outside = double.pod(src("independent", 11))
+ with new_job() as job:
+ inside = double.pod(original, label="inside")
+ plus.pod(inside, label="after_inside")
+ plus.pod(outside, label="after_outside")
+ _ = job.inside.content_hash() # Warm the identity before replacing its input.
+ job.bind(sources={"a": replacement})
+ slot = next(
+ slot for slot in job.source_pods.values() if slot.bound_source is outside
+ )
+ alias = double.pod(replacement)
+
+ def bind() -> None:
+ if entry == "bind":
+ job.bind(sources={slot.name: alias})
+ else:
+ slot.bound_source = alias
+
+ refused(
+ job,
+ bind,
+ f"Slot {slot.name!r} and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559).",
+ )
+ run(job, mode)
+ assert job.after_inside.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == [7, 9]
+ assert job.after_outside.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == [23, 25]
+
+
+@pytest.mark.parametrize("recording", [False, True], ids=["outside", "inside"])
+@pytest.mark.parametrize(
+ ("entry", "compiled"),
+ [
+ pytest.param("bind", False, id="uncompiled-bind"),
+ ("bind", True),
+ ("setter", True),
+ ],
+)
+def test_r67_binding_checks_pending_capture(
+ entry: str, recording: bool, compiled: bool
+) -> None:
+ left, right = src("left", 3), src("right", 8)
+ outside = double.pod(left)
+ job = PipelineJob("pending", database=InMemoryArrowDatabase(), auto_compile=False)
+ with job:
+ _ = plus.pod(double.pod(SourceNode.from_stream(right, name="root")))
+ if compiled:
+ job.compile()
+ slot = job.source_pods.get("root")
+ database = job.database
+ modified = slot.last_modified if slot is not None else None
+ with job:
+ _ = plus.pod(outside, label="after_outside")
+
+ def change() -> None:
+ if entry == "bind":
+ job.bind(sources={"root": left}, database=InMemoryArrowDatabase())
+ else:
+ assert slot is not None
+ slot.bound_source = left
+
+ with job if recording else nullcontext():
+ roles = deepcopy(vars(vars(job)["_execution_roles"]))
+ refused(
+ job,
+ change,
+ f"Slot {slot_name_for(outside)!r} and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559).",
+ )
+ if slot is not None:
+ assert slot.bound_source is None
+ assert slot.last_modified == modified
+ assert job.database is database
+ assert vars(vars(job)["_execution_roles"]) == roles
+ assert vars(job)["_pending_source_slots"] == {}
+ assert vars(job)["_rebound_source_keys"] == set()
+ job.bind(sources={"root": right})
+ job.compile()
+ assert job.source_pods["root"].bound_source is right
+
+
+@pytest.mark.parametrize("recording", [False, True], ids=["outside", "inside"])
+def test_r67_instantiation_checks_bound_execution_roles(recording: bool) -> None:
+ left, right = src("left", 3), src("right", 8)
+ example = double.pod(right)
+ with Pipeline("instantiate") as blueprint:
+ root = SourceNode.from_stream(right, name="root")
+ outside = SourceNode.from_stream(example, name="outside")
+ _ = plus.pod(double.pod(root))
+ _ = plus.pod(outside, label="after_outside")
+ alias = double.pod(left)
+ with new_job() if recording else nullcontext() as receiver:
+ before = snapshot(receiver) if receiver is not None else None
+ refused(
+ blueprint,
+ lambda: PipelineJob.from_pipeline(
+ blueprint, sources={"root": left, "outside": alias}
+ ),
+ "Slot 'outside' and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559).",
+ )
+ if receiver is not None:
+ assert snapshot(receiver) == before
+
+
+@pytest.mark.parametrize("recording", [False, True], ids=["outside", "inside"])
+def test_r67_load_checks_restored_execution_roles(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, recording: bool
+) -> None:
+ from orcapod.pipeline import serialization
+
+ source = src()
+ with new_job() as job:
+ _ = double.pod(source, label="result")
+ path = tmp_path / "job.json"
+ job.save(path)
+ saved = json.loads(path.read_text())
+ saved["run"]["node_job_content_hashes"]["result"] = (
+ source.content_hash().to_string()
+ )
+ _ = path.write_text(json.dumps(saved))
+ monkeypatch.setattr(serialization, "resolve_source_from_config", lambda _: source)
+ with job if recording else nullcontext():
+ refused(
+ job,
+ lambda: PipelineJob.load(path),
+ "Slot 'a' and an in-graph step share a legacy execution identity. "
+ "Capture the step inside the graph and reuse its output (ITL-1559).",
+ )
+
+
+@pytest.mark.parametrize(
+ ("receiver_kind", "entry"),
+ [
+ ("pipeline", "capture"),
+ ("job", "capture"),
+ ("pipeline", "construct"),
+ ("pipeline", "bind"),
+ ("job", "bind"),
+ ("pipeline", "setter"),
+ ("job", "setter"),
+ ],
+)
+@pytest.mark.parametrize("form", ["source", "prebuilt", "declaration"])
+@pytest.mark.parametrize("names", ["inferred", "explicit", "mixed"])
+@pytest.mark.parametrize("equal", [False, True], ids=["distinct", "equal"])
+@pytest.mark.parametrize("reverse", [False, True], ids=["forward", "reverse"])
+def test_execution_identity_matrix(
+ receiver_kind: str,
+ entry: str,
+ form: str,
+ names: str,
+ equal: bool,
+ reverse: bool,
+ mode: str,
+) -> None:
+ """Each accepted branch must yield main's rows, including downstream."""
+ roots = (
+ src("left", 3),
+ src("left", 3) if equal and form == "source" else src("right", 8),
+ )
+ streams: tuple[StreamProtocol, StreamProtocol]
+ if form == "source":
+ streams = roots
+ else:
+ projection = SelectDataColumns(["x"])
+ streams = (
+ projection(roots[0], label="left_prebuilt"),
+ projection(roots[0] if equal else roots[1], label="right_prebuilt"),
+ )
+ assert (streams[0].content_hash() == streams[1].content_hash()) == equal
+ graph: Pipeline | PipelineJob = (
+ Pipeline("identity_matrix") if receiver_kind == "pipeline" else new_job()
+ )
+ database = InMemoryArrowDatabase()
+ order = (1, 0) if reverse else (0, 1)
+ requested_names = (
+ "left_explicit" if names in ("explicit", "mixed") else None,
+ "right_explicit" if names == "explicit" else None,
+ )
+ # A bind replaces values under existing names. Use independent template
+ # bindings so even two equal roots can be offered to distinct inferred slots.
+ templates = (
+ (src("template_left"), src("template_right"))
+ if form == "source"
+ else (streams[0], SelectDataColumns(["x"])(roots[1], label="template_right"))
+ )
+ source_slots: dict[str, StreamProtocol] = {}
+ case = "legacy execution identity|with one content hash|same source|already holds"
+
+ def record(index: int) -> None:
+ stream = streams[index] if entry == "capture" else templates[index]
+ explicit = requested_names[index]
+ if entry != "capture" or form == "declaration" or explicit is not None:
+ stream = SourceNode.from_stream(stream, name=explicit)
+ name = stream.name if isinstance(stream, SourceNode) else slot_name_for(stream)
+ double_value = double.pod(stream, label=f"double_{index}")
+ _ = plus.pod(double_value, label=f"result_{index}")
+ source_slots[name] = streams[index]
+
+ with graph:
+ record(order[0])
+ before_capture = snapshot(graph)
+ try:
+ record(order[1])
+ except InconsistentSourceError as exc:
+ assert equal and entry == "capture"
+ assert re.search(case, str(exc))
+ assert snapshot(graph) == before_capture
+ return
+
+ if entry == "construct" or entry == "capture" and isinstance(graph, Pipeline):
+ assert isinstance(graph, Pipeline)
+ before = snapshot(graph)
+ if equal:
+ with pytest.raises(InconsistentSourceError, match=case):
+ _ = PipelineJob.from_pipeline(
+ graph, sources=source_slots, database=database
+ )
+ assert snapshot(graph) == before
+ return
+ job = PipelineJob.from_pipeline(graph, sources=source_slots, database=database)
+ else:
+ job = (
+ graph
+ if isinstance(graph, PipelineJob)
+ else PipelineJob.from_pipeline(graph, database=database)
+ )
+ pending = {
+ name: source
+ for name, source in source_slots.items()
+ if name not in job.sources
+ }
+ if entry == "setter":
+ name = next(iter(pending))
+ job.source_pods[name].bound_source = pending.pop(name)
+ before = snapshot(job)
+ before_bindings = [
+ (slot.bound_source, slot.last_modified) for slot in job.source_pods.values()
+ ]
+
+ def bind() -> None:
+ if entry == "setter":
+ name, source = next(iter(pending.items()))
+ job.source_pods[name].bound_source = source
+ else:
+ job.bind(sources=pending)
+
+ if equal:
+ with pytest.raises(InconsistentSourceError, match=case):
+ bind()
+ assert snapshot(job) == before
+ for slot, (source, modified) in zip(
+ job.source_pods.values(), before_bindings, strict=True
+ ):
+ assert slot.bound_source is source and slot.last_modified == modified
+ return
+ bind()
+
+ run(job, mode)
+ for index, expected in enumerate(([7, 9], [17, 19])):
+ assert (
+ job.nodes[f"result_{index}"]
+ .as_table(columns={"sort_by_tags": True})["plus"]
+ .to_pylist()
+ == expected
+ )
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("declaration_first", [False, True])
+@pytest.mark.parametrize("example_kind", ["matching_example", "schemas_only"])
+@pytest.mark.parametrize("bind_together", [False, True])
+def test_r75_schema_only_slot_binds_independently(
+ mode: str, declaration_first: bool, example_kind: str, bind_together: bool
+) -> None:
+ left, right = src("left"), src("right", 8)
+ example = SourceNode.from_stream(double.pod(left), name="declared")
+ declaration = (
+ example
+ if example_kind == "matching_example"
+ else SourceNode(
+ name="declared",
+ tag_schema=example.tag_schema,
+ data_schema=example.data_schema,
+ )
+ )
+
+ def capture_inside() -> None:
+ plus.pod(double.pod(left, label="inside"), label="after_inside")
+
+ def capture_declared() -> None:
+ plus.pod(declaration, label="after_declared")
+
+ with Pipeline("declared_example") as graph:
+ captures = (capture_inside, capture_declared)
+ for capture in reversed(captures) if declaration_first else captures:
+ capture()
+
+ bindings = {"left": left, "declared": double.pod(right)}
+ job = PipelineJob.from_pipeline(
+ graph,
+ database=InMemoryArrowDatabase(),
+ sources=bindings if bind_together else None,
+ )
+ if not bind_together:
+ assert not job.sources
+ job.bind(sources={"left": bindings["left"]})
+ job.bind(sources={"declared": bindings["declared"]})
+ assert (asyncio.run(job.run_async()) if mode == "async" else job.run()).ok
+ assert job.after_inside.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == [7, 9]
+ assert job.after_declared.as_table(columns={"sort_by_tags": True})[
+ "plus"
+ ].to_pylist() == [17, 19]
+
+
+@pytest.mark.parametrize("branches", [32, 64])
+def test_r77_capture_reads_each_invocation_a_constant_number_of_times(
+ monkeypatch: pytest.MonkeyPatch, branches: int
+) -> None:
+ slot_visits = step_visits = 0
+ prepare = ExecutionRoles.prepare
+
+ def count(
+ index: ExecutionRoles,
+ slots: Iterable[tuple[str, str | None]],
+ step_key: str | None = None,
+ step_role: str | None = None,
+ ) -> Callable[[], None]:
+ nonlocal slot_visits, step_visits
+ proposed = tuple(slots)
+ slot_visits += len(proposed)
+ step_visits += step_key is not None
+ return prepare(index, proposed, step_key, step_role)
+
+ monkeypatch.setattr(ExecutionRoles, "prepare", count)
+ with PipelineJob("visits", auto_compile=False) as graph:
+ for i in range(branches):
+ double.pod(src(f"source_{i}"), label=f"step_{i}")
+ assert len(vars(graph)["_capture_graph"]) == 2 * branches
+ assert (slot_visits, step_visits) == (branches, branches)
+
+
+@pytest.mark.parametrize(
+ "database_argument", ["database", "result_database", "result_database_only"]
+)
+@pytest.mark.parametrize("compiled_prefix", [False, True])
+@pytest.mark.parametrize("recording", [False, True], ids=["outside", "inside"])
+def test_r79_pending_bind_storage_refusal_is_atomic(
+ tmp_path: Path, database_argument: str, compiled_prefix: bool, recording: bool
+) -> None:
+ from orcapod.databases import ConnectorArrowDatabase, SQLiteConnector
+ from orcapod.errors import UnstorableColumnError
+ from orcapod.pipeline.execution_context import ExecutionContext
+
+ original = (
+ None if database_argument == "result_database_only" else InMemoryArrowDatabase()
+ )
+ incompatible = ConnectorArrowDatabase(
+ SQLiteConnector(str(tmp_path / "bind.sqlite"))
+ )
+ job = PipelineJob("atomic", database=original, auto_compile=False)
+ if compiled_prefix:
+ with job:
+ _ = SelectDataColumns(["x"])(src("prefix"), label="prefix_step")
+ job.compile()
+
+ left, right = src("left"), src("right", 8)
+ first, second = src("first", 4), src("second", 12)
+ with job:
+ _ = SelectDataColumns(["x"])(
+ SourceNode.from_stream(first, name="other"), label="other_step"
+ )
+ _ = double.pod(SourceNode.from_stream(left, name="root"), label="answer")
+
+ def state() -> tuple[object, ...]:
+ private = vars(job)
+ return (
+ snapshot(job),
+ job.database,
+ job.result_database,
+ job.execution_context,
+ private["_compiled"],
+ job.last_run,
+ tuple(
+ (
+ name,
+ id(slot),
+ slot.last_modified,
+ slot.bound_source,
+ slot.binding_generation,
+ )
+ for name, slot in job.source_pods.items()
+ ),
+ deepcopy(vars(private["_execution_roles"])),
+ dict(private["_pending_source_slots"]),
+ dict(private["_sources_as_captured"]),
+ set(private["_rebound_source_keys"]),
+ dict(private["_unresolved_sources"]),
+ private["_unresolved_database"],
+ private["_unresolved_result_database"],
+ private["_node_database_views"],
+ )
+
+ replacement: dict[str, StreamProtocol] = {"other": second, "root": right}
+ if compiled_prefix:
+ replacement["prefix"] = src("replacement_prefix", 16)
+ context = ExecutionContext()
+ with job if recording else nullcontext():
+ before = state()
+ with pytest.raises(UnstorableColumnError, match="answer"):
+ if database_argument == "database":
+ job.bind(replacement, database=incompatible, execution_context=context)
+ else:
+ job.bind(
+ replacement, result_database=incompatible, execution_context=context
+ )
+ assert state() == before
+ job.bind(replacement, database=InMemoryArrowDatabase())
+ job.compile()
+ assert job.source_pods["root"].bound_source is right
+ assert job.source_pods["other"].bound_source is second
+ assert job.run().ok
+
+
+@pytest.mark.parametrize(
+ "graph",
+ [blueprint, lambda: instance(src("bound"))],
+ ids=["blueprint", "bound-job"],
+)
+def test_object_membership_requires_label_access(
+ graph: Callable[[], Pipeline | PipelineJob],
+) -> None:
+ pipeline = graph()
+ for operand in (
+ src("unrelated"),
+ blueprint().output,
+ pipeline.to_invocations().invocations[0],
+ ):
+ for collection in (pipeline.dag, pipeline.dag.nodes(), pipeline.nodes):
+ with pytest.raises(
+ UndefinedGraphMembershipError,
+ match=r"membership is not defined yet.*nodes\[label\]",
+ ):
+ _ = operand in collection # pyright: ignore[reportOperatorIssue] # intentionally pass objects to the membership API
+
+ with pytest.raises(UndefinedGraphMembershipError):
+ _ = pipeline.output in pipeline.nodes
+ assert "output" in pipeline.nodes
+ assert "unknown" not in pipeline.nodes
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+def test_public_graph_attribute_is_removed(receiver) -> None:
+ graph = receiver("graph-api")
+ with pytest.raises(AttributeError):
+ _ = getattr(graph, "graph")
+ with graph:
+ _ = double.pod(src(), label="output")
+ with pytest.raises(AttributeError):
+ _ = getattr(graph, "graph")
+ assert graph.nodes["output"] is graph.output
+ assert len(graph.dag.predecessors(graph.output)) == 1
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+def test_r80_public_dag_vertex_operations_match_main(receiver) -> None:
+ graph = receiver("vertex-api")
+ with graph:
+ double.pod(src(), label="output")
+ dag = graph.dag
+ vertices = cast("Any", dag.nodes())
+ output = graph.output
+ # Main's OrcaDAG returns the keys of its node-attribute dictionary.
+ expected = {node: dag.node_attrs(node) for node in dag}.keys()
+ other_view = cast("Any", dag.nodes())
+ assert len(dag) == len(vertices) == len(expected)
+ assert list(dag) == list(vertices) == list(expected)
+ assert list(reversed(vertices)) == list(reversed(expected))
+ assert vertices.mapping == expected.mapping
+ assert repr(vertices) == repr(expected)
+ assert output in dag
+ assert output in vertices
+ assert nx.is_simple_path(dag, [output])
+
+ for operand in ({output}, list(expected), expected, other_view):
+ oracle = expected if operand is other_view else operand
+ for operation in (operator.and_, operator.or_, operator.sub, operator.xor):
+ assert operation(vertices, operand) == operation(expected, oracle)
+ if isinstance(operand, list):
+ continue
+ result = operation(operand, vertices)
+ assert type(result) is set
+ assert result == operation(oracle, expected)
+ assert vertices.isdisjoint(operand) == expected.isdisjoint(oracle)
+ if isinstance(operand, list):
+ continue
+ for operation in (
+ operator.eq,
+ operator.ne,
+ operator.le,
+ operator.lt,
+ operator.ge,
+ operator.gt,
+ ):
+ assert operation(vertices, operand) == operation(expected, oracle)
+ assert operation(operand, vertices) == operation(oracle, expected)
+ assert vertices.isdisjoint([])
+ assert (vertices & iter([output])) == {output}
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+@pytest.mark.parametrize("form", ["invocation", "node"])
+@pytest.mark.parametrize("edit", ["node", "incoming", "outgoing"])
+def test_r81_public_dag_rejects_foreign_insertions(receiver, form, edit) -> None:
+ graph = receiver("receiver")
+ with graph:
+ double.pod(src(), label="output")
+ with Pipeline("other") as other:
+ invocation = double.pod(src("slot"), label="external")
+ outside = invocation if form == "invocation" else other.external
+ before = snapshot(graph)
+ dag = graph.dag
+ with pytest.raises(TypeError, match="read-only.*pipeline API"):
+ if edit == "node":
+ dag.add_node(outside)
+ elif edit == "incoming":
+ dag.add_edge(outside, graph.output)
+ else:
+ dag.add_edge(graph.output, outside)
+ assert snapshot(graph) == before
+ with graph:
+ refused(
+ graph,
+ lambda: plus.pod(outside),
+ foreign(graph="job" if receiver is PipelineJob else "pipeline"),
+ )
+
+
+@pytest.mark.parametrize("adapter", [OrcaDAG, NetworkxBackend])
+def test_standalone_dag_distinguishes_bound_job_nodes(adapter) -> None:
+ template = blueprint()
+ left = PipelineJob.from_pipeline(template, sources={"slot": src("left")})
+ right = PipelineJob.from_pipeline(template, sources={"slot": src("right", 9)})
+ first, second = left.output, right.output
+ assert first != second
+
+ dag = adapter()
+ dag.add_node(first, branch="left")
+ dag.add_node(second, branch="right")
+ assert len(dag) == 2
+ assert first in dag and second in dag
+ assert dag.node_attrs(first) == {"branch": "left"}
+ assert dag.node_attrs(second) == {"branch": "right"}
+ dag.add_edge(first, second)
+ [(upstream, downstream)] = list(dag.edges())
+ assert upstream is first and downstream is second
+ assert dag.node_attrs(first) == {"branch": "left"}
+ assert dag.node_attrs(second) == {"branch": "right"}
+
+ edged = adapter()
+ edged.add_edge(first, second)
+ assert len(edged) == 2
+ assert list(edged.successors(first)) == [second]
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("kind", ["function", "operator"])
+@pytest.mark.parametrize("receiver", ["pipeline", "job"])
+@pytest.mark.parametrize("replacement", ["foreign", "fresh", "held"])
+def test_compiled_upstream_setter_preserves_captured_edges(
+ mode: str, kind: str, receiver: str, replacement: str
+) -> None:
+ source = src("left")
+ alternate = src("right", 10)
+ with new_job() as foreign_job:
+ echo.pod(alternate, label="foreign")
+ graph = Pipeline("blueprint") if receiver == "pipeline" else new_job()
+ with graph:
+ if kind == "function":
+ double.pod(source, label="result")
+ column, expected = "doubled", [6, 8]
+ else:
+ SelectDataColumns(["x"])(source, label="result")
+ column, expected = "x", [3, 4]
+ echo.pod(alternate, label="alternate")
+ before = snapshot(graph)
+ held = graph.result.upstreams
+ graph.result.upstreams = held
+ incoming = {
+ "foreign": foreign_job.foreign,
+ "fresh": src("fresh", 20),
+ "held": graph.right,
+ }[replacement]
+ message = "from outside this" if replacement == "foreign" else "Cannot rewire"
+ with pytest.raises(InconsistentSourceError, match=message):
+ graph.result.upstreams = (incoming,)
+ assert graph.result.upstreams[0] is held[0]
+ assert snapshot(graph) == before
+ job = (
+ graph
+ if isinstance(graph, PipelineJob)
+ else PipelineJob.from_pipeline(
+ graph,
+ sources={"left": source, "right": alternate},
+ database=InMemoryArrowDatabase(),
+ )
+ )
+ run(job, mode)
+ assert (
+ job.result.as_table(columns={"sort_by_tags": True})[column].to_pylist()
+ == expected
+ )
+
+
+@pytest.mark.parametrize("receiver", ["loaded-blueprint", "loaded-job", "derived"])
+@pytest.mark.parametrize("kind", ["function", "operator"])
+def test_restored_and_derived_setters_refuse_foreign_edges(
+ receiver: str, kind: str, tmp_path: Path
+) -> None:
+ with Pipeline("blueprint") as graph:
+ if kind == "function":
+ double.pod(src("left"), label="result")
+ else:
+ SelectDataColumns(["x"])(src("left"), label="result")
+ with new_job() as foreign_job:
+ echo.pod(src("foreign"), label="other")
+
+ path = tmp_path / "graph.json"
+ restored: Pipeline | PipelineJob
+ if receiver == "loaded-blueprint":
+ graph.save(path)
+ restored = Pipeline.load(path)
+ else:
+ job = PipelineJob.from_pipeline(graph)
+ if receiver == "loaded-job":
+ job.save(path)
+ restored = PipelineJob.load(path, database=InMemoryArrowDatabase())
+ else:
+ restored = job.as_pipeline()
+ held = restored.result.upstreams
+ before = snapshot(restored)
+ with pytest.raises(InconsistentSourceError, match="from outside this"):
+ restored.result.upstreams = (foreign_job.other,)
+ assert restored.result.upstreams[0] is held[0]
+ assert snapshot(restored) == before
+
+
+def test_blueprint_refuses_reserved_names_in_bound_proxy_schema() -> None:
+ source = ArrowTableSource(
+ pa.table({"x": [3, 4]}), source_id="proxy", infer_nullable=True
+ )
+ proxy = SourceProxy(
+ source.source_id,
+ source.content_hash().to_string(),
+ source.pipeline_hash().to_string(),
+ *source.output_schema(columns={"system_tags": True}),
+ )
+ proxy.bind(source)
+ graph = Pipeline("blueprint")
+ before = snapshot(graph)
+ with graph, pytest.raises(ReservedColumnNameError):
+ double.pod(proxy, label="result")
+ assert snapshot(graph) == before
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+def test_refused_import_preserves_the_callers_declaration_and_descriptor(
+ receiver,
+) -> None:
+ with Pipeline("foreign") as foreign:
+ double.pod(src("foreign_slot"), label="foreign_output")
+ with new_job() as foreign_job:
+ echo.pod(src("foreign_job_slot"), label="foreign_output")
+
+ original = src("original")
+ descriptor = OperatorNode if receiver is Pipeline else OperatorJobNode
+ select = SelectDataColumns(["x"])
+ outside = descriptor(select, (original,))
+ declaration = SourceNode.from_stream(src("declared"), name="decl")
+ graph = InvocationGraph(
+ (
+ OperatorInvocation(select, (outside,), label="external"),
+ OperatorInvocation(select, (declaration,), label="first"),
+ OperatorInvocation(select, (foreign.foreign_output,), label="second"),
+ ),
+ {},
+ )
+ # Keep the failed receiver alive through the traceback when checking for leaks.
+ with pytest.raises(InconsistentSourceError, match="from outside this") as error:
+ receiver.from_invocations(graph)
+ assert error.traceback
+ outside.upstreams = (foreign_job.foreign_output,)
+ outside.upstreams = (original,)
+
+ with Pipeline("retry") as retry:
+ double.pod(declaration, label="first")
+ assert "first" in retry.nodes
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("kind", ["function", "operator"])
+def test_compiled_upstream_setter_refuses_foreign_job_node(mode, kind) -> None:
+ source = src()
+ with new_job() as job:
+ step = double.pod(source, label="first")
+ if kind == "function":
+ plus.pod(step, label="result")
+ column, expected = "plus", [7, 9]
+ else:
+ SelectDataColumns(["doubled"])(step, label="result")
+ column, expected = "doubled", [6, 8]
+
+ with new_job() as foreign:
+ double.pod(source, label="other")
+
+ before = snapshot(job)
+ with pytest.raises(InconsistentSourceError, match="from outside this job"):
+ job.result.upstreams = (foreign.other,)
+ assert snapshot(job) == before
+ assert job.result.upstreams[0] is job.first
+ run(job, mode)
+ assert (
+ job.result.as_table(columns={"sort_by_tags": True})[column].to_pylist()
+ == expected
+ )
+
+
+class CustomSourceNode(SourceNode):
+ pass
+
+
+class CustomSourceJobNode(SourceJobNode):
+ pass
+
+
+class CustomPipeline(Pipeline):
+ source_node_class = CustomSourceNode
+
+
+class CustomPipelineJob(PipelineJob):
+ source_node_class = CustomSourceJobNode
+
+
+def test_custom_blueprint_factory_refuses_held_compiled_step() -> None:
+ with CustomPipeline("custom") as graph:
+ first = double.pod(src("root"), label="first")
+ assert isinstance(graph.root, CustomSourceNode)
+ with graph:
+ refused(
+ graph,
+ lambda: plus.pod(graph.first, label="second"),
+ "Capturing compiled blueprint step 'first' is not supported yet "
+ "(ITL-1559). Pass the original invocation stream to add a downstream step.",
+ )
+ plus.pod(first, label="second")
+ assert graph.dag.predecessors(graph.second) == {graph.first}
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_custom_blueprint_factory_allows_separate_declarations(mode: str) -> None:
+ example = src("example")
+ with CustomPipeline("custom") as graph:
+ double.pod(SourceNode.from_stream(example, name="left"), label="first")
+ double.pod(SourceNode.from_stream(example, name="right"), label="second")
+ job = CustomPipelineJob.from_pipeline(
+ graph,
+ sources={"left": src("left"), "right": src("right", 9)},
+ database=InMemoryArrowDatabase(),
+ )
+ assert isinstance(job.left, CustomSourceJobNode)
+ assert isinstance(job.right, CustomSourceJobNode)
+ run(job, mode)
+ assert job.first.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [6, 8]
+ assert job.second.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [18, 20]
+
+
+def test_custom_job_factory_keeps_foreign_job_diagnostic() -> None:
+ owner = instance(src("root"))
+ with CustomPipelineJob("custom") as graph:
+ refused(graph, lambda: plus.pod(owner.output), foreign(graph="job"))
+
+
+@pytest.mark.parametrize("kind", ["function", "operator", "side_effect"])
+def test_stacked_capture_runs_public_preflight(kind: str) -> None:
+ class ValidatingPipeline(Pipeline):
+ def prepare_invocation(self, invocation: PodInvocation) -> Callable[[], None]:
+ if invocation.label == "blocked":
+ raise ValueError("Blocked by the capture policy")
+ return super().prepare_invocation(invocation)
+
+ first, second = Pipeline("first"), ValidatingPipeline("second")
+ before = snapshot(first), snapshot(second)
+ source = src("example")
+ with (
+ first,
+ second,
+ pytest.raises(ValueError, match="Blocked by the capture policy"),
+ ):
+ if kind == "function":
+ double.pod(source, label="blocked")
+ elif kind == "operator":
+ SelectDataColumns(["x"])(source, label="blocked")
+ else:
+
+ def deliver(x: int, ctx) -> None:
+ pass
+
+ SideEffectPod(deliver)(source, label="blocked")
+ assert (snapshot(first), snapshot(second)) == before
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_job_binding_refuses_descriptor_rewire_to_live_slot(mode: str) -> None:
+ with Pipeline("template") as graph:
+ double.pod(SourceNode.from_stream(src("example"), name="left"), label="first")
+ double.pod(SourceNode.from_stream(src("other"), name="right"), label="second")
+ external = src("external")
+ descriptor = OperatorJobNode(SelectDataColumns(["x"]), (external,))
+ descriptor.run()
+ job = PipelineJob.from_pipeline(
+ graph,
+ sources={"left": descriptor, "right": src("right", 9)},
+ database=InMemoryArrowDatabase(),
+ )
+ run(job, mode)
+ assert job.first.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [6, 8]
+ before = snapshot(job)
+ with pytest.raises(
+ SourceSpecMismatchError,
+ match="Binding source slot 'left' to a source that depends on source slot 'right'",
+ ):
+ descriptor.upstreams = (job.right,)
+ assert descriptor.upstreams[0] is external
+ assert snapshot(job) == before
+ run(job, mode)
+ assert job.first.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [6, 8]
+
+
+def test_job_binding_refuses_descriptor_rewire_to_owned_invocation() -> None:
+ select = SelectDataColumns(["x"])
+ external = src("external")
+ descriptor = OperatorJobNode(select, (external,))
+ with new_job() as job:
+ double.pod(descriptor, label="first")
+ invocation = select(src("live", 12), label="project")
+
+ before = snapshot(job)
+ with pytest.raises(
+ InconsistentSourceError, match=re.escape(foreign("live", "job"))
+ ):
+ descriptor.upstreams = (invocation,)
+ assert descriptor.upstreams[0] is external
+ assert snapshot(job) == before
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+@pytest.mark.parametrize("kind", ["function", "operator"])
+def test_as_node_wrapper_reports_foreign_slot(receiver, kind: str) -> None:
+ with new_job() as owner:
+ echo.pod(src("function_input"), label="function")
+ SelectDataColumns(["x"])(src("operator_input"), label="operator")
+ wrapper = owner.nodes[kind].as_node()
+ with receiver("receiver") as graph:
+ refused(
+ graph,
+ lambda: double.pod(wrapper),
+ foreign(f"{kind}_input", "job" if receiver is PipelineJob else "pipeline"),
+ )
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("adapter", [OrcaDAG, NetworkxBackend])
+def test_standalone_dag_run_keeps_independent_bindings(mode: str, adapter) -> None:
+ template = blueprint()
+ left = PipelineJob.from_pipeline(
+ template, sources={"slot": src("left")}, database=InMemoryArrowDatabase()
+ )
+ right = PipelineJob.from_pipeline(
+ template, sources={"slot": src("right", 8)}, database=InMemoryArrowDatabase()
+ )
+ graph = adapter()
+ for job in (left, right):
+ graph.add_edge(job.slot, job.output)
+ result = (
+ SyncPipelineOrchestrator().run(graph)
+ if mode == "sync"
+ else asyncio.run(AsyncPipelineOrchestrator().run_async(graph))
+ )
+ assert len(result.node_outputs) == 4
+ for job, expected in ((left, [6, 8]), (right, [16, 18])):
+ table = result.node_outputs[job.output].as_table(columns={"sort_by_tags": True})
+ assert table["doubled"].to_pylist() == expected
+
+
+@pytest.fixture(params=["table", "rows"])
+def executed_slot_output(request: pytest.FixtureRequest) -> StreamProtocol:
+ source = src("root")
+ stream = source if request.param == "table" else raw(source)
+ with new_job() as owner:
+ double.pod(SourceNode.from_stream(stream, name="root"), label="before")
+ owner.bind(sources={"root": stream})
+ output = owner.root.execute()
+ assert isinstance(output, ArrowTableStream) == (request.param == "table")
+ return output
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+def test_executed_foreign_slot_refused_at_capture(
+ receiver, executed_slot_output: StreamProtocol
+) -> None:
+ with receiver("receiver") as graph:
+ refused(
+ graph,
+ lambda: double.pod(executed_slot_output, label="after"),
+ foreign("root", "job" if receiver is PipelineJob else "pipeline"),
+ )
+
+
+@pytest.mark.parametrize("entry", ["from_pipeline", "bind", "setter"])
+def test_executed_foreign_slot_refused_at_binding(
+ entry: str, executed_slot_output: StreamProtocol
+) -> None:
+ template = blueprint()
+ initial = src("initial", 10)
+ job = PipelineJob.from_pipeline(template, sources={"slot": initial})
+ bind = {
+ "from_pipeline": lambda: PipelineJob.from_pipeline(
+ template, sources={"slot": executed_slot_output}
+ ),
+ "bind": lambda: job.bind(sources={"slot": executed_slot_output}),
+ "setter": lambda: setattr(job.slot, "bound_source", executed_slot_output),
+ }[entry]
+ refused(
+ job,
+ bind,
+ "Binding source slot 'slot' to a source that depends on source slot "
+ "'root' is not supported yet (ITL-1559). Pass the underlying source, "
+ "or use a non-slot node's as_source() to read stored results.",
+ SourceSpecMismatchError,
+ )
+ assert job.slot.bound_source is initial
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_detached_binding_descriptor_can_be_rewired(mode: str) -> None:
+ with Pipeline("template") as graph:
+ double.pod(SourceNode.from_stream(src("example"), name="left"), label="first")
+ double.pod(SourceNode.from_stream(src("other"), name="right"), label="second")
+ descriptor = OperatorJobNode(SelectDataColumns(["x"]), (src("external"),))
+ descriptor.run()
+ job = PipelineJob.from_pipeline(
+ graph,
+ sources={"left": descriptor, "right": src("right", 8)},
+ database=InMemoryArrowDatabase(),
+ )
+ run(job, mode)
+ replacement = src("replacement", 15)
+ job.bind(sources={"left": replacement})
+ run(job, mode)
+ assert job.left.bound_source is replacement
+
+ descriptor.upstreams = (job.right,)
+ assert descriptor.upstreams[0] is job.right
+ descriptor.run()
+ assert descriptor.as_table(columns={"sort_by_tags": True})["x"].to_pylist() == [
+ 8,
+ 9,
+ ]
+ run(job, mode)
+ assert job.first.as_table(columns={"sort_by_tags": True})[
+ "doubled"
+ ].to_pylist() == [30, 32]
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+def test_public_dag_refuses_internal_key_strings(receiver) -> None:
+ with receiver("receiver") as graph:
+ double.pod(src("root"), label="after")
+ dag = graph.dag
+ key = graph.after.node_hash().to_string()
+ assert key not in dag
+ assert key not in dag.nodes()
+ assert key not in graph.nodes
+ assert (graph.root, key) not in dag.edges()
+ for query in (
+ dag.node_attrs,
+ dag.predecessors,
+ dag.successors,
+ dag.ancestors,
+ dag.in_degree,
+ ):
+ with pytest.raises(KeyError, match="Pass a DAG vertex object"):
+ _ = query(key)
+ assert graph.root in dag.predecessors(graph.after)
diff --git a/tests/test_pipeline/test_cross_session_miss_tags.py b/tests/test_pipeline/test_cross_session_miss_tags.py
index 0bcee789f..82d9fe625 100644
--- a/tests/test_pipeline/test_cross_session_miss_tags.py
+++ b/tests/test_pipeline/test_cross_session_miss_tags.py
@@ -235,7 +235,10 @@ def test_a_cross_session_miss_keeps_its_stored_tag(
first = _job(database, InMemoryArrowDatabase(), tags, role, config, layout)
summary = first.run(orchestrator=run())
assert {
- label: (summary.nodes[label].computed, summary.nodes[label].reused)
+ label: (
+ summary.nodes[label].computed,
+ summary.nodes[label].reused,
+ )
for label in ("one", "two")
} == {"one": (2, 0), "two": (2, 0)}
presented = {label: _presented(first, label) for label in ("one", "two")}
@@ -304,7 +307,10 @@ def test_a_cross_session_miss_keeps_its_stored_tag(
summary = second.run(orchestrator=run())
recomputed = 2 if scenario == ALL_MISSING else 1
assert {
- label: (summary.nodes[label].computed, summary.nodes[label].reused)
+ label: (
+ summary.nodes[label].computed,
+ summary.nodes[label].reused,
+ )
for label in ("one", "two")
} == {
"one": (recomputed, 2 - recomputed),
diff --git a/tests/test_pipeline/test_current_run_review_fixes.py b/tests/test_pipeline/test_current_run_review_fixes.py
index 25f266174..ebb29422f 100644
--- a/tests/test_pipeline/test_current_run_review_fixes.py
+++ b/tests/test_pipeline/test_current_run_review_fixes.py
@@ -570,7 +570,10 @@ def test_a_run_with_failed_rows_is_retried_by_the_next_run(orchestrator: str) ->
FLAKY["fail"] = False
summary = job.run(orchestrator=ORCHESTRATORS[orchestrator]())
assert CALLS == ["flaky"]
- assert (summary.nodes["node"].computed, summary.nodes["node"].reused) == (1, 5)
+ assert (
+ summary.nodes["node"].computed,
+ summary.nodes["node"].reused,
+ ) == (1, 5)
assert job.nodes["node"].as_table().num_rows == 6
CALLS.clear()
summary = job.run(orchestrator=ORCHESTRATORS[orchestrator]())
diff --git a/tests/test_pipeline/test_dag.py b/tests/test_pipeline/test_dag.py
index 35c355f99..2a457f950 100644
--- a/tests/test_pipeline/test_dag.py
+++ b/tests/test_pipeline/test_dag.py
@@ -543,8 +543,8 @@ def test_dag_predecessors_and_successors(self):
pipeline = self._make_simple_pipeline()
source = next(n for n in pipeline.dag.nodes() if isinstance(n, SourceNode))
fn_node = next(n for n in pipeline.dag.nodes() if isinstance(n, FunctionNode))
- assert pipeline.dag.successors(source) == {fn_node}
- assert pipeline.dag.predecessors(fn_node) == {source}
+ assert set(pipeline.dag.successors(source)) == {fn_node}
+ assert set(pipeline.dag.predecessors(fn_node)) == {source}
def test_dag_raises_before_compile(self):
"""Accessing dag before compile() raises RuntimeError."""
diff --git a/tests/test_pipeline/test_function_node_stored_values.py b/tests/test_pipeline/test_function_node_stored_values.py
index 21e5c98fb..f7ebf012c 100644
--- a/tests/test_pipeline/test_function_node_stored_values.py
+++ b/tests/test_pipeline/test_function_node_stored_values.py
@@ -245,7 +245,10 @@ def test_every_read_of_stored_results_gives_the_tag_exactly(
reuse = _job(database, values)
summary = reuse.run(orchestrator=make())
for label in ("one", "two"):
- assert (summary.nodes[label].computed, summary.nodes[label].reused) == (0, 2)
+ assert (
+ summary.nodes[label].computed,
+ summary.nodes[label].reused,
+ ) == (0, 2)
assert _k(reuse.nodes[label]) == want, f"reuse run: {label}"
loading = _job(database, values)
@@ -265,7 +268,10 @@ def test_every_read_of_stored_results_gives_the_tag_exactly(
outputs = reuse.nodes["one"].as_table()
assert sorted(outputs.column("y").to_pylist()) == [11, 21]
assert sorted(outputs.column("w").to_pylist()) == ["w10", "w20"]
- assert sorted(reuse.nodes["two"].as_table().column("z").to_pylist()) == [22, 42]
+ assert sorted(reuse.nodes["two"].as_table().column("z").to_pylist()) == [
+ 22,
+ 42,
+ ]
# ── downstream consequences ──────────────────────────────────────────────────
@@ -285,8 +291,14 @@ def test_a_node_added_over_a_reused_node_stores_the_exact_tag(
)
second = _job(database, values)
summary = second.run(orchestrator=ORCHESTRATORS[orchestrator]())
- assert (summary.nodes["one"].computed, summary.nodes["one"].reused) == (0, 2)
- assert (summary.nodes["two"].computed, summary.nodes["two"].reused) == (2, 0)
+ assert (
+ summary.nodes["one"].computed,
+ summary.nodes["one"].reused,
+ ) == (0, 2)
+ assert (
+ summary.nodes["two"].computed,
+ summary.nodes["two"].reused,
+ ) == (2, 0)
stored = _stored_rows(database, "double")
assert sorted(map(repr, _exact(stored.column("k")))) == _want(values)
assert _k(second.nodes["two"]) == _want(values)
diff --git a/tests/test_pipeline/test_function_pod_concurrency.py b/tests/test_pipeline/test_function_pod_concurrency.py
index ad9e291b4..d0e48233c 100644
--- a/tests/test_pipeline/test_function_pod_concurrency.py
+++ b/tests/test_pipeline/test_function_pod_concurrency.py
@@ -146,7 +146,10 @@ async def run(job: PipelineJob) -> RunSummary:
sync_job = _repeated_job(pod, InMemoryArrowDatabase(), reverse=reverse)
sync_summary = sync_job.run()
- assert (sync_summary.nodes["add"].computed, sync_summary.nodes["add"].reused) == (
+ assert (
+ sync_summary.nodes["add"].computed,
+ sync_summary.nodes["add"].reused,
+ ) == (
2,
2,
)
@@ -159,7 +162,10 @@ async def run(job: PipelineJob) -> RunSummary:
async_job = _repeated_job(pod, database, reverse=reverse)
summary = asyncio.run(run(async_job))
assert calls == [1, 2]
- assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (2, 2)
+ assert (
+ summary.nodes["add"].computed,
+ summary.nodes["add"].reused,
+ ) == (2, 2)
check(async_job, 0)
calls.clear()
@@ -167,7 +173,10 @@ async def run(job: PipelineJob) -> RunSummary:
replay = _repeated_job(pod, database, reverse=reverse, shift=10)
summary = asyncio.run(run(replay))
assert calls == []
- assert (summary.nodes["add"].computed, summary.nodes["add"].reused) == (0, 4)
+ assert (
+ summary.nodes["add"].computed,
+ summary.nodes["add"].reused,
+ ) == (0, 4)
check(replay, 10)
replay = _repeated_job(pod, database, reverse=reverse, shift=20)
assert replay.run().nodes["add"].reused == 4
diff --git a/tests/test_pipeline/test_graph_node_keys.py b/tests/test_pipeline/test_graph_node_keys.py
new file mode 100644
index 000000000..e64f52e9f
--- /dev/null
+++ b/tests/test_pipeline/test_graph_node_keys.py
@@ -0,0 +1,248 @@
+"""Graph addresses follow declared slot names throughout a job's lifetime."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import os
+import subprocess
+import sys
+from pathlib import Path
+
+import pytest
+
+from orcapod import Pipeline, PipelineJob, SourceNode, function_pod
+from orcapod.core.operators import Join, MergeJoin, SelectDataColumns
+from orcapod.databases import InMemoryArrowDatabase
+from orcapod.sources import DictSource
+
+
+@function_pod(output_keys="doubled")
+def double(x: int) -> int:
+ return x * 2
+
+
+def source(name: str, data_key: str, value: int) -> DictSource:
+ return DictSource(
+ [
+ {"id": 1, "session": 2, data_key: value, f"{data_key}_other": 10},
+ {"id": 2, "session": 2, data_key: value + 1, f"{data_key}_other": 11},
+ ],
+ source_id=name,
+ tag_columns=["id", "session"],
+ tag_only_columns=True,
+ )
+
+
+def address(node) -> str:
+ return node.node_hash().to_string()
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_unbound_graph_keys_survive_bind_rebind_and_reload(
+ mode: str, tmp_path: Path
+) -> None:
+ left = source("left_data", "x", 3)
+ right = source("right_data", "y", 8)
+ blueprint = Pipeline("addresses")
+ with blueprint:
+ slot_left = SourceNode.from_stream(left, name="left")
+ slot_right = SourceNode.from_stream(right, name="right")
+ joined = Join()(slot_left, slot_right, label="joined")
+ double.pod(joined, label="result")
+
+ db = InMemoryArrowDatabase()
+ job = PipelineJob.from_pipeline(blueprint, database=db)
+ keys = set(job._hash_graph.nodes)
+ assert (
+ keys
+ == set(job._hash_graph.nodes)
+ == {address(node) for node in job.nodes.values()}
+ )
+ assert {job.left.label, job.right.label} == set(job.unbound_sources)
+ assert not job.is_runnable("result")
+ assert job._hash_graph[address(job.left)][address(job.joined)]["positions"] == (0,)
+ assert job._hash_graph[address(job.right)][address(job.joined)]["positions"] == (1,)
+ result_input = address(job.result.upstreams[0])
+ assert job._hash_graph[result_input][address(job.result)]["positions"] == (0,)
+
+ job.bind(sources={"right": right, "left": left})
+ assert set(job._hash_graph.nodes) == keys
+ assert job.is_runnable("result")
+ left = source("replacement", "x", 5)
+ job.bind(sources={"left": left, "right": right})
+ job.compile()
+ assert set(job._hash_graph.nodes) == keys
+ summary = job.run() if mode == "sync" else asyncio.run(job.run_async())
+ assert summary.nodes["result"].rows == 2
+
+ path = tmp_path / "run.json"
+ job.save(path)
+ saved = json.loads(path.read_text())["pipeline"]
+ # Main writes the declaration hashes for the unbound blueprint.
+ assert set(saved["nodes"]) == {
+ address(node) for node in job.pipeline.nodes.values()
+ }
+ loaded = PipelineJob.load(path, database=db)
+ assert set(loaded._hash_graph.nodes) == keys
+ loaded.bind(sources={"left": left, "right": right})
+ loaded.run(load_only=True)
+ assert loaded.result.as_table().equals(job.result.as_table())
+
+
+def test_diamond_and_repeated_input_positions() -> None:
+ left = source("left", "x", 3)
+ blueprint = Pipeline("edges")
+ with blueprint:
+ slot = SourceNode.from_stream(left, name="left")
+ first = SelectDataColumns(["x"])(slot, label="first")
+ second = SelectDataColumns(["x_other"])(slot, label="second")
+ Join()(first, second, label="diamond")
+ MergeJoin()(first, first, label="repeat")
+ job = PipelineJob.from_pipeline(blueprint)
+ assert set(job._hash_graph.successors(address(job.left))) == {
+ address(job.first),
+ address(job.second),
+ }
+ assert set(job._hash_graph.predecessors(address(job.diamond))) == {
+ address(job.first),
+ address(job.second),
+ }
+ assert job._hash_graph[address(job.first)][address(job.repeat)]["positions"] == (
+ 0,
+ 1,
+ )
+ assert not job.is_runnable("repeat")
+
+
+def automatic_job(order: int) -> PipelineJob:
+ sources = [source("a", "x", 3), source("b", "x", 8)]
+ with PipelineJob("automatic", database=InMemoryArrowDatabase()) as job:
+ for stream in sources[::order]:
+ double.pod(stream)
+ return job
+
+
+def automatic_labels(job: PipelineJob) -> dict[str, str]:
+ return {address(node): node.label for node in job.function_pods.values()}
+
+
+def test_automatic_names_follow_node_hash_across_orders_processes_and_bindings() -> (
+ None
+):
+ job = automatic_job(1)
+ expected = automatic_labels(job)
+ assert [expected[key] for key in sorted(expected)] == ["double_1", "double_2"]
+ assert automatic_labels(automatic_job(-1)) == expected
+ job.bind(sources={"a": source("b_new", "x", 20), "b": source("a_new", "x", 30)})
+ assert automatic_labels(job) == expected
+
+ script = """
+import json
+import sys
+from test_graph_node_keys import automatic_job, automatic_labels
+
+print(json.dumps(automatic_labels(automatic_job(int(sys.argv[1])))))
+"""
+ for order, seed in ((1, "3"), (-1, "91")):
+ result = subprocess.check_output(
+ [sys.executable, "-c", script, str(order)],
+ cwd=Path(__file__).parent,
+ env={**os.environ, "PYTHONHASHSEED": seed},
+ text=True,
+ )
+ assert json.loads(result) == expected
+
+
+@pytest.mark.parametrize("legacy_labels", [False, True], ids=["branch", "main"])
+def test_load_preserves_saved_automatic_labels(
+ tmp_path: Path, legacy_labels: bool
+) -> None:
+ job = automatic_job(1)
+ job.run()
+ path = tmp_path / "automatic.json"
+ job.save(path)
+ saved = json.loads(path.read_text())
+ expected = automatic_labels(job)
+ run_hashes = {
+ node.label: node.content_hash().to_string()
+ for node in job.function_pods.values()
+ }
+ assert {
+ label: saved["run"]["node_job_content_hashes"][label] for label in run_hashes
+ } == run_hashes
+
+ if legacy_labels:
+ # The same job on main (08c048a7) gave each pair the opposite labels.
+ swaps = {
+ first: second
+ for base in ("double", "SelectDataColumns")
+ for first, second in (
+ (f"{base}_1", f"{base}_2"),
+ (f"{base}_2", f"{base}_1"),
+ )
+ }
+ for descriptor in saved["pipeline"]["nodes"].values():
+ label = descriptor["label"]
+ descriptor["label"] = swaps.get(label, label)
+ for field in ("node_job_content_hashes", "expected_rows"):
+ saved["run"][field] = {
+ swaps.get(label, label): value
+ for label, value in saved["run"][field].items()
+ }
+ path.write_text(json.dumps(saved))
+ expected = {key: swaps[label] for key, label in expected.items()}
+
+ loaded = PipelineJob.load(path, database=job.database)
+ assert automatic_labels(loaded) == expected
+ loaded.bind(sources=job.sources)
+ assert loaded.run(load_only=True).ok
+ assert automatic_labels(loaded) == expected
+ for key, label in expected.items():
+ assert (
+ loaded.nodes[label]
+ .as_table()
+ .equals(job.nodes[automatic_labels(job)[key]].as_table())
+ )
+
+
+def test_automatic_suffixes_skip_explicit_labels() -> None:
+ with PipelineJob() as job:
+ double.pod(source("a", "x", 3))
+ double.pod(source("b", "x", 8))
+ double.pod(source("c", "x", 13), label="double_1")
+ assert set(job.function_pods) == {"double_1", "double_2", "double_3"}
+ assert job.double_1.upstreams[0].upstreams[0] is job.c
+
+
+def test_smallest_explicit_label_keeps_its_node_key() -> None:
+ left = source("left", "x", 3)
+ job = PipelineJob(database=InMemoryArrowDatabase())
+ with job:
+ double.pod(left, label="r1")
+ key = address(job.r1)
+ with job:
+ double.pod(left, label="r2")
+ double.pod(left)
+ assert job.nodes["r1"] is job.r1
+ assert job._hash_graph.nodes[key]["label"] == "r1"
+ assert set(job.function_pods) == {"r1"}
+
+
+def test_legacy_graph_key_uses_a_disjoint_namespace() -> None:
+ class CustomMerge(MergeJoin):
+ pass
+
+ left = source("left", "x", 3)
+ job = PipelineJob(database=InMemoryArrowDatabase())
+ with job:
+ CustomMerge()(left, left, label="custom")
+ (legacy,) = (
+ key
+ for key, attrs in job._hash_graph.nodes.items()
+ if attrs["label"] == "custom"
+ )
+ assert legacy != f"legacy:{job.custom.content_hash().to_string()}"
+ assert legacy.startswith("legacy:")
+ assert address(job.left).startswith("node_hash_v1:")
+ assert set(job._hash_graph.nodes) == {legacy, address(job.left)}
diff --git a/tests/test_pipeline/test_graph_walk_cost.py b/tests/test_pipeline/test_graph_walk_cost.py
index 359830e71..b11c93fbf 100644
--- a/tests/test_pipeline/test_graph_walk_cost.py
+++ b/tests/test_pipeline/test_graph_walk_cost.py
@@ -28,11 +28,18 @@
import pytest
-from orcapod import PipelineJob, function_pod
+from orcapod import FunctionPod, PipelineJob, function_pod
+from orcapod.core.nodes.function_node import FunctionJobNode
+from orcapod.core.nodes.operator_node import OperatorJobNode
from orcapod.core.sources import DictSource
from orcapod.core.streams.base import StreamBase
from orcapod.databases import InMemoryArrowDatabase
-from orcapod.errors import InputValidationError, SourceSpecMismatchError
+from orcapod.errors import (
+ InconsistentSourceError,
+ InputValidationError,
+ SourceSpecMismatchError,
+)
+from orcapod.operators import MapData
from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator
STAGES = 20
@@ -526,14 +533,6 @@ def _rename_job() -> PipelineJob:
return job
-def _function_job() -> PipelineJob:
- """Return a job with one function node, ``plus_one``, over ``src``."""
- job = PipelineJob(name="rebind_function", database=InMemoryArrowDatabase())
- with job:
- _branch_a.pod(_one_row_source(1), label="plus_one")
- return job
-
-
class TestMemoInvalidation:
"""A memoized schema is predicted again when an input of the prediction changes."""
@@ -576,8 +575,7 @@ def test_a_source_of_another_column_type_is_refused_and_moves_no_schema(
def test_setting_an_operator_nodes_upstreams_changes_its_schema(self) -> None:
"""Setting an operator node's ``upstreams`` changes its own schema."""
- job = _rename_job()
- node = job.nodes["renamed"]
+ node = OperatorJobNode(MapData({"x": "y"}), (_one_row_source(1),))
assert node.output_schema()[1]["y"] is int
node.upstreams = (_one_row_source(1.5),)
@@ -586,8 +584,9 @@ def test_setting_an_operator_nodes_upstreams_changes_its_schema(self) -> None:
def test_setting_a_function_nodes_upstreams_changes_its_schema(self) -> None:
"""Setting a function node's ``upstreams`` changes its own schema."""
- job = _function_job()
- node = job.nodes["plus_one"]
+ pod = _branch_a.pod
+ assert isinstance(pod, FunctionPod)
+ node = FunctionJobNode(pod, _one_row_source(1))
assert node.output_schema()[0]["id"] is int
other = DictSource(
[{"id": "one", "x": 1}],
@@ -600,19 +599,14 @@ def test_setting_a_function_nodes_upstreams_changes_its_schema(self) -> None:
assert node.output_schema()[0]["id"] is str
- @pytest.mark.xfail(
- strict=True,
- reason=(
- "Setting a wired node's upstreams clears its own memo only; the nodes "
- "downstream of it keep theirs (ITL-1111). Nothing in orcapod sets "
- "upstreams after construction."
- ),
- )
- def test_setting_upstreams_changes_downstream_schemas(self) -> None:
- """Setting a node's ``upstreams`` should change the schemas downstream of it."""
+ def test_compiled_node_refuses_upstream_changes_and_preserves_schemas(self) -> None:
+ """A refused topology edit leaves the downstream schema intact."""
job = _rename_job()
assert job.nodes["renamed_again"].output_schema()[1]["z"] is int
- job.nodes["renamed"].upstreams = (_one_row_source(1.5),)
+ with pytest.raises(
+ InconsistentSourceError, match="Cannot rewire compiled step"
+ ):
+ job.nodes["renamed"].upstreams = (_one_row_source(1.5),)
- assert job.nodes["renamed_again"].output_schema()[1]["z"] is float
+ assert job.nodes["renamed_again"].output_schema()[1]["z"] is int
diff --git a/tests/test_pipeline/test_observer_main_compatibility.py b/tests/test_pipeline/test_observer_main_compatibility.py
index 2c7078eea..c3e2c98af 100644
--- a/tests/test_pipeline/test_observer_main_compatibility.py
+++ b/tests/test_pipeline/test_observer_main_compatibility.py
@@ -289,6 +289,7 @@ def _run_case(path: str, scenario: str, arrangement: Arrangement) -> _RunRecord:
_ = (_fail if fails else _succeed).pod(
make_source(spec, arrangement), label="result"
)
+ nodes_by_label = job.nodes
policy = "fail_fast" if scenario == "fail_fast" else "continue"
async def run_async() -> RunSummary:
@@ -333,9 +334,10 @@ async def run_async() -> RunSummary:
values = dict(cast("dict[str, object]", vars(summary)))
_ = values.pop("lost_observer_events", None)
values["nodes"] = {
- label: _record_value(asdict(node)) for label, node in summary.nodes.items()
+ label: _record_value(asdict(node_summary))
+ for label, node_summary in summary.nodes.items()
}
- node = cast("StreamProtocol", job.nodes["result"])
+ node = cast("StreamProtocol", nodes_by_label["result"])
rows = cast("list[dict[str, object]]", node.as_table().to_pylist())
return {
"outcome": outcome,
diff --git a/tests/test_pipeline/test_pipeline.py b/tests/test_pipeline/test_pipeline.py
index b135a1ad8..6d20a23e4 100644
--- a/tests/test_pipeline/test_pipeline.py
+++ b/tests/test_pipeline/test_pipeline.py
@@ -13,7 +13,6 @@
from typing import cast
-import networkx as nx
import pyarrow as pa
import pytest
@@ -489,24 +488,20 @@ def test_two_derived_sources_from_same_node_share_pipeline_hash(self, pipeline_d
class TestHashGraph:
def test_graph_empty_before_context(self):
- """pipeline.graph is an empty DiGraph before any with block."""
- # Test the Pipeline object directly — no PipelineJob needed for this property check.
+ """An uncompiled pipeline exposes an empty label mapping."""
pipeline = Pipeline(name="test")
- assert isinstance(pipeline.graph, nx.DiGraph)
- assert len(pipeline.graph.nodes) == 0
- assert len(pipeline.graph.edges) == 0
+ assert pipeline.nodes == {}
+ with pytest.raises(RuntimeError, match="has not been compiled"):
+ _ = pipeline.dag
def test_graph_has_edges_after_compile(self, pipeline_db):
- """After a with block + compile, graph contains the right edges."""
+ """After compilation the DAG connects the labeled node to its sources."""
src_a, src_b = _make_two_sources()
job = PipelineJob(database=pipeline_db)
with job:
Join()(src_a, src_b, label="joiner")
pipeline = job.pipeline
- g = pipeline.graph
- assert len(g.edges) > 0
- joiner_hash = job.pipeline.nodes["joiner"].node_hash().to_string()
- assert joiner_hash in g.nodes
+ assert len(pipeline.dag.predecessors(pipeline.nodes["joiner"])) == 2
def test_graph_multi_node_has_more_edges_than_single_node(self, pipeline_db):
"""A pipeline with more nodes has more edges than one with fewer."""
@@ -517,14 +512,14 @@ def test_graph_multi_node_has_more_edges_than_single_node(self, pipeline_db):
job1 = PipelineJob(database=pipeline_db)
with job1:
Join()(src_a, src_b, label="joiner")
- edges_single = set(job1.pipeline.graph.edges)
+ edges_single = list(job1.pipeline.dag.edges())
# Build two-node pipeline
src_a2, src_b2 = _make_two_sources()
job2 = PipelineJob(database=InMemoryArrowDatabase())
with job2:
joined = Join()(src_a2, src_b2, label="joiner")
pod(joined, label="adder")
- edges_double = set(job2.pipeline.graph.edges)
+ edges_double = list(job2.pipeline.dag.edges())
assert len(edges_double) > len(edges_single)
def test_graph_node_type_source(self, pipeline_db):
@@ -534,11 +529,8 @@ def test_graph_node_type_source(self, pipeline_db):
with job:
Join()(src_a, src_b, label="joiner")
pipeline = job.pipeline
- g = pipeline.graph
- joiner_hash = pipeline.joiner.node_hash().to_string()
- # Predecessors of joiner are source nodes
- for src_hash in g.predecessors(joiner_hash):
- assert g.nodes[src_hash].get("node_type") == "source"
+ for node in pipeline.dag.predecessors(pipeline.joiner):
+ assert node.node_type == "source"
def test_graph_node_type_operator(self, pipeline_db):
"""Operator nodes have node_type='operator' after compile."""
@@ -547,8 +539,7 @@ def test_graph_node_type_operator(self, pipeline_db):
with job:
Join()(src_a, src_b, label="joiner")
pipeline = job.pipeline
- joiner_hash = pipeline.joiner.node_hash().to_string()
- assert pipeline.graph.nodes[joiner_hash].get("node_type") == "operator"
+ assert pipeline.nodes["joiner"].node_type == "operator"
def test_graph_node_type_function(self, pipeline_db):
"""Function nodes have node_type='function' after compile."""
@@ -560,8 +551,7 @@ def test_graph_node_type_function(self, pipeline_db):
joined = Join()(src_a, src_b)
pod(joined, label="adder")
pipeline = job.pipeline
- adder_hash = pipeline.adder.node_hash().to_string()
- assert pipeline.graph.nodes[adder_hash].get("node_type") == "function"
+ assert pipeline.nodes["adder"].node_type == "function"
def test_graph_label_attribute(self, pipeline_db):
"""Labeled nodes carry their label in graph node attributes after compile."""
@@ -570,8 +560,7 @@ def test_graph_label_attribute(self, pipeline_db):
with job:
Join()(src_a, src_b, label="my_join")
pipeline = job.pipeline
- joiner_hash = pipeline.my_join.node_hash().to_string()
- assert pipeline.graph.nodes[joiner_hash].get("label") == "my_join"
+ assert pipeline.nodes["my_join"].label == "my_join"
def test_graph_pipeline_hash_attribute(self, pipeline_db):
"""Compiled nodes have pipeline_hash attribute set in the graph."""
@@ -581,7 +570,7 @@ def test_graph_pipeline_hash_attribute(self, pipeline_db):
Join()(src_a, src_b, label="joiner")
pipeline = job.pipeline
joiner_hash = pipeline.joiner.node_hash().to_string()
- stored_ph = pipeline.graph.nodes[joiner_hash].get("pipeline_hash")
+ stored_ph = pipeline._hash_graph.nodes[joiner_hash].get("pipeline_hash")
assert stored_ph is not None
assert stored_ph == pipeline.joiner.pipeline_hash().to_string()
diff --git a/tests/test_pipeline/test_pipeline_base_recording.py b/tests/test_pipeline/test_pipeline_base_recording.py
index 770e23d25..2ab8a2f3f 100644
--- a/tests/test_pipeline/test_pipeline_base_recording.py
+++ b/tests/test_pipeline/test_pipeline_base_recording.py
@@ -10,6 +10,7 @@
import pyarrow as pa
from orcapod.core.function_pod import FunctionPod
+from orcapod.core.identity_chains import graph_key
from orcapod.core.data_function import PythonDataFunction
from orcapod.core.operators import Join
from orcapod.core.sources import ArrowTableSource
@@ -63,7 +64,7 @@ def test_record_function_pod_captures_source_stream(self):
pipeline = Pipeline(name="test", auto_compile=False)
with pipeline:
pod(stream, label="out")
- stream_hash = stream.content_hash().to_string()
+ stream_hash = graph_key(stream)
assert stream_hash in pipeline._source_streams
def test_invocation_lut_additive_across_with_blocks(self):
@@ -109,8 +110,10 @@ def test_compile_creates_source_node_for_unregistered_upstream(self):
pipeline = Pipeline(name="test")
with pipeline:
pod(stream, label="out")
- source_hash = stream.content_hash().to_string()
- assert isinstance(pipeline._persistent_node_map[source_hash], SourceNode)
+ (source_node,) = pipeline.source_pods.values()
+ assert isinstance(source_node, SourceNode)
+ assert list(pipeline.dag.predecessors(pipeline.nodes["out"])) == [source_node]
+ assert graph_key(source_node) in pipeline._hash_graph
class TestSourceNodeNaming:
@@ -256,7 +259,7 @@ def test_record_operator_captures_both_source_streams(self):
pipeline = Pipeline(name="test", auto_compile=False)
with pipeline:
join(s1, s2, label="joined")
- h1 = s1.content_hash().to_string()
- h2 = s2.content_hash().to_string()
+ h1 = graph_key(s1)
+ h2 = graph_key(s2)
assert h1 in pipeline._source_streams
assert h2 in pipeline._source_streams
diff --git a/tests/test_pipeline/test_rows_on_read.py b/tests/test_pipeline/test_rows_on_read.py
index 39ad613ff..4c2a55d91 100644
--- a/tests/test_pipeline/test_rows_on_read.py
+++ b/tests/test_pipeline/test_rows_on_read.py
@@ -909,7 +909,7 @@ class _AddSystemTag:
"""``SelectDataColumns`` whose result carries one more string system tag."""
@staticmethod
- def operator(values: list[str], exact: bool) -> Any:
+ def operator(values: list[str | None], exact: bool) -> Any:
from orcapod.operators import SelectDataColumns
from orcapod.system_constants import constants
@@ -931,7 +931,7 @@ def unary_static_process(self, stream: Any) -> Any:
return AddSystemTag(["x"])
-def _system_tag_job(values: list[str], exact: bool) -> tuple[Any, Any]:
+def _system_tag_job(values: list[str | None], exact: bool) -> tuple[Any, Any]:
database = InMemoryArrowDatabase()
job = PipelineJob(name="system_tag", database=database)
with job:
@@ -973,6 +973,13 @@ def test_a_nullable_raw_system_tag_is_stored_with_its_declared_field() -> None:
)
+def test_an_operator_refuses_null_values_in_a_nullable_raw_system_tag() -> None:
+ """A nullable field may carry a system tag only when all values are present."""
+ job, _ = _system_tag_job([None, "b"], exact=True)
+ with pytest.raises(InputValidationError, match="null values"):
+ job.run(orchestrator=SyncPipelineOrchestrator(error_policy="fail_fast"))
+
+
def test_a_source_refuses_a_prefixed_system_tag() -> None:
"""Public tables reserve the system-tag prefix for Orcapod."""
from orcapod.core.streams.base import system_tags_as_rows_give
diff --git a/tests/test_pipeline/test_shadowed_job_steps.py b/tests/test_pipeline/test_shadowed_job_steps.py
index 755406d3b..5d14b036d 100644
--- a/tests/test_pipeline/test_shadowed_job_steps.py
+++ b/tests/test_pipeline/test_shadowed_job_steps.py
@@ -32,6 +32,7 @@
from orcapod.core.nodes.operator_node import OperatorJobNode
from orcapod.core.operators.column_selection import SelectDataColumns
from orcapod.databases import DeltaTableDatabase
+from orcapod.errors import InconsistentSourceError
from orcapod.operators import Join, MergeJoin, SemiJoin
from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator
from orcapod.sources import ArrowTableSource, CSVSource
@@ -76,12 +77,14 @@ def _capture(
*,
reverse: bool = False,
null_keys: bool = False,
+ independent: bool = False,
) -> dict[str, StreamProtocol]:
a, b = _source("a", null_keys=null_keys), _source("b")
bindings: dict[str, StreamProtocol] = {"a": a}
with pipeline:
left = SourceNode.from_stream(a, name="a")
- other = SourceNode.from_stream(a, name="a2")
+ alternate = _source("a2", null_keys=null_keys) if independent else a
+ other = SourceNode.from_stream(alternate, name="a2")
if case in ("unary", "distinct"):
second = double if case == "unary" else triple
function_branches = [("first", left, double), ("second", other, second)]
@@ -89,11 +92,11 @@ def _capture(
function_branches.reverse()
for label, source, pod in function_branches:
_ = pod.pod(source, label=label)
- bindings["a2"] = a
+ bindings["a2"] = alternate
elif case == "third":
third = SourceNode.from_stream(b, name="b")
double.pod(Join()(left, other, third, label="join"), label="result")
- bindings.update(a2=a, b=b)
+ bindings.update(a2=alternate, b=b)
elif case == "identical":
for suffix in ("2", "1"):
double.pod(Join()(a, a, label=f"join{suffix}"), label=f"result{suffix}")
@@ -110,7 +113,7 @@ def _capture(
continue
double.pod(operator()(*inputs, label=label), label=f"{label}_result")
if label == "slots":
- bindings["a2"] = a
+ bindings["a2"] = alternate
return bindings
@@ -123,34 +126,32 @@ def _capture(
] + [pytest.param("unary", reverse, id=f"unary-{reverse}") for reverse in (False, True)]
-def _refusal_message(case: str) -> str:
- first, second = ("first", "second") if case == "unary" else ("direct", "slots")
- labels = rf"(?:'{first}' and '{second}'|'{second}' and '{first}')"
- return (
- rf"Steps {labels} have the same identity in this job \(ITL-1767\)\. "
- + re.escape("Put them in separate jobs or use only one of the two forms.")
- )
+_SHARED_SOURCE = "One source object on two slots"
+_MIXED_CAPTURE = _SHARED_SOURCE + "|already declared under slot"
@pytest.mark.parametrize(("case", "reverse"), _REFUSALS)
@pytest.mark.parametrize("direct_capture", [False, True], ids=["blueprint", "capture"])
-def test_refuses_shadowed_steps_at_compile(
+def test_refuses_the_source_alias_before_it_can_shadow_steps(
case: str, reverse: bool, direct_capture: bool, tmp_path: Path
) -> None:
database_path = tmp_path / "db"
database = DeltaTableDatabase(database_path)
- message = _refusal_message(case)
if direct_capture:
- job = PipelineJob("matrix", database=database)
- bindings = _capture(job, case, reverse=reverse)
- job.bind(sources=bindings)
- with pytest.raises(ValueError, match=message):
- job.compile()
+ graph = PipelineJob("matrix", database=database)
+ with pytest.raises(InconsistentSourceError, match=_MIXED_CAPTURE):
+ _ = _capture(graph, case, reverse=reverse)
else:
pipeline = Pipeline("matrix")
- bindings = _capture(pipeline, case, reverse=reverse)
- with pytest.raises(ValueError, match=message):
- _ = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings)
+ if case == "unary":
+ bindings = _capture(pipeline, case, reverse=reverse)
+ with pytest.raises(InconsistentSourceError, match=_SHARED_SOURCE):
+ _ = PipelineJob.from_pipeline(
+ pipeline, database=database, sources=bindings
+ )
+ else:
+ with pytest.raises(InconsistentSourceError, match=_MIXED_CAPTURE):
+ _ = _capture(pipeline, case, reverse=reverse)
assert not list(database_path.rglob("_delta_log"))
@@ -186,7 +187,7 @@ def test_working_cases_run_and_reload(
) -> None:
database = DeltaTableDatabase(tmp_path / "db")
pipeline = Pipeline("matrix")
- bindings = _capture(pipeline, case)
+ bindings = _capture(pipeline, case, independent=True)
job = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings)
assert {
label for label, node in job.nodes.items() if node.node_type != "source"
@@ -213,86 +214,53 @@ def test_working_cases_run_and_reload(
@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
-@pytest.mark.parametrize(("case", "reverse"), _REFUSALS)
-def test_rechecks_when_later_bindings_make_steps_equal(
- case: str, reverse: bool, asynchronous: bool, tmp_path: Path
-) -> None:
- pipeline = Pipeline("matrix")
- bindings = _capture(pipeline, case, reverse=reverse)
- job = cast(
- "PipelineJob",
- PipelineJob.from_invocations(pipeline.to_invocations(), name="matrix"),
- )
- database_path = tmp_path / "db"
- job.bind(database=DeltaTableDatabase(database_path), sources=bindings)
-
- with pytest.raises(ValueError, match=_refusal_message(case)):
- _run(job, asynchronous)
- assert not list(database_path.rglob("_delta_log"))
-
-
-@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
-@pytest.mark.parametrize("reverse", [False, True], ids=["direct-first", "slots-first"])
@pytest.mark.parametrize("scenario", ["null-keys", "both-current"])
-def test_step_collision_is_independent_of_rows_and_run_state(
- scenario: str, reverse: bool, asynchronous: bool, tmp_path: Path
+def test_refuses_a_rewire_that_would_shadow_a_distinct_step(
+ scenario: str, asynchronous: bool, tmp_path: Path
) -> None:
- pipeline = Pipeline("matrix")
- bindings = _capture(
- pipeline, "mixed", reverse=reverse, null_keys=scenario == "null-keys"
- )
database = DeltaTableDatabase(tmp_path / "db")
- if scenario == "null-keys":
- with pytest.raises(ValueError, match=_refusal_message("mixed")):
- _ = PipelineJob.from_pipeline(pipeline, database=database, sources=bindings)
- job = PipelineJob.from_pipeline(pipeline, database=database)
- job.bind(sources=bindings)
- expected = 0 if scenario == "null-keys" else 2
- for label in ("direct_result", "slots_result"):
- node = cast("FunctionJobNode", job.nodes[label])
- _ = node.run()
- assert node.as_table().num_rows == expected
- assert node.holds_current_run()
-
- with pytest.raises(ValueError, match=_refusal_message("mixed")):
+ with PipelineJob("matrix", database=database) as job:
+ for name, label in (("a", "first"), ("b", "second")):
+ _ = double.pod(
+ _source(name, null_keys=scenario == "null-keys"), label=label
+ )
+ first = cast("FunctionJobNode", job.nodes["first"])
+ second = cast("FunctionJobNode", job.nodes["second"])
+ if scenario == "both-current":
_run(job, asynchronous)
+ assert first.holds_current_run() and second.holds_current_run()
+ held = second.upstreams[0]
+ message = re.escape(
+ "Steps 'first' and 'second' have the same identity in this job (ITL-1767). "
+ "Put them in separate jobs or use only one of the two forms."
+ )
+ with pytest.raises(ValueError, match=f"^{message}$"):
+ second.upstreams = first.upstreams
+ assert second.upstreams[0] is held
+ _run(job, asynchronous)
+ for node in (first, second):
+ assert node.as_table(columns={"sort_by_tags": True})["result"].to_pylist() == [
+ 20,
+ 40,
+ ]
-@pytest.mark.parametrize("asynchronous", [False, True], ids=["sync", "async"])
-def test_pending_operator_steps_on_aliased_slots_can_be_saved_and_loaded(
- asynchronous: bool, tmp_path: Path
-) -> None:
+def test_later_bindings_refuse_aliased_operator_slots(tmp_path: Path) -> None:
data_path = tmp_path / "rows.csv"
_ = data_path.write_text("key,value\n1,10\n2,20\n")
source = CSVSource(
str(data_path), source_id="shared", tag_columns=["key"], tag_only_columns=True
)
- database = DeltaTableDatabase(tmp_path / "db")
- with PipelineJob("matrix", database=database) as job:
+ database_path = tmp_path / "db"
+ with Pipeline("matrix") as pipeline:
for slot, label in (("a", "first"), ("b", "second")):
_ = SelectDataColumns(["value"])(
SourceNode.from_stream(source, name=slot), label=label
)
- job.bind(sources={"a": source, "b": source})
- path = tmp_path / "job.json"
- job.save(path)
-
- loaded = PipelineJob.load(path)
- assert loaded.sources["a"] is loaded.sources["b"]
- assert set(loaded.nodes) == {"a", "b", "first", "second"}
- with pytest.raises(ValueError, match=_refusal_message("unary")):
- _run(loaded, asynchronous, load_only=True)
-
-
-@pytest.mark.parametrize(("case", "reverse"), _REFUSALS)
-def test_load_keeps_existing_refusal_of_colliding_stubs(
- case: str, reverse: bool, tmp_path: Path
-) -> None:
- pipeline = Pipeline("matrix")
- bindings = _capture(pipeline, case, reverse=reverse)
- job = PipelineJob.from_pipeline(pipeline)
- job.bind(sources=bindings)
- path = tmp_path / "job.json"
- job.save(path)
- with pytest.raises(NotImplementedError, match=r"StreamBase\.identity_structure"):
- _ = PipelineJob.load(path)
+ job = PipelineJob.from_pipeline(
+ pipeline, database=DeltaTableDatabase(database_path)
+ )
+ with pytest.raises(InconsistentSourceError, match=_SHARED_SOURCE):
+ job.bind(sources={"a": source, "b": source})
+ assert not job.sources
+ assert not list(database_path.rglob("_delta_log"))
diff --git a/tests/test_pipeline/test_shared_operator_inputs.py b/tests/test_pipeline/test_shared_operator_inputs.py
index c1a458cd7..e559e12e7 100644
--- a/tests/test_pipeline/test_shared_operator_inputs.py
+++ b/tests/test_pipeline/test_shared_operator_inputs.py
@@ -11,6 +11,7 @@
from orcapod.contexts import get_default_context
from orcapod.core.row_ids import entry_id
from orcapod.databases import InMemoryArrowDatabase
+from orcapod.errors import InconsistentSourceError
from orcapod.operators import Join, MergeJoin, SemiJoin
from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator
from orcapod.protocols.core_protocols import StreamProtocol
@@ -54,7 +55,7 @@ def runner(
("operator", "arity", "tag_count"),
[(Join, 2, 4), (Join, 3, 6), (MergeJoin, 2, 4), (SemiJoin, 2, 2)],
)
-def test_shared_slots_match_repeated_source(
+def test_repeating_one_slot_matches_repeated_source(
runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator,
operator: type[Join | MergeJoin | SemiJoin],
arity: int,
@@ -66,10 +67,19 @@ def test_shared_slots_match_repeated_source(
with Pipeline("shared") as pipeline:
slots = tuple(SourceNode.from_stream(a, name=name) for name in names)
_ = double_join_value.pod(operator()(*slots, label="joined"), label="out")
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ _ = PipelineJob.from_pipeline(
+ pipeline,
+ database=InMemoryArrowDatabase(),
+ sources=dict.fromkeys(names, a),
+ )
+ with Pipeline("shared") as one_slot:
+ slot = SourceNode.from_stream(a, name="a")
+ _ = double_join_value.pod(
+ operator()(*[slot] * arity, label="joined"), label="out"
+ )
shared = PipelineJob.from_pipeline(
- pipeline,
- database=InMemoryArrowDatabase(),
- sources=dict.fromkeys(names, a),
+ one_slot, database=InMemoryArrowDatabase(), sources={"a": a}
)
repeated = PipelineJob("shared", database=InMemoryArrowDatabase())
with repeated:
@@ -101,7 +111,7 @@ def test_shared_slots_match_repeated_source(
@pytest.mark.parametrize("jobs", ["one", "shared_first", "distinct_first"])
-def test_shared_slots_and_distinct_sources_share_storage(
+def test_repeat_and_distinct_sources_share_storage(
runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, jobs: str
) -> None:
"""Write both variants to the same function table in either execution order."""
@@ -113,9 +123,11 @@ def make_job(variants: tuple[bool, ...]) -> PipelineJob:
with Pipeline("shared") as pipeline:
left = SourceNode.from_stream(a, name="a")
for shared in variants:
- name, right_source = ("a2", a) if shared else ("b", b)
- sources[name] = right_source
- right = SourceNode.from_stream(right_source, name=name)
+ if shared:
+ name, right = "a2", left
+ else:
+ name, right = "b", SourceNode.from_stream(b, name="b")
+ sources[name] = b
_ = double_join_value.pod(Join()(left, right), label=name + "_out")
return PipelineJob.from_pipeline(pipeline, database=db, sources=sources)
@@ -135,15 +147,15 @@ def make_job(variants: tuple[bool, ...]) -> PipelineJob:
assert len(paths) == 1
-def test_shared_slot_join_save_and_load_only(
+def test_two_slot_join_save_and_load_only(
runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator, tmp_path: Path
) -> None:
"""Keep both saved inputs when rebuilding the blueprint and the job."""
- a = source("a")
- sources: dict[str, StreamProtocol] = {"a": a, "a2": a}
+ a, b = source("a"), source("b")
+ sources: dict[str, StreamProtocol] = {"a": a, "a2": b}
with Pipeline("shared") as pipeline:
left = SourceNode.from_stream(a, name="a")
- right = SourceNode.from_stream(a, name="a2")
+ right = SourceNode.from_stream(b, name="a2")
_ = double_join_value.pod(Join()(left, right, label="joined"), label="out")
db = InMemoryArrowDatabase()
job = PipelineJob.from_pipeline(pipeline, database=db, sources=sources)
@@ -152,6 +164,8 @@ def test_shared_slot_join_save_and_load_only(
job.save(path)
loaded = PipelineJob.load(path, database=db)
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ loaded.bind(sources={"a": a, "a2": a})
loaded.bind(sources=sources)
summary = loaded.run(orchestrator=runner, load_only=True)
assert summary.nodes["out"].reused == 2
@@ -166,19 +180,19 @@ def test_shared_slot_join_save_and_load_only(
)
-def test_join_downstream_of_function_pods_on_shared_slots(
+def test_join_downstream_of_function_pods_on_distinct_slots(
runner: SyncPipelineOrchestrator | AsyncPipelineOrchestrator,
) -> None:
- """A source that occupies two slots still feeds both branches through functions."""
- a = source("a")
+ """Distinct bindings feed both branches through functions."""
+ a, b = source("a"), source("b")
with Pipeline("shared") as pipeline:
left = SourceNode.from_stream(a, name="a")
- right = SourceNode.from_stream(a, name="a2")
+ right = SourceNode.from_stream(b, name="a2")
_ = Join()(
double_join_value.pod(left), other_join_value.pod(right), label="joined"
)
job = PipelineJob.from_pipeline(
- pipeline, database=InMemoryArrowDatabase(), sources={"a": a, "a2": a}
+ pipeline, database=InMemoryArrowDatabase(), sources={"a": a, "a2": b}
)
_ = job.run(orchestrator=runner)
rows = job.nodes["joined"].as_table(columns={"system_tags": True}).sort_by("value")
diff --git a/tests/test_pipeline/test_source_id_conflicts.py b/tests/test_pipeline/test_source_id_conflicts.py
index a745e03c9..293b02d5b 100644
--- a/tests/test_pipeline/test_source_id_conflicts.py
+++ b/tests/test_pipeline/test_source_id_conflicts.py
@@ -522,10 +522,11 @@ def test_bind_checks_all_prospective_slots_atomically(
assert job.sources["left"] is second
with pytest.raises(InconsistentSourceError, match="distinct source objects"):
job.bind(sources={"right": first})
- job.bind(sources={"right": second})
- assert job.sources["right"] is second
- with pytest.raises(InconsistentSourceError, match="distinct source objects"):
- job.bind(sources={"left": _dict(100)})
+ before = job.sources
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ job.bind(sources={"right": second})
+ assert job.sources == before
+ assert job.sources["left"] is second
def test_from_pipeline_checks_the_initial_bind() -> None:
@@ -632,11 +633,11 @@ def test_deferred_capture_refuses_new_source_conflict() -> None:
OperatorInvocation(other, (first,), "reused")
)
record_first()
- before = pipeline.graph.copy()
+ before = pipeline._capture_graph.copy()
with pytest.raises(InconsistentSourceError, match="distinct source objects"):
record_conflicting()
- assert set(pipeline.graph.nodes) == set(before.nodes)
- assert set(pipeline.graph.edges) == set(before.edges)
+ assert set(pipeline._capture_graph.nodes) == set(before.nodes)
+ assert set(pipeline._capture_graph.edges) == set(before.edges)
record_shared()
pipeline.compile()
assert set(pipeline.nodes) == {"first", "reused", "shared"}
diff --git a/tests/test_pipeline/test_source_object_registration.py b/tests/test_pipeline/test_source_object_registration.py
index f44ef4c9b..4979161f6 100644
--- a/tests/test_pipeline/test_source_object_registration.py
+++ b/tests/test_pipeline/test_source_object_registration.py
@@ -14,7 +14,11 @@
from orcapod import Pipeline, PipelineJob, function_pod, side_effect_pod
from orcapod.databases import InMemoryArrowDatabase
from orcapod.errors import InconsistentSourceError, SourceSpecMismatchError
-from orcapod.pipeline import AsyncPipelineOrchestrator, SyncPipelineOrchestrator
+from orcapod.pipeline import (
+ AsyncPipelineOrchestrator,
+ StatusObserver,
+ SyncPipelineOrchestrator,
+)
from orcapod.protocols.core_protocols import SourceProtocol, StreamProtocol
from orcapod.side_effects import SideEffectPod
from orcapod.sources import CSVSource, DictSource
@@ -107,7 +111,7 @@ def _rebind(job: PipelineJob, sources: dict[str, StreamProtocol], setter: bool)
for name, source in sources.items():
job.nodes[name].bound_source = source
else:
- job.bind(sources=sources)
+ job.bind(sources=dict(sources))
@pytest.mark.parametrize("reverse", [False, True])
@@ -146,8 +150,9 @@ def test_bind_refuses_two_objects_with_one_hash(
assert "slot 'a'" in str(error.value) and "slot 'b'" in str(error.value)
assert job.sources == before
- job.bind(sources={"a": first, "b": first})
- assert job.sources["a"] is job.sources["b"] is first
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ job.bind(sources={"a": first, "b": first})
+ assert job.sources == before
job.bind(sources={"a": _source(tmp_path, kind, "replacement")})
job.bind(sources={"b": second})
assert job.sources["b"] is second
@@ -227,53 +232,25 @@ def test_load_refuses_one_source_id_with_different_key_columns(
@pytest.mark.parametrize("slots", [("a", "b"), ("c", "b", "a")])
@pytest.mark.parametrize("orchestrator", ORCHESTRATORS)
-def test_load_reuses_one_object_for_identical_saved_configs(
+def test_bind_refuses_one_source_for_identical_saved_configs(
tmp_path: Path, slots: tuple[str, ...], orchestrator: Orchestrator
) -> None:
job = _job(tmp_path, slots)
- db = InMemoryArrowDatabase()
source = _source(tmp_path, "csv", "shared")
- job.bind(database=db, sources=dict.fromkeys(slots, source))
- job.run(orchestrator=orchestrator())
- path = tmp_path / "job.json"
- job.save(path)
- saved = json.loads(path.read_text())
- configs = saved["bindings"]["sources"]
- assert all(configs[name] == configs[slots[0]] for name in slots)
-
- loaded = PipelineJob.load(path, database=db)
- shared = loaded.sources[slots[0]]
- for name in slots:
- assert loaded.sources[name] is shared
- copied = tmp_path / "copied.json"
- loaded.save(copied)
- assert copied.read_bytes() == path.read_bytes()
-
- def rows(graph: PipelineJob, name: str) -> list[dict[str, Any]]:
- return graph.nodes[name].as_table(columns={"sort_by_tags": True}).to_pylist()
-
- stored = {
- table_path: db.get_all_records(table_path)
- for table_path in db.list_table_paths()
- }
- loaded.run(orchestrator=orchestrator(), load_only=True)
- for name in slots:
- assert rows(loaded, name) == ROWS
- assert rows(loaded, f"result_{name}") == rows(job, f"result_{name}")
- assert {
- table_path: db.get_all_records(table_path)
- for table_path in db.list_table_paths()
- } == stored
-
- replacement = _source(tmp_path, "csv", "replacement")
- loaded.bind(sources={slots[0]: replacement})
- assert loaded.sources[slots[0]] is replacement
- for name in slots[1:]:
- assert loaded.sources[name] is shared
+ if len(slots) == 1:
+ job.bind(sources={slots[0]: source})
+ assert job.run(orchestrator=orchestrator()).ok
+ else:
+ before = job.sources
+ with pytest.raises(
+ InconsistentSourceError, match="One source object on two slots"
+ ):
+ job.bind(sources=dict.fromkeys(slots, source))
+ assert job.sources == before
@pytest.mark.parametrize("reverse_keys", [False, True])
-def test_load_shares_repeated_configs_written_by_main(
+def test_load_refuses_repeated_configs_written_by_main(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, reverse_keys: bool
) -> None:
# origin/main (f55ed6d7) wrote a separate, identical config for each of two
@@ -291,10 +268,8 @@ def test_load_shares_repeated_configs_written_by_main(
path = tmp_path / "reordered.json"
path.write_text(json.dumps(saved))
- job = PipelineJob.load(path)
- assert job.sources["a"] is job.sources["b"]
- assert job.nodes["a"].as_table().to_pylist() == ROWS
- assert job.nodes["b"].as_table().to_pylist() == ROWS
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ PipelineJob.load(path)
def test_load_refuses_a_saved_custom_system_tag(tmp_path: Path) -> None:
@@ -308,23 +283,34 @@ def test_load_refuses_a_saved_custom_system_tag(tmp_path: Path) -> None:
PipelineJob.load(path)
-def test_itl_1554_loading_shared_slots_feeding_the_same_pod(tmp_path: Path) -> None:
- """Record the existing read-only DAG failure for this shared-source topology."""
+@pytest.mark.parametrize("orchestrator", ORCHESTRATORS)
+def test_status_keeps_main_run_uri(tmp_path: Path, orchestrator: Orchestrator) -> None:
+ """Persist the URI measured on main (39be606a)."""
+ slots = ("a",)
db = InMemoryArrowDatabase()
- with PipelineJob(database=db) as job:
+ with PipelineJob("check", database=db) as job:
+ for slot in slots:
+ total.pod(_source(tmp_path, "dict", slot), label=f"total_{slot}")
+ source = _source(tmp_path, "dict", "shared")
+ job.bind(sources=dict.fromkeys(slots, source))
+
+ observer = StatusObserver(status_database=db)
+ job.run(observer=observer, orchestrator=orchestrator())
+
+ status = observer.get_status()
+ assert status is not None
+ assert set(status["_status_pipeline_uri"].to_pylist()) == {"check@3f66b63aa7f119f8"}
+
+
+def test_itl_1554_shared_slots_feeding_the_same_pod_are_refused(tmp_path: Path) -> None:
+ with PipelineJob() as job:
for slot in ("a", "b"):
total.pod(_source(tmp_path, "dict", slot), label=f"total_{slot}")
source = _source(tmp_path, "csv", "shared")
- job.bind(sources={"a": source, "b": source})
- path = tmp_path / "job.json"
- job.save(path)
-
- with pytest.raises(NotImplementedError, match="StreamBase.identity_structure"):
- PipelineJob.load(path, database=db)
- with pytest.raises(
- ValueError, match="Steps 'total_a' and 'total_b' have the same identity"
- ):
- job.run()
+ before = job.sources
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ job.bind(sources={"a": source, "b": source})
+ assert job.sources == before
@pytest.mark.parametrize("kind", ["equal", "different", "csv"])
@@ -444,7 +430,7 @@ def test_binding_refuses_projection_over_the_receiving_slot(
@pytest.mark.parametrize(
"entry", ["sync", "async_orchestrator", "run_async", "slot", "node"]
)
-def test_run_refuses_slot_cycle_created_by_upstream_replacement(
+def test_run_refuses_slot_cycle_in_existing_binding(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, entry: str, load_only: bool
) -> None:
from orcapod.core.nodes.operator_node import OperatorJobNode
@@ -458,7 +444,10 @@ def test_run_refuses_slot_cycle_created_by_upstream_replacement(
job.bind(sources={"a": projection})
_ = projection.run()
assert slot.run().table.to_pylist() == ROWS
- projection.upstreams = (slot,)
+ # Simulate an invalid binding that predates validation at the setter.
+ with monkeypatch.context() as patch:
+ patch.setattr(projection, "_rewire_validators", ())
+ projection.upstreams = (slot,)
def unexpected_check() -> bool:
pytest.fail("A source was checked before the invalid binding was refused")
@@ -751,9 +740,18 @@ def test_bind_refuses_other_slots_atomically_and_recompile_preserves_rows(
job.nodes[name].bound_source is source for name, source in before.items()
)
job.run(orchestrator=orchestrator())
- assert sorted(job.nodes["result_a"].as_table()["out"].to_pylist()) == [3, 7]
- assert sorted(job.nodes["result_b"].as_table()["out"].to_pylist()) == [-1, -1]
- assert sorted(job.nodes["result_c"].as_table()["out"].to_pylist()) == [2, 12]
+ assert sorted(job.nodes["result_a"].as_table()["out"].to_pylist()) == [
+ 3,
+ 7,
+ ]
+ assert sorted(job.nodes["result_b"].as_table()["out"].to_pylist()) == [
+ -1,
+ -1,
+ ]
+ assert sorted(job.nodes["result_c"].as_table()["out"].to_pylist()) == [
+ 2,
+ 12,
+ ]
@pytest.mark.parametrize("bound", [False, True])
@@ -817,38 +815,25 @@ def test_source_slot_refuses_composite_with_conflicting_roots(
assert slot.bound_source is first
-def test_coalesced_captures_release_duplicate_projections(tmp_path: Path) -> None:
- import gc
- from weakref import ref
-
+def test_coalesced_captures_reuse_the_projection(tmp_path: Path) -> None:
source = _source(tmp_path, "dict", "shared")
+ projection = source.select_data_columns(["x", "y"])
graph = Pipeline("retention")
-
- def capture_projection():
- projection = source.select_data_columns(["x", "y"])
+ for _ in range(8):
with graph:
- _ = total.pod(projection, label="step")
- return ref(projection)
-
- projections = [capture_projection() for _ in range(8)]
- _ = gc.collect()
-
- assert "step" in graph.nodes
- assert sum(projection_ref() is not None for projection_ref in projections) <= 2
+ total.pod(projection, label="step")
+ assert set(graph.function_pods) == {"step"}
+ assert len(graph.source_pods) == 1
def test_capture_reports_both_uses_of_slots_with_the_same_name(tmp_path: Path) -> None:
- from orcapod.core.nodes.source_node import SourceJobNode
-
first, second = _pair(tmp_path, "different", False)
- left = SourceJobNode.from_stream(first, name="same")
- right = SourceJobNode.from_stream(second, name="same")
with Pipeline("diagnostics"):
- total.pod(left, label="first")
+ total.pod(first, label="first")
with pytest.raises(
InconsistentSourceError, match="distinct source objects"
) as error:
- difference.pod(right, label="second")
+ difference.pod(second, label="second")
message = str(error.value)
assert "step 'first'" in message and "step 'second'" in message
@@ -874,31 +859,6 @@ def consume(out: int) -> int:
assert "source_id" not in str(error.value)
-def test_compile_refuses_schema_conflict_introduced_through_live_slot() -> None:
- import pyarrow as pa
-
- from orcapod.core.nodes.source_node import SourceJobNode
- from orcapod.sources import ArrowTableSource
-
- def source(name: str, kind: pa.DataType) -> ArrowTableSource:
- return ArrowTableSource(
- pa.table({"x": pa.array([1], type=kind), "y": [2]}),
- source_id=name,
- infer_nullable=True,
- )
-
- first = SourceJobNode.from_stream(source("shared", pa.int32()), name="same")
- second = SourceJobNode.from_stream(source("other", pa.int64()), name="same")
- with Pipeline("compile", auto_compile=False) as pipeline:
- total.pod(first, label="first")
- difference.pod(second, label="second")
- second.bound_source = source("shared", pa.int64())
- with pytest.raises(InconsistentSourceError, match="different schemas") as error:
- pipeline.compile()
- assert "step 'first'" in str(error.value) and "step 'second'" in str(error.value)
-
-
-@pytest.mark.filterwarnings("ignore::orcapod.errors.SemiJoinIgnoredColumnWarning")
def test_source_slot_run_checks_roots_changed_after_binding(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
@@ -1101,6 +1061,13 @@ def test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows(
for name, source in sources.items():
total.pod(source, label=f"original_{name}")
rotated = names[1:] + names[:1]
+ if setter:
+ with pytest.raises(
+ InconsistentSourceError, match="One source object on two slots"
+ ):
+ _rebind(job, {names[0]: sources[rotated[0]]}, setter=True)
+ assert all(job.sources[name] is sources[name] for name in names)
+ return
_rebind(
job,
{slot: sources[name] for slot, name in zip(names, rotated, strict=True)},
@@ -1123,15 +1090,11 @@ def test_swapping_or_rotating_slots_blocks_capture_but_preserves_rows(
offset = 10 * ((index + 1) % len(names))
assert sorted(before.as_table()["out"].to_pylist()) == [offset + 3, offset + 7]
- restored, *still_changed = names
- _rebind(job, {restored: sources[restored]}, setter)
- with job:
- with pytest.raises(InconsistentSourceError, match="not as captured") as error:
- difference.pod(sources[restored], label="added")
- assert repr(restored) not in str(error.value)
- assert all(repr(name) in str(error.value) for name in still_changed)
-
- _rebind(job, {name: sources[name] for name in still_changed}, setter)
+ restored = names[0]
+ with pytest.raises(InconsistentSourceError, match="One source object on two slots"):
+ job.bind(sources={restored: sources[restored]})
+ assert job.sources[restored] is sources[rotated[0]]
+ job.bind(sources=dict(sources))
with job:
difference.pod(sources[restored], label="added")
job.run(orchestrator=orchestrator())
@@ -1193,8 +1156,9 @@ def test_rebound_job_refuses_same_pod_or_prebuilt_recapture(
total.pod(first, label="original_a")
total.pod(second, label="original_b")
if setter:
- job.nodes["a"].bound_source = second
+ job.nodes["a"].bound_source = None
job.nodes["b"].bound_source = first
+ job.nodes["a"].bound_source = second
else:
job.bind(sources={"a": second, "b": first})
job.compile()
@@ -1517,6 +1481,14 @@ def test_schema_declaration_gives_each_job_its_own_binding(
declaration = SourceNode.from_stream(original, name="a")
assert isinstance(declaration, SourceNode)
assert not hasattr(declaration, "bound_source")
+ if origin != "standalone":
+ # A compiled slot belongs to its blueprint. A fresh declaration states
+ # the same schema without capturing that graph's node.
+ declaration = SourceNode(
+ name=declaration.name,
+ tag_schema=declaration.tag_schema,
+ data_schema=declaration.data_schema,
+ )
with PipelineJob(database=InMemoryArrowDatabase()) as first:
total.pod(declaration, label="result")
@@ -1526,9 +1498,14 @@ def test_schema_declaration_gives_each_job_its_own_binding(
assert first_slot.bound_source is None
first.bind(sources={"a": original})
+ second_declaration = SourceNode(
+ name=declaration.name,
+ tag_schema=declaration.tag_schema,
+ data_schema=declaration.data_schema,
+ )
with PipelineJob(database=InMemoryArrowDatabase()) as second:
- total.pod(declaration, label="result")
- product.pod(declaration, label="reused")
+ total.pod(second_declaration, label="result")
+ product.pod(second_declaration, label="reused")
second_slot = second.nodes["a"]
assert isinstance(second_slot, SourceJobNode)
assert second_slot is not first_slot
@@ -1653,7 +1630,7 @@ def test_prebuilt_stream_over_own_slot_is_refused_before_rebinding(
) as error:
total.pod(prebuilt, label="rejected")
assert "ITL-1559" in str(error.value)
- assert "inside the job" in str(error.value)
+ assert "from outside this pipeline" in str(error.value)
assert not outer.nodes
assert set(job.nodes) == {"a", "direct"}
@@ -1801,7 +1778,7 @@ def unexpected_check() -> bool:
@pytest.mark.parametrize("read", ["iter_data", "async_iter_data", "held_row_count"])
def test_cold_function_held_reads_refuse_a_slot_cycle(
- tmp_path: Path, read: str
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch, read: str
) -> None:
from orcapod.core.nodes.operator_node import OperatorJobNode
from orcapod.operators import SelectDataColumns
@@ -1811,7 +1788,9 @@ def test_cold_function_held_reads_refuse_a_slot_cycle(
function = job.nodes["result_a"]
projection = OperatorJobNode(SelectDataColumns(["x", "y"]), [job.sources["a"]])
job.bind(sources={"a": projection})
- projection.upstreams = (slot,)
+ with monkeypatch.context() as patch:
+ patch.setattr(projection, "_rewire_validators", ())
+ projection.upstreams = (slot,)
async def read_async() -> None:
_ = [row async for row in function.async_iter_data()]
@@ -1870,8 +1849,8 @@ def public_state(pipeline: Pipeline | PipelineJob) -> tuple[object, ...]:
"""Snapshot public topology, compiled nodes and registered sources."""
invocations = pipeline.to_invocations()
return (
- tuple(pipeline.graph.nodes),
- tuple(pipeline.graph.edges),
+ tuple(id(node) for node in pipeline.dag.nodes()),
+ tuple((id(up), id(down)) for up, down in pipeline.dag.edges()),
{label: id(node) for label, node in pipeline.nodes.items()},
tuple(invocations.source_streams),
tuple(invocation.label for invocation in invocations.invocations),
diff --git a/tests/test_pipeline/test_stale_outputs.py b/tests/test_pipeline/test_stale_outputs.py
index d7fdc5b56..154d32dc9 100644
--- a/tests/test_pipeline/test_stale_outputs.py
+++ b/tests/test_pipeline/test_stale_outputs.py
@@ -9,7 +9,7 @@
import pytest
from typing_extensions import override
-from orcapod import Pipeline, PipelineJob, SourceNode, function_pod
+from orcapod import FunctionPod, Pipeline, PipelineJob, SourceNode, function_pod
from orcapod.channels import Channel
from orcapod.core.nodes.function_node import FunctionJobNode
from orcapod.core.nodes.operator_node import OperatorJobNode
@@ -588,18 +588,22 @@ def test_derived_source_tracks_slot_added_by_upstream_replacement(
run_async: bool,
) -> None:
_, job, a, b, _, _ = _job(as_function=True)
- origin = job.nodes["step"]
slot = job.nodes["input"]
- assert isinstance(origin, FunctionJobNode)
assert isinstance(slot, SourceJobNode)
- origin.upstreams = (a,)
- _run(job, run_async)
+ database = InMemoryArrowDatabase()
+ pod = add.pod
+ assert isinstance(pod, FunctionPod)
+ origin = FunctionJobNode(
+ pod, a, pipeline_database=database, result_database=database
+ )
+ _ = origin.run()
derived = origin.as_source()
assert derived.as_table()["value"].to_pylist() == [12]
origin.upstreams = (slot,)
job.bind(sources={"input": b})
_run(job, run_async)
+ _ = origin.run()
assert derived.check_for_new_data()
assert derived.as_table()["value"].to_pylist() == [112]
rows = derived.iter_data()
@@ -633,13 +637,11 @@ def unexpected_read() -> None:
@pytest.mark.asyncio
async def test_operator_async_preflight_rejection_clears_held_rows() -> None:
- _, job, _, _, _, _ = _job(as_function=False)
- _, other_job, _, b, _, _ = _job(as_function=False)
- consumer = job.nodes["step"]
+ _, other_job, a, b, _, _ = _job(as_function=False)
+ consumer = OperatorJobNode(SelectDataColumns(["x", "y"]), (a,))
external = other_job.nodes["input"]
- assert isinstance(consumer, OperatorJobNode)
assert isinstance(external, SourceJobNode)
- _run(job, run_async=False)
+ _ = consumer.run()
assert consumer.as_table().num_rows == 1
upstreams = consumer.upstreams
diff --git a/tests/test_pipeline/test_step3_main_compatibility.py b/tests/test_pipeline/test_step3_main_compatibility.py
new file mode 100644
index 000000000..5d962d941
--- /dev/null
+++ b/tests/test_pipeline/test_step3_main_compatibility.py
@@ -0,0 +1,1515 @@
+"""Compare step 3 execution and public containers with the reviewed main."""
+
+from __future__ import annotations
+
+import asyncio
+import io
+import json
+import operator
+import os
+import re
+import subprocess
+import sys
+from collections.abc import Callable, Collection, Iterator, Sequence
+from dataclasses import asdict, dataclass, field, replace
+from datetime import datetime, timezone, tzinfo
+from itertools import count, product
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import patch
+from uuid import UUID
+from zipfile import ZipFile
+
+import pytest
+from deltalake import DeltaTable
+from typing_extensions import override
+
+from orcapod import Pipeline, PipelineJob, SourceNode, function_pod
+from orcapod.channels import ReadableChannel, WritableChannel
+from orcapod.core.nodes.operator_node import OperatorJobNode, OperatorNode
+from orcapod.core.nodes.source_node import slot_name_for
+from orcapod.core.operators import Join, SelectDataColumns, SelectTagColumns
+from orcapod.databases import DeltaTableDatabase, InMemoryArrowDatabase
+from orcapod.errors import InconsistentSourceError, UnboundSourceError
+from orcapod.operators import MergeJoin
+from orcapod.pipeline import AsyncPipelineOrchestrator, StatusObserver
+from orcapod.pipeline.base import InvocationGraph
+from orcapod.pipeline.dag import OrcaDAG
+from orcapod.pipeline.networkx_backend import NetworkxBackend
+from orcapod.pipeline.observer import NoOpObserver
+from orcapod.pipeline.pod_invocation import FunctionInvocation
+from orcapod.pipeline.run_summary import RunSummary
+from orcapod.pipeline.serialization import OPERATOR_REGISTRY, register_operator
+from orcapod.protocols.core_protocols import (
+ ArgumentGroup,
+ DataProtocol,
+ StreamProtocol,
+ TagProtocol,
+)
+from orcapod.sources import CSVSource, DictSource
+from orcapod.types import ColumnConfig, ContentHash, Schema, SchemaLike
+
+ROOT = Path(__file__).resolve().parents[2]
+MAIN = "26efe35aa0079aed07a29249b6a3d6ac071f805b"
+CALLS: list[int] = []
+
+
+@function_pod(output_keys="out")
+def double(x: int) -> int:
+ CALLS.append(x)
+ return x * 2
+
+
+def source(name: str, value: int) -> DictSource:
+ return DictSource(
+ [{"id": 1, "x": value}, {"id": 2, "x": value + 1}],
+ source_id=name,
+ tag_columns=["id"],
+ tag_only_columns=True,
+ )
+
+
+class FrozenClock(datetime):
+ @classmethod
+ @override
+ def now(cls, tz: tzinfo | None = None) -> datetime:
+ return cls(2026, 1, 1, tzinfo=timezone.utc).astimezone(tz)
+
+
+def stored_run(path: Path, mode: str) -> dict[str, Any]:
+ """Freeze generated fields so every stored column can be compared."""
+ CALLS.clear()
+ database = DeltaTableDatabase(path / "data")
+ observer = StatusObserver(status_database=DeltaTableDatabase(path / "status"))
+ with PipelineJob("compat", database=database) as job:
+ double.pod(source("a", 3), label="result_a")
+ # A single branch gives generated event IDs the same assignment order in
+ # both processes even when the async scheduler is under load.
+ job.bind(sources={"a": source("left", 3)})
+ results = count(1)
+ statuses = count(50)
+ correlations = count(100)
+ with (
+ patch(
+ "orcapod.core.data_function.uuid7",
+ side_effect=lambda: UUID(int=next(results)),
+ ),
+ patch("orcapod.core.result_cache.datetime", FrozenClock),
+ patch("orcapod.core.nodes.function_node.datetime", FrozenClock),
+ patch("orcapod.pipeline.status_observer.datetime", FrozenClock),
+ patch(
+ "orcapod.pipeline.status_observer.uuid7",
+ side_effect=lambda: UUID(int=next(statuses)),
+ ),
+ patch("uuid.uuid4", side_effect=lambda: UUID(int=next(correlations) << 64)),
+ ):
+ summary = (
+ asyncio.run(job.run_async(observer=observer))
+ if mode == "async"
+ else job.run(observer=observer)
+ )
+ tables = {}
+ for log in path.rglob("_delta_log"):
+ table = DeltaTable(str(log.parent)).to_pyarrow_table()
+ tables[str(log.parent.relative_to(path))] = {
+ "schema": str(table.schema),
+ "rows": sorted(table.to_pylist(), key=repr),
+ }
+ return {
+ "calls": sorted(CALLS),
+ "summary": {
+ "nodes": {label: asdict(node) for label, node in summary.nodes.items()},
+ "job_name": summary.job_name,
+ "load_only": summary.load_only,
+ "target": summary.target,
+ "unchecked_sources": summary.unchecked_sources,
+ "ran_nothing": summary.ran_nothing,
+ "lost_observer_events": summary.lost_observer_events,
+ "conditions": summary.conditions,
+ "limits": summary.limits,
+ "restricted_source_ids": summary.restricted_source_ids,
+ },
+ "tables": tables,
+ }
+
+
+@pytest.fixture(scope="module")
+def baseline(tmp_path_factory: pytest.TempPathFactory) -> Path | None:
+ archive = subprocess.run(
+ ["git", "archive", "--format=zip", MAIN, "src"],
+ cwd=ROOT,
+ capture_output=True,
+ check=False,
+ )
+ if archive.returncode:
+ return None
+ path = tmp_path_factory.mktemp("step3-main")
+ with ZipFile(io.BytesIO(archive.stdout)) as contents:
+ contents.extractall(path)
+ return path / "src"
+
+
+def probe(package: Path, *args: str) -> dict[str, Any]:
+ output = subprocess.check_output(
+ [sys.executable, str(Path(__file__).resolve()), *args],
+ cwd=ROOT,
+ env={**os.environ, "PYTHONPATH": os.pathsep.join(map(str, (package, ROOT)))},
+ text=True,
+ timeout=60,
+ )
+ return json.loads(output)
+
+
+def public_edge_iteration(receiver: str) -> dict[str, Any]:
+ root = source("root", 3)
+
+ def build() -> Pipeline | PipelineJob:
+ graph = (
+ PipelineJob("edges", database=InMemoryArrowDatabase())
+ if receiver == "job"
+ else Pipeline("edges")
+ )
+ with graph:
+ double.pod(root, label="result")
+ return graph
+
+ graph, other = build(), build()
+ own = graph.nodes["root"], graph.nodes["result"]
+ foreign = other.nodes["root"], other.nodes["result"]
+ assert own == foreign
+ assert own[0] is not foreign[0] and own[1] is not foreign[1]
+
+ edges = graph.dag.edges()
+ first = next(edges) if isinstance(edges, Iterator) else None
+ searched = graph.dag.edges()
+ matched = foreign in searched
+ return {
+ "type": type(edges).__name__,
+ "self_iterating": iter(edges) is edges,
+ "first_is_held": first is not None
+ and first[0] is own[0]
+ and first[1] is own[1],
+ "listed": [[up.label, down.label] for up, down in graph.dag.edges()],
+ "remaining_after_next": [[up.label, down.label] for up, down in edges],
+ "foreign_member": matched,
+ "mixed_members": [
+ (own[0], foreign[1]) in graph.dag.edges(),
+ (foreign[0], own[1]) in graph.dag.edges(),
+ ],
+ "reversed_member": (own[1], own[0]) in graph.dag.edges(),
+ "remaining_after_membership": [[up.label, down.label] for up, down in searched],
+ }
+
+
+@pytest.mark.parametrize("receiver", ["pipeline", "job"])
+def test_public_edges_match_main(baseline: Path | None, receiver: str) -> None:
+ actual = public_edge_iteration(receiver)
+ if baseline is not None:
+ assert actual == probe(baseline, "edges", receiver)
+ assert actual == {
+ "type": "generator",
+ "self_iterating": True,
+ "first_is_held": True,
+ "listed": [["root", "result"]],
+ "remaining_after_next": [],
+ "foreign_member": True,
+ "mixed_members": [True, True],
+ "reversed_member": False,
+ "remaining_after_membership": [],
+ }
+
+
+class CustomSelect(SelectDataColumns):
+ """A plain custom operator without step 1 identity support."""
+
+
+class CustomJoin(Join):
+ """Inherit the library's commutative symmetry."""
+
+
+class ExplicitCommutativeJoin(CustomJoin):
+ @override
+ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup:
+ return frozenset(streams)
+
+ @override
+ def identity_structure(self) -> Any:
+ return ("custom_join", 1)
+
+
+class OrderedJoin(CustomJoin):
+ @override
+ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup:
+ return tuple(streams)
+
+
+class IdentifiedOrderedJoin(OrderedJoin):
+ @override
+ def identity_structure(self) -> Any:
+ return ("ordered_join", 1)
+
+
+class ChooseFirst(IdentifiedOrderedJoin):
+ """Return the first input so swapping arguments changes the result."""
+
+ @override
+ def validate_nonzero_inputs(self, *streams: StreamProtocol) -> None:
+ pass
+
+ @override
+ def output_schema(
+ self,
+ *streams: StreamProtocol,
+ columns: ColumnConfig | dict[str, Any] | None = None,
+ all_info: bool = False,
+ ) -> tuple[Schema, Schema]:
+ return streams[0].output_schema(columns=columns, all_info=all_info)
+
+ @override
+ def static_process(self, *streams: StreamProtocol) -> StreamProtocol:
+ return streams[0]
+
+ @override
+ async def async_execute(
+ self,
+ inputs: Sequence[ReadableChannel[tuple[TagProtocol, DataProtocol]]],
+ output: WritableChannel[tuple[TagProtocol, DataProtocol]],
+ *,
+ input_pipeline_hashes: Sequence[ContentHash],
+ ) -> None:
+ async def drain() -> None:
+ async for _ in inputs[1]:
+ pass
+
+ async with asyncio.TaskGroup() as tasks:
+ _ = tasks.create_task(drain())
+ async for pair in inputs[0]:
+ await output.send(pair)
+ await output.close()
+
+ @override
+ def identity_structure(self) -> tuple[str, int]:
+ return ("choose_first", 1)
+
+
+class IdentifiedSelect(CustomSelect):
+ @override
+ def argument_symmetry(self, streams: Collection[StreamProtocol]) -> ArgumentGroup:
+ return tuple(streams)[0]
+
+ @override
+ def identity_structure(self) -> Any:
+ return ("custom_select_x", 1)
+
+
+CUSTOM_OPERATORS = (
+ CustomJoin,
+ ExplicitCommutativeJoin,
+ OrderedJoin,
+ IdentifiedOrderedJoin,
+ CustomSelect,
+ IdentifiedSelect,
+)
+
+
+@function_pod(output_keys="out")
+def adjust(x: int, y: int) -> int:
+ return x * 100 + y + 1
+
+
+def custom_operator_case(
+ directory: Path,
+ operator: str,
+ mode: str,
+ receiver: str,
+ order: str,
+ sources: str,
+) -> dict[str, Any]:
+ """Observe downstream rows, saved bytes and a fresh load of the same job."""
+ directory.mkdir(parents=True, exist_ok=True)
+
+ def csv_source(name: str, column: str, value: int) -> CSVSource:
+ path = directory / f"{name}.csv"
+ _ = path.write_text(f"id,{column}\n1,{value}\n2,{value + 1}\n")
+ return CSVSource(
+ str(path), source_id=name, tag_columns=["id"], tag_only_columns=True
+ )
+
+ operator_class = next(cls for cls in CUSTOM_OPERATORS if cls.__name__ == operator)
+ database = InMemoryArrowDatabase()
+ graph = (
+ Pipeline("custom_operator")
+ if receiver == "pipeline"
+ else PipelineJob("custom_operator", database=database)
+ )
+ unary = issubclass(operator_class, CustomSelect)
+ original = (csv_source("a", "x", 2), csv_source("b", "x" if unary else "y", 5))
+ repeated = (
+ original
+ if sources == "shared"
+ else (csv_source("c", "x", 12), csv_source("d", "x" if unary else "y", 15))
+ )
+ second_inputs = repeated[::-1] if order == "reverse" else repeated
+ first_args = original[:1] if unary else original
+ second_args = second_inputs[:1] if unary else second_inputs
+ with graph:
+ if issubclass(operator_class, CustomSelect):
+ first_pod, second_pod = operator_class(["x"]), operator_class(["x"])
+ else:
+ first_pod, second_pod = operator_class(), operator_class()
+ _ = first_pod(*first_args, label="first")
+ second = second_pod(*second_args, label="second")
+ _ = (double if unary else adjust).pod(second, label="adjusted")
+ job = (
+ graph
+ if isinstance(graph, PipelineJob)
+ else PipelineJob.from_pipeline(
+ graph,
+ sources={
+ stream.source_name: stream for stream in (*first_args, *second_args)
+ },
+ database=database,
+ )
+ )
+
+ def observe(target: PipelineJob, *, load_only: bool = False) -> dict[str, Any]:
+ summary = (
+ asyncio.run(target.run_async(load_only=load_only))
+ if mode == "async"
+ else target.run(load_only=load_only)
+ )
+ node = target.function_pods["adjusted"]
+ return {
+ "ok": summary.ok,
+ "computed": summary.nodes["adjusted"].computed,
+ "rows": sorted(node.as_table()["out"].to_pylist()),
+ }
+
+ path = directory / "job.json"
+ with (
+ patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: UUID(int=1))),
+ patch("orcapod.__version__", "0.4.0"),
+ patch.dict(OPERATOR_REGISTRY),
+ ):
+ register_operator(operator, operator_class)
+ live = observe(job)
+ job.save(path)
+ saved = path.read_bytes().decode()
+ restored = PipelineJob.load(path, database=database)
+ loaded = observe(restored, load_only=True)
+ restored.save(path)
+ return {
+ "live": live,
+ "loaded": loaded,
+ "saved": saved,
+ "resaved": path.read_bytes().decode(),
+ "operators": sorted(job.operator_pods),
+ }
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_r82_reversed_custom_join_keeps_downstream_rows(
+ tmp_path: Path, mode: str
+) -> None:
+ actual = custom_operator_case(
+ tmp_path, "CustomJoin", mode, "job", "reverse", "shared"
+ )
+ assert actual["live"] == {
+ "ok": True,
+ "computed": 2,
+ "rows": [206, 307],
+ }
+ assert actual["loaded"] == {**actual["live"], "computed": 0}
+
+
+def custom_operator_matrix(path: Path, operator: str) -> dict[str, Any]:
+ result = {}
+ for case in product(
+ ("sync", "async"),
+ ("job", "pipeline"),
+ ("forward", "reverse"),
+ ("shared", "distinct"),
+ ):
+ key = "-".join(case)
+ result[key] = custom_operator_case(path / key, operator, *case)
+ return result
+
+
+def capture_after_mutation(
+ path: Path, mutation: str, mode: str, incoming: str, relation: str, clean: bool
+) -> dict[str, Any]:
+ """Observe a job whose first branch changes before the second capture."""
+ initial = source("left", 3)
+ other = source("right", 8)
+ final = other if relation == "moves_away" else initial
+ offered = (
+ final
+ if relation == "equal"
+ else (initial if relation == "moves_away" else other)
+ )
+ rewires = mutation in ("rewire", "recompile") and not clean
+ before = (initial if relation == "moves_away" else other) if rewires else final
+ project = SelectDataColumns(["x"])
+ holder = OperatorJobNode(project, (before,), label="holder")
+ job = PipelineJob("mutation", database=InMemoryArrowDatabase())
+ with job:
+ double.pod(holder, label="held_result")
+ slot_name = slot_name_for(holder)
+ if rewires:
+ holder.upstreams = (final,)
+ if mutation == "bind":
+ job.bind(sources={slot_name: holder})
+ elif mutation == "rebind":
+ slot = job.source_pods[slot_name]
+ slot.bound_source = project(initial if final is other else other)
+ # Extending a job requires its captured binding to be restored.
+ slot.bound_source = holder
+ elif mutation == "recompile":
+ job.compile()
+ _ = holder.run()
+
+ before_labels = sorted(job.nodes)
+ external = project(offered, label="incoming") if incoming == "slot" else None
+ try:
+ with job:
+ step = project(offered, label="incoming") if external is None else external
+ double.pod(step, label="new_result")
+ except InconsistentSourceError as exc:
+ assert sorted(job.nodes) == before_labels
+ return {"refused": str(exc)}
+
+ with (
+ patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: UUID(int=1))),
+ patch("orcapod.__version__", "0.4.0"),
+ ):
+ try:
+ summary = asyncio.run(job.run_async()) if mode == "async" else job.run()
+ rows = {
+ label: sorted(job.nodes[label].as_table()["out"].to_pylist())
+ for label in ("held_result", "new_result")
+ }
+ except KeyError:
+ return {"legacy_missing_input": True}
+ job.save(path)
+ return {"ok": summary.ok, "rows": rows, "saved": path.read_text()}
+
+
+def capture_mutation_matrix(directory: Path, mode: str, clean: bool) -> dict[str, Any]:
+ directory.mkdir(parents=True, exist_ok=True)
+ results = {}
+ for mutation, incoming, relation in product(
+ ("rewire", "bind", "rebind", "recompile"),
+ ("step", "slot"),
+ ("distinct", "equal", "moves_away"),
+ ):
+ key = f"{mutation}-{incoming}-{relation}"
+ results[key] = capture_after_mutation(
+ directory / f"{key}.json", mutation, mode, incoming, relation, clean
+ )
+ return results
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_capture_after_mutation_against_main(
+ tmp_path: Path, baseline: Path | None, mode: str
+) -> None:
+ actual = probe(ROOT / "src", "capture-mutation", str(tmp_path / "head"), mode)
+ # Main's capture keys are tied to the original input digest. Start main
+ # from the final inputs so its expected rows can also cover rewired jobs.
+ expected = (
+ probe(baseline, "capture-mutation", str(tmp_path / "main"), mode, "clean")
+ if baseline is not None
+ else {}
+ )
+ for key, observed in actual.items():
+ if key.endswith("-equal"):
+ assert "share a legacy execution identity" in observed["refused"], key
+ else:
+ rows = (
+ {"held_result": [16, 18], "new_result": [6, 8]}
+ if key.endswith("-moves_away")
+ else {"held_result": [6, 8], "new_result": [16, 18]}
+ )
+ assert observed["ok"] and observed["rows"] == rows, key
+ if key in expected:
+ assert observed["rows"] == expected[key]["rows"], key
+ if key.startswith(("bind-", "rebind-")):
+ assert observed["saved"] == expected[key]["saved"], key
+
+
+@pytest.mark.parametrize("operator", [cls.__name__ for cls in CUSTOM_OPERATORS])
+def test_custom_operator_execution_matrix(
+ tmp_path: Path, baseline: Path | None, operator: str
+) -> None:
+ if baseline is None:
+ pytest.skip("The frozen main revision is unavailable.")
+ args = ("operators", str(tmp_path), operator)
+ main = probe(baseline, *args)
+ branch = probe(ROOT / "src", *args)
+ assert branch.keys() == main.keys()
+ ordered = operator in {"OrderedJoin", "IdentifiedOrderedJoin"}
+ for key, outcome in branch.items():
+ if ordered:
+ # Main used commutative hashes even for these declared tuple groups.
+ assert outcome["live"] == main[key]["live"], key
+ assert outcome["loaded"] == main[key]["loaded"], key
+ assert outcome["saved"] == outcome["resaved"], key
+ if key.endswith("reverse-shared"):
+ assert outcome["operators"] == ["first", "second"], key
+ assert main[key]["operators"] == ["first"], key
+ else:
+ assert outcome == main[key], key
+ for phase in ("live", "loaded"):
+ assert outcome[phase]["ok"], (key, phase)
+ assert len(outcome[phase]["rows"]) == 2, (key, phase)
+
+
+def run_job(job: PipelineJob, mode: str, *, load_only: bool = False) -> RunSummary:
+ return (
+ asyncio.run(job.run_async(load_only=load_only))
+ if mode == "async"
+ else job.run(load_only=load_only)
+ )
+
+
+def ordered_case(receiver: str, mode: str) -> dict[str, list[int]]:
+ a, b = source("a", 3), source("b", 8)
+ database = InMemoryArrowDatabase()
+ graph = (
+ Pipeline("ordered")
+ if receiver == "pipeline"
+ else PipelineJob(database=database)
+ )
+ with graph:
+ _ = double.pod(ChooseFirst()(a, b, label="left"), label="first")
+ _ = double.pod(ChooseFirst()(b, a, label="right"), label="second")
+ job = (
+ graph
+ if isinstance(graph, PipelineJob)
+ else PipelineJob.from_pipeline(
+ graph, sources={"a": a, "b": b}, database=database
+ )
+ )
+ assert run_job(job, mode).ok
+ return {
+ label: sorted(node.as_table()["out"].to_pylist())
+ for label, node in job.function_pods.items()
+ }
+
+
+@pytest.mark.parametrize("receiver", ["job", "pipeline"])
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_r83_ordered_custom_operator_keeps_both_branches(
+ baseline: Path | None, receiver: str, mode: str
+) -> None:
+ actual = ordered_case(receiver, mode)
+ assert actual == {"first": [6, 8], "second": [16, 18]}
+ if baseline is not None:
+ main = probe(baseline, "ordered", receiver, mode)
+ assert main == {"first": actual["first"]}
+
+
+@pytest.mark.parametrize("receiver", [Pipeline, PipelineJob])
+@pytest.mark.parametrize("replace_export", [False, True])
+def test_r84_import_refuses_a_foreign_invocation_output(
+ baseline: Path | None,
+ receiver: type[Pipeline] | type[PipelineJob],
+ replace_export: bool,
+) -> None:
+ with Pipeline("original") as original:
+ first = double.pod(source("a", 3), label="first")
+ _ = increment.pod(first, label="second")
+ with Pipeline("foreign") as foreign:
+ _ = double.pod(source("foreign", 8), label="foreign")
+ exported = original.to_invocations()
+ assert set(receiver.from_invocations(exported).nodes) == {"a", "first", "second"}
+ invocations = (
+ exported.invocations[0],
+ FunctionInvocation(exported.invocations[1].pod, (foreign.foreign,), "second"),
+ )
+ outputs = (foreign.foreign, exported.outputs[1])
+ malformed = (
+ replace(exported, invocations=invocations, outputs=outputs)
+ if replace_export
+ else InvocationGraph(invocations, exported.source_streams, outputs)
+ )
+ kind = "job" if receiver is PipelineJob else "pipeline"
+ message = (
+ f"Capturing source slot 'foreign' from outside this {kind} is not supported "
+ "yet (ITL-1559). Pass the source itself, or use node.as_source() to read "
+ "another job's stored results."
+ )
+ with pytest.raises(InconsistentSourceError, match=f"^{re.escape(message)}$"):
+ _ = receiver.from_invocations(malformed)
+ assert set(receiver.from_invocations(exported).nodes) == {"a", "first", "second"}
+ if baseline is not None:
+ assert probe(baseline, "exports") == {"positional_outputs": False}
+
+
+@function_pod(output_keys="result")
+def increment(out: int) -> int:
+ return out + 1
+
+
+def tagged(name: str, value: int, *, extra: bool = False) -> DictSource:
+ rows = [{"id": 1, "x": value}, {"id": 2, "x": value + 1}]
+ if extra:
+ for row in rows:
+ row["extra"] = row["x"] + 100
+ return DictSource(
+ rows,
+ source_id=name,
+ tag_columns=["id", "x"],
+ tag_only_columns=["id"],
+ )
+
+
+def blueprint_boundary_case(directory: Path, case: str, mode: str) -> dict[str, Any]:
+ graph = Pipeline("boundary")
+ bindings: dict[str, StreamProtocol]
+ if case == "standalone":
+ external = OperatorNode(
+ Join(), (tagged("a", 3), tagged("b", 3)), label="external"
+ )
+ with graph:
+ _ = external.select_tag_columns(["id"], label="second")
+ bindings = {slot_name_for(external): tagged("replacement", 8)}
+ column = "x"
+ else:
+ a = source("a", 3)
+ with graph:
+ first = double.pod(a, label="first")
+ with graph:
+ _ = increment.pod(graph.first if case == "held" else first, label="second")
+ bindings = {"a": a}
+ column = "result"
+
+ path = directory / "blueprint.json"
+ with patch("orcapod.__version__", "0.4.0"):
+ graph.save(path)
+ job = PipelineJob.from_pipeline(
+ graph, sources=bindings, database=InMemoryArrowDatabase()
+ )
+ assert run_job(job, mode).ok
+ return {
+ "nodes": sorted(graph.nodes),
+ "predecessors": sorted(
+ node.label for node in graph.dag.predecessors(graph.second)
+ ),
+ "saved": path.read_text(),
+ "rows": sorted(job.second.as_table()[column].to_pylist()),
+ }
+
+
+@pytest.mark.parametrize("case", ["invocation", "standalone"])
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_blueprint_capture_boundary_against_main(
+ tmp_path: Path, baseline: Path | None, case: str, mode: str
+) -> None:
+ args = ("blueprint", str(tmp_path), case, mode)
+ actual = probe(ROOT / "src", *args)
+ assert actual["rows"] == ([8, 9] if case == "standalone" else [7, 9])
+ if baseline is not None:
+ assert actual == probe(baseline, *args)
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_r85_refuses_late_capture_of_compiled_blueprint_step(
+ tmp_path: Path, baseline: Path | None, mode: str
+) -> None:
+ a = source("a", 3)
+ with Pipeline("boundary") as graph:
+ first = double.pod(a, label="first")
+
+ path = tmp_path / "preserved.json"
+ with patch("orcapod.__version__", "0.4.0"):
+ graph.save(path)
+ recorded = path.read_bytes()
+ with graph:
+ with pytest.raises(
+ InconsistentSourceError,
+ match="compiled blueprint step 'first'.*original invocation stream",
+ ):
+ _ = increment.pod(graph.first, label="second")
+ graph.save(path)
+ assert path.read_bytes() == recorded
+ assert set(graph.nodes) == {"a", "first"}
+
+ with graph:
+ _ = increment.pod(first, label="second")
+ job = PipelineJob.from_pipeline(
+ graph, sources={"a": a}, database=InMemoryArrowDatabase()
+ )
+ assert run_job(job, mode).ok
+ assert sorted(job.second.as_table()["result"].to_pylist()) == [7, 9]
+ if baseline is not None:
+ legacy = probe(baseline, "blueprint", str(tmp_path), "held", mode)
+ invocation = probe(baseline, "blueprint", str(tmp_path), "invocation", mode)
+ assert legacy["rows"] == []
+ assert legacy["predecessors"] != invocation["predecessors"] == ["first"]
+ assert legacy["saved"] != invocation["saved"]
+ assert len(legacy["nodes"]) == 4
+
+
+@function_pod(output_keys="out")
+def triple(x: int) -> int:
+ return x * 3
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("schema_change", [False, True], ids=["wire-key", "schema"])
+def test_r87_refuses_rewiring_a_captured_descriptor(
+ mode: str, schema_change: bool, tmp_path: Path
+) -> None:
+ a, b = tagged("a", 3), tagged("b", 3)
+ descriptor = OperatorNode(Join(), (a, b), label="external")
+ slot = slot_name_for(descriptor)
+ path = tmp_path / "blueprint.json"
+
+ def capture(external: OperatorNode) -> tuple[Pipeline, StreamProtocol]:
+ with Pipeline("rewired") as graph:
+ first = SelectTagColumns(["id"])(external, label="original")
+ _ = double.pod(first, label="early")
+ return graph, first
+
+ control, original = capture(OperatorNode(Join(), (a, b), label="external"))
+ with control:
+ _ = triple.pod(original, label="late")
+ control.save(path)
+ expected = path.read_bytes()
+
+ graph, first = capture(descriptor)
+ graph.save(path)
+ before = path.read_bytes()
+ inputs = (a, tagged("extra", 3, extra=True)) if schema_change else (a, b, b)
+
+ with graph:
+ with pytest.raises(
+ InconsistentSourceError,
+ match="Cannot rewire.*external.*captured blueprint.*new descriptor",
+ ):
+ descriptor.upstreams = inputs
+ graph.save(path)
+ assert path.read_bytes() == before
+ assert slot_name_for(descriptor) == slot
+
+ descriptor.upstreams = (a, b)
+ with graph:
+ _ = triple.pod(first, label="late")
+ graph.save(path)
+ assert path.read_bytes() == expected
+
+ assert set(graph.nodes) == {slot, "original", "early", "late"}
+ for label in ("early", "late"):
+ assert {node.label for node in graph.dag.predecessors(graph.nodes[label])} == {
+ "original"
+ }
+ job = PipelineJob.from_pipeline(
+ graph,
+ sources={slot: tagged("replacement", 30)},
+ database=InMemoryArrowDatabase(),
+ )
+ assert run_job(job, mode).ok
+ assert sorted(job.early.as_table()["out"].to_pylist()) == [60, 62]
+ assert sorted(job.late.as_table()["out"].to_pylist()) == [90, 93]
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_r87_compile_refuses_a_changed_slot_schema(
+ mode: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ descriptor = OperatorNode(
+ Join(), (tagged("a", 3), tagged("b", 3)), label="external"
+ )
+ slot = slot_name_for(descriptor)
+ with Pipeline("changed_schema") as graph:
+ first = SelectTagColumns(["id"])(descriptor, label="original")
+ _ = double.pod(SelectDataColumns(["x"])(first), label="early")
+ path = tmp_path / "blueprint.json"
+ graph.save(path)
+ before = path.read_bytes()
+ held_slot = graph.nodes[slot]
+
+ # Simulate an external schema refresh independently of the guarded setter.
+ replacement = tagged("extra", 3, extra=True)
+ with monkeypatch.context() as changing:
+ changing.setattr(descriptor, "output_schema", replacement.output_schema)
+ changing.setattr(
+ descriptor,
+ "_typed_zero_row_table",
+ replacement._typed_zero_row_table, # pyright: ignore[reportPrivateUsage] # coherent Arrow schema for the refreshed metadata
+ )
+ with pytest.raises(
+ InconsistentSourceError, match="Cannot recompile.*slot.*schema changed"
+ ):
+ with graph:
+ pass
+ assert graph.nodes[slot] is held_slot
+
+ graph.save(path)
+ assert path.read_bytes() == before
+ job = PipelineJob.from_pipeline(
+ graph,
+ sources={slot: tagged("replacement", 30)},
+ database=InMemoryArrowDatabase(),
+ )
+ assert run_job(job, mode).ok
+ assert sorted(job.early.as_table()["out"].to_pylist()) == [60, 62]
+
+
+def cross_store_case(
+ directory: Path, case: str, mode: str, action: str
+) -> dict[str, Any]:
+ directory.mkdir(parents=True, exist_ok=True)
+ database = DeltaTableDatabase(directory / "store")
+ path = directory / "job.json"
+
+ def csv_source(name: str, column: str, value: int) -> CSVSource:
+ csv_path = directory / f"{name}.csv"
+ _ = csv_path.write_text(f"id,{column}\n1,{value}\n2,{value + 1}\n")
+ return CSVSource(
+ str(csv_path), source_id=name, tag_columns=["id"], tag_only_columns=True
+ )
+
+ with (
+ patch.dict(OPERATOR_REGISTRY),
+ patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: UUID(int=1))),
+ patch("orcapod.__version__", "0.4.0"),
+ ):
+ register_operator("ChooseFirst", ChooseFirst)
+ register_operator("CustomJoin", CustomJoin)
+ if action == "write":
+ with PipelineJob("cross_store", database=database) as job:
+ a = csv_source("a", "x", 3)
+ if case == "commutative":
+ b = csv_source("b", "y", 5)
+ _ = CustomJoin()(a, b, label="first")
+ joined = CustomJoin()(b, a, label="second")
+ _ = adjust.pod(joined, label="result")
+ elif case == "ordered":
+ b = csv_source("b", "x", 8)
+ _ = double.pod(ChooseFirst()(a, b, label="left"), label="first")
+ _ = double.pod(ChooseFirst()(b, a, label="right"), label="second")
+ else:
+ first = double.pod(a, label="first")
+ _ = increment.pod(first, label="second")
+ summary = run_job(job, mode)
+ job.save(path)
+ else:
+ job = PipelineJob.load(path, database=database)
+ summary = run_job(job, mode, load_only=True)
+ assert summary.ok
+ return {
+ label: {
+ "rows": sorted(
+ node.as_table()[
+ "result" if case == "functions" and label == "second" else "out"
+ ].to_pylist()
+ ),
+ "computed": summary.nodes[label].computed,
+ "reused": summary.nodes[label].reused,
+ }
+ for label, node in job.function_pods.items()
+ }
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+@pytest.mark.parametrize("case", ["functions", "commutative", "ordered"])
+def test_saved_jobs_read_each_others_stores(
+ tmp_path: Path, baseline: Path | None, case: str, mode: str
+) -> None:
+ if baseline is None:
+ pytest.skip("The frozen main revision is unavailable.")
+ branch = ROOT / "src"
+ wire = []
+ for index, (writer, reader) in enumerate(((baseline, branch), (branch, baseline))):
+ directory = tmp_path / str(index)
+ args = ("cross-store", str(directory), case, mode)
+ written = probe(writer, *args, "write")
+ read = probe(reader, *args, "read")
+ assert written.keys() == read.keys()
+ if case == "ordered":
+ assert {label: values["rows"] for label, values in written.items()} == (
+ {"first": [6, 8]}
+ if writer == baseline
+ else {"first": [6, 8], "second": [16, 18]}
+ )
+ for label, entry in written.items():
+ assert entry == {"rows": read[label]["rows"], "computed": 2, "reused": 0}
+ assert read[label]["computed"] == 0
+ assert read[label]["reused"] == 2
+ wire.append(
+ (directory / "job.json")
+ .read_bytes()
+ .replace(str(directory).encode(), b"")
+ )
+ if case != "ordered":
+ assert wire[0] == wire[1]
+
+
+class NodeStarts(NoOpObserver):
+ def __init__(self) -> None:
+ self.addresses: dict[str, str] = {}
+ self.ends: dict[str, str] = {}
+ self.uri = ""
+
+ @override
+ def on_run_start(self, run_id: str, pipeline_uri: str = "") -> None:
+ self.uri = pipeline_uri
+
+ @override
+ def on_node_end(self, node_label: str, node_hash: str) -> None:
+ self.ends[node_label] = node_hash
+
+ @override
+ def on_node_start(
+ self, node_label: str, node_hash: str, tag_schema: SchemaLike | None = None
+ ) -> None:
+ self.addresses[node_label] = node_hash
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_legacy_keys_and_observer_addresses_survive_binding(mode: str) -> None:
+ dataset = source("a", 3)
+ with Pipeline("fallback") as blueprint:
+ slot = SourceNode.from_stream(dataset, name="a")
+ double.pod(CustomSelect(["x"])(slot, label="step"), label="result")
+ job = PipelineJob.from_pipeline(blueprint, database=InMemoryArrowDatabase())
+ keys = {attrs["label"]: key for key, attrs in job._hash_graph.nodes.items()}
+ assert keys["step"].startswith("legacy:")
+ assert keys["result"].startswith("legacy:")
+ for dataset in (dataset, source("replacement", 13)):
+ job.bind(sources={"a": dataset})
+ observer = NodeStarts()
+ summary = (
+ asyncio.run(job.run_async(observer=observer))
+ if mode == "async"
+ else job.run(observer=observer)
+ )
+ assert observer.addresses == {
+ label: job.nodes[label].content_hash().to_string() for label in keys
+ }
+ assert set(summary.nodes) == {"result"}
+ job.compile()
+ assert {
+ attrs["label"]: key for key, attrs in job._hash_graph.nodes.items()
+ } == keys
+ assert set(job._hash_graph.nodes) == set(keys.values())
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_run_rows_and_uri_match_main(
+ tmp_path: Path, baseline: Path | None, mode: str
+) -> None:
+ actual = probe(ROOT / "src", str(tmp_path / "branch"), mode)
+ assert actual["calls"] == [3, 4]
+ assert set(actual["summary"]["nodes"]) == {"result_a"}
+ assert actual["summary"]["nodes"]["result_a"]["computed"] == 2
+ if baseline is not None:
+ assert actual == probe(baseline, str(tmp_path / "main"), mode)
+
+
+def public_listings(graph: Pipeline | PipelineJob) -> dict[str, Any]:
+ """Record public labels and adjacency with the node each label refers to."""
+ dag = graph.dag
+ listed = list(dag.nodes())
+ assert sorted(map(id, listed)) == sorted(map(id, graph.nodes.values()))
+ for label, node in graph.nodes.items():
+ assert getattr(graph, label) is node
+
+ def adjacency(node: Any) -> list[Any]:
+ values = []
+ for related in (
+ dag.predecessors(node),
+ dag.successors(node),
+ dag.ancestors(node),
+ ):
+ assert isinstance(related, frozenset)
+ assert hash(related) == hash(frozenset(iter(related)))
+ values.append(sorted(other.label for other in related))
+ return [*values, dag.in_degree(node)]
+
+ def identity(node: Any) -> str:
+ try:
+ return node.content_hash().to_string()
+ except UnboundSourceError:
+ return node.node_hash().to_string()
+
+ return {
+ "nodes": {label: identity(node) for label, node in graph.nodes.items()},
+ "source_pods": sorted(graph.source_pods),
+ "function_pods": sorted(graph.function_pods),
+ "operator_pods": sorted(graph.operator_pods),
+ "dag_nodes": sorted(node.label for node in listed),
+ "dag_iter": sorted(node.label for node in dag),
+ "topological_sort": sorted(node.label for node in dag.topological_sort()),
+ "edges": sorted((up.label, down.label) for up, down in dag.edges()),
+ "adjacency": {node.label: adjacency(node) for node in listed},
+ "runnable": {label: graph.is_runnable(label) for label in graph.nodes}
+ if isinstance(graph, PipelineJob)
+ else {},
+ }
+
+
+def public_lifecycle(path: Path, mode: str) -> dict[str, Any]:
+ """Compare label assignment and observer addresses across the graph lifecycle."""
+ database = InMemoryArrowDatabase()
+ job = PipelineJob("compat", database=database)
+
+ def csv_source(name: str, first: int) -> CSVSource:
+ file = path.with_name(f"{name}.csv")
+ file.write_text(f"id,x\n1,{first}\n2,{first + 1}\n")
+ return CSVSource(
+ str(file), source_id=name, tag_columns=["id"], tag_only_columns=True
+ )
+
+ with job:
+ double.pod(csv_source("a", 3), label="d")
+ select = SelectDataColumns(["x"])(csv_source("b", 8), label="select")
+ double.pod(select, label="d")
+ public = {
+ "captured": public_listings(job),
+ "blueprint": public_listings(job.pipeline),
+ }
+ job.compile()
+ public["recompiled"] = public_listings(job)
+
+ def observe(job: PipelineJob, *, load_only: bool = False) -> dict[str, Any]:
+ observer = NodeStarts()
+ if mode == "async":
+ asyncio.run(job.run_async(observer=observer, load_only=load_only))
+ else:
+ job.run(observer=observer, load_only=load_only)
+ return {
+ "starts": observer.addresses,
+ "ends": observer.ends,
+ "uri": observer.uri,
+ }
+
+ fixed_run_id = UUID("01234567-89ab-4def-8abc-0123456789ab")
+ with (
+ patch("orcapod.pipeline.job.uuid", SimpleNamespace(uuid4=lambda: fixed_run_id)),
+ patch("orcapod.__version__", "0.4.0"),
+ ):
+ addresses = {"first": observe(job)}
+ job.save(path)
+ public["run"] = public_listings(job)
+ job.bind(sources={"a": csv_source("replacement", 13)})
+ addresses["rebound"] = observe(job)
+ loaded = PipelineJob.load(path, database=database)
+ public["loaded"] = public_listings(loaded)
+ for node in (*loaded.function_pods.values(), *loaded.operator_pods.values()):
+ node.clear_cache()
+ public["cleared"] = public_listings(loaded)
+ addresses["loaded"] = observe(loaded, load_only=True)
+ rows = {
+ label: sorted(node.as_table()["out"].to_pylist())
+ for label, node in loaded.function_pods.items()
+ }
+ return {
+ "listings": public,
+ "addresses": addresses,
+ "rows": rows,
+ "saved": path.read_text(),
+ }
+
+
+@pytest.mark.parametrize("mode", ["sync", "async"])
+def test_r65_duplicate_explicit_labels_and_public_lifecycle_match_main(
+ tmp_path: Path, baseline: Path | None, mode: str
+) -> None:
+ actual = probe(ROOT / "src", "public", str(tmp_path / "branch.json"), mode)
+ assert set(actual["rows"]) == {"d_1", "d_2"}
+ assert sorted(actual["rows"].values()) == [[6, 8], [16, 18]]
+ for state in ("first", "rebound", "loaded"):
+ addresses = actual["addresses"][state]
+ assert addresses["starts"] == addresses["ends"]
+ assert addresses["starts"]
+ assert all(
+ digest.startswith(("content_hash_v1:", "semantic_v1:"))
+ for digest in addresses["starts"].values()
+ )
+ if baseline is not None:
+ assert actual == probe(baseline, "public", str(tmp_path / "main.json"), mode)
+
+
+@dataclass(frozen=True, order=True)
+class Vertex:
+ key: str
+ metadata: str = field(compare=False)
+
+
+def standalone_edge_operands(alias_end: str) -> dict[str, Any]:
+ held = Vertex("held", "vertex registration")
+ alias = Vertex("held", "edge registration")
+ other = Vertex("other", "other endpoint")
+ graph: OrcaDAG[Vertex] = OrcaDAG()
+ graph.add_node(other)
+ graph.add_node(held)
+ up, down = (alias, other) if alias_end == "source" else (other, alias)
+ graph.add_edge(up, down)
+ # Equal operands on a repeated insertion keep the original edge keys.
+ duplicate = (held, other) if alias_end == "source" else (other, held)
+ graph.add_edge(*duplicate)
+ return {
+ "nodes": [node.metadata for node in graph.nodes()],
+ "edges": [[u.metadata, v.metadata] for u, v in graph.edges()],
+ "successors": [node.metadata for node in graph.successors(up)],
+ "predecessors": [node.metadata for node in graph.predecessors(down)],
+ "ancestors": [node.metadata for node in graph.ancestors(down)],
+ "topological": [node.metadata for node in graph.topological_sort()],
+ "deterministic": [
+ node.metadata for node in graph.topological_sort_deterministic()
+ ],
+ }
+
+
+@pytest.mark.parametrize("alias_end", ["source", "target"])
+def test_standalone_dag_retains_edge_operands(
+ baseline: Path | None, alias_end: str
+) -> None:
+ actual = standalone_edge_operands(alias_end)
+ if baseline is not None:
+ assert actual == probe(baseline, "standalone-edges", alias_end)
+ assert actual["nodes"] == ["other endpoint", "vertex registration"]
+ if alias_end == "source":
+ assert actual["edges"] == [["vertex registration", "other endpoint"]]
+ assert actual["predecessors"] == actual["ancestors"] == ["edge registration"]
+ assert actual["topological"] == ["edge registration", "other endpoint"]
+ else:
+ assert actual["edges"] == [["other endpoint", "edge registration"]]
+ assert actual["successors"] == ["edge registration"]
+ assert actual["deterministic"] == ["other endpoint", "edge registration"]
+
+
+def standalone_join(binding: str, order: str, state: str) -> dict[str, Any]:
+ with Pipeline("blueprint") as blueprint:
+ double.pod(source("slot", 0), label="output")
+ left = source("left", 3)
+ right = left if binding == "same" else source("right", 8)
+ first, second = (
+ PipelineJob.from_pipeline(
+ blueprint, sources={"slot": bound}, database=InMemoryArrowDatabase()
+ )
+ for bound in (left, right)
+ )
+ inputs = (first.output, second.output)
+ if order == "reverse":
+ inputs = inputs[::-1]
+ if state == "warm":
+ first.run()
+ second.run()
+ CALLS.clear()
+ operator = MergeJoin()
+ operator.validate_inputs(*inputs)
+ joined = OperatorJobNode(operator, inputs, label="combined")
+ return {
+ "rows": joined.run().as_table()["out"].to_pylist(),
+ "equal_content": inputs[0].content_hash() == inputs[1].content_hash(),
+ "computed_inputs": sorted(CALLS),
+ }
+
+
+@pytest.mark.parametrize("binding", ["distinct", "same"])
+@pytest.mark.parametrize("order", ["forward", "reverse"])
+@pytest.mark.parametrize("state", ["cold", "warm"])
+@pytest.mark.filterwarnings("ignore:MergeJoin is provisional")
+def test_standalone_join_of_two_job_instances_matches_main(
+ baseline: Path | None, binding: str, order: str, state: str
+) -> None:
+ rows = [[6, 6], [8, 8]] if binding == "same" else [[6, 16], [8, 18]]
+ if order == "reverse":
+ rows = [row[::-1] for row in rows]
+ cold_calls = [3, 4] if binding == "same" else [3, 4, 8, 9]
+ expected = {
+ "rows": rows,
+ "equal_content": binding == "same",
+ "computed_inputs": [] if state == "warm" else cold_calls,
+ }
+ if baseline is not None:
+ assert expected == probe(baseline, "standalone-join", binding, order, state)
+ assert standalone_join(binding, order, state) == expected
+
+
+@function_pod(output_keys="adjusted")
+def adjust_output(out: int) -> int:
+ return out + 1
+
+
+def standalone_graph_surface() -> dict[str, Any]:
+ """Observe public topology, object representatives, views, and graph errors."""
+
+ def caught(call: Callable[[], Any]) -> Any:
+ try:
+ return call()
+ except Exception as error:
+ return [type(error).__name__, str(error)]
+
+ def adjacency(nodes: frozenset[Any], describe: Callable[[Any], str]) -> list[Any]:
+ return [type(nodes).__name__, sorted(map(describe, nodes))]
+
+ def topology(
+ dag: Any, describe: Callable[[Any], str], operands: dict[str, Any]
+ ) -> dict[str, Any]:
+ return {
+ "length": len(dag),
+ "iteration": [describe(node) for node in dag],
+ "vertices": [describe(node) for node in dag.nodes()],
+ "edges": [[describe(up), describe(down)] for up, down in dag.edges()],
+ "topological": caught(
+ lambda: [describe(node) for node in dag.topological_sort()]
+ ),
+ "deterministic": caught(
+ lambda: [
+ describe(node) for node in dag.topological_sort_deterministic()
+ ]
+ ),
+ "operands": {
+ name: {
+ "contains": caught(lambda: node in dag),
+ "attributes": caught(lambda: dict(dag.node_attrs(node))),
+ "in_degree": caught(lambda: dag.in_degree(node)),
+ "successors": caught(
+ lambda: adjacency(dag.successors(node), describe)
+ ),
+ "predecessors": caught(
+ lambda: adjacency(dag.predecessors(node), describe)
+ ),
+ "ancestors": caught(
+ lambda: adjacency(dag.ancestors(node), describe)
+ ),
+ }
+ for name, node in operands.items()
+ },
+ }
+
+ def vertex_view(
+ view: Any, node: Any, other: Any, describe: Callable[[Any], str]
+ ) -> dict[str, Any]:
+ def members(vertices: set[Any]) -> list[str]:
+ return sorted("missing" if v is other else describe(v) for v in vertices)
+
+ return {
+ "length": len(view),
+ "member": node in view,
+ "disjoint": view.isdisjoint([other]),
+ "equal": view == set(view),
+ "subset": view <= set(view),
+ "proper_subset": view < (set(view) | {other}),
+ "superset": view >= {node},
+ "proper_superset": view > {node},
+ "union": members(view | {other}),
+ "intersection": members(view & {node, other}),
+ "difference": members(view - {node}),
+ "reverse_difference": members({node, other} - view),
+ "symmetric_difference": members(view ^ {node, other}),
+ "reversed": caught(lambda: list(reversed(view)) == list(view)[::-1]),
+ }
+
+ @dataclass(frozen=True, order=True)
+ class Vertex:
+ key: int
+ name: str = field(compare=False)
+
+ cases = {}
+ for dag in (OrcaDAG[Vertex](), NetworkxBackend[Vertex]()):
+ backend = type(dag).__name__
+ root = Vertex(1, "registered root")
+ leaf = Vertex(2, "registered leaf")
+ alias_root = Vertex(1, "edge root")
+ alias_leaf = Vertex(2, "edge leaf")
+ missing = Vertex(3, "missing")
+ isolated = Vertex(0, "isolated")
+ describe = operator.attrgetter("name")
+ operands = {
+ "root": root,
+ "leaf": leaf,
+ "root alias": alias_root,
+ "leaf alias": alias_leaf,
+ "missing": missing,
+ "isolated": isolated,
+ }
+ cases[f"{backend} empty"] = topology(dag, describe, {})
+ first_vertex = dag.add_node(root, marker=42)
+ dag.add_node(leaf)
+ view: Any = dag.nodes()
+ attrs: Any = view.mapping if isinstance(dag, OrcaDAG) else view
+ before = (
+ dict(attrs[root]) if isinstance(attrs[root], dict) else repr(attrs[root])
+ )
+ dag.add_node(alias_root, label="merged")
+ dag.node_attrs(root)["marker"] = 43
+ first_edge = dag.add_edge(alias_root, alias_leaf)
+ dag.add_edge(root, leaf)
+ dag.add_node(isolated)
+ after = (
+ dict(attrs[root]) if isinstance(attrs[root], dict) else repr(attrs[root])
+ )
+ cases[backend] = {
+ "topology": topology(dag, describe, operands),
+ "view": vertex_view(view, root, missing, describe),
+ "view_attributes": [before, after],
+ "mutator_returns": [first_vertex, first_edge],
+ }
+ dag.add_edge(leaf, root)
+ cyclic = topology(dag, describe, {})
+ cases[f"{backend} cycle"] = {
+ kind: cyclic[kind] for kind in ("topological", "deterministic")
+ }
+
+ for receiver in (Pipeline, PipelineJob):
+ root = source("slot", 3)
+ with receiver("compiled") as graph:
+ output = double.pod(root, label="step")
+ adjust_output.pod(output, label="output")
+ with receiver("compiled") as other:
+ output = double.pod(root, label="step")
+ adjust_output.pod(output, label="output")
+ own = graph.nodes["slot"], graph.nodes["step"], graph.nodes["output"]
+ alias = other.nodes["step"]
+ dag = graph.dag
+ describe = operator.attrgetter("label")
+ topology_before = topology(dag, describe, {node.label: node for node in own})
+ view = dag.nodes()
+ # Compiled graph policy changes are compared separately from shared behavior.
+ cases[receiver.__name__] = {
+ "topology": topology_before,
+ "view": vertex_view(view, own[0], "unregistered", describe),
+ "labels": list(graph.nodes),
+ "label_objects": [getattr(graph, node.label) is node for node in own],
+ "view_mapping": [
+ view.mapping[node] == dag.node_attrs(node) for node in own
+ ],
+ "policy": {
+ "graph_property": hasattr(graph, "graph"),
+ "foreign_member": caught(lambda: alias in dag),
+ "foreign_view_member": caught(lambda: alias in view),
+ "foreign_degree": caught(lambda: dag.in_degree(alias)),
+ "add_node": caught(lambda: dag.add_node(alias, marker=42)),
+ "add_edge": caught(lambda: dag.add_edge(own[0], own[2])),
+ },
+ }
+
+ def build_job() -> PipelineJob:
+ with PipelineJob("result", database=InMemoryArrowDatabase()) as job:
+ double.pod(root_source, label="output")
+ return job
+
+ root_source = source("slot", 3)
+ job, twin = build_job(), build_job()
+ dag = OrcaDAG[Any]()
+ dag.add_edge(job.nodes["slot"], job.nodes["output"])
+ original, alias = job.nodes["output"], twin.nodes["output"]
+ outputs = AsyncPipelineOrchestrator().run(dag).node_outputs
+ cases["async equal alias"] = {
+ "equal": alias == original,
+ "distinct": alias is not original,
+ "member": alias in outputs,
+ "rows": caught(lambda: outputs[alias].as_table()["out"].to_pylist()),
+ "cached_identity": caught(lambda: outputs[alias] is outputs[original]),
+ "iterates_original": any(node is original for node in outputs),
+ }
+ outputs = AsyncPipelineOrchestrator().run(dag).node_outputs
+ job.bind(sources={"slot": source("replacement", 8)})
+ cases["async result after rebind"] = {
+ "member": original in outputs,
+ "rows": caught(lambda: outputs[original].as_table()["out"].to_pylist()),
+ }
+
+ with Pipeline("blueprint") as blueprint:
+ double.pod(source("slot", 0), label="output")
+ first, second = (
+ PipelineJob.from_pipeline(
+ blueprint,
+ sources={"slot": source(name, value)},
+ database=InMemoryArrowDatabase(),
+ )
+ for name, value in (("first", 3), ("second", 8))
+ )
+ first.run()
+ second.run()
+ inputs = first.nodes["output"], second.nodes["output"]
+ join = MergeJoin()
+ join.validate_inputs(*inputs)
+ combined = OperatorJobNode(join, inputs, label="combined")
+ rows = combined.run().as_table()["out"].to_pylist()
+ trace = combined.trace({"id": 1}, "out")
+ cases["standalone join provenance"] = {
+ "rows": rows,
+ "matched": trace.matched,
+ "cells": [[cell.source_id, cell.value] for cell in trace.source_cells()],
+ "absence": {
+ name: caught(lambda: combined.why_missing(name, "row_0").status)
+ for name in ("first", "second", "dict_v1:first", "dict_v1:second", "slot")
+ },
+ }
+ return cases
+
+
+@pytest.mark.filterwarnings("ignore:MergeJoin is provisional")
+def test_standalone_and_compiled_graph_operations_match_main(
+ baseline: Path | None,
+) -> None:
+ if baseline is None:
+ pytest.skip(f"Reviewed main commit {MAIN} is unavailable")
+ main = probe(baseline, "graph-surface")
+ actual = standalone_graph_surface()
+ for receiver in ("Pipeline", "PipelineJob"):
+ main_policy = main[receiver].pop("policy")
+ policy = actual[receiver].pop("policy")
+ assert main_policy == {
+ "graph_property": True,
+ "foreign_member": True,
+ "foreign_view_member": True,
+ "foreign_degree": 1,
+ "add_node": None,
+ "add_edge": None,
+ }
+ assert policy["graph_property"] is False
+ assert policy["foreign_member"][0] == "UndefinedGraphMembershipError"
+ assert policy["foreign_view_member"] == policy["foreign_member"]
+ assert policy["foreign_degree"][0] == "KeyError"
+ assert (
+ policy["add_node"]
+ == policy["add_edge"]
+ == [
+ "TypeError",
+ "Pipeline DAG topology is read-only. Use the pipeline API.",
+ ]
+ )
+ assert actual == main
+
+
+if __name__ == "__main__":
+ args = sys.argv[1:]
+ if args[0] == "graph-surface":
+ print(json.dumps(standalone_graph_surface()))
+ elif args[0] == "edges":
+ print(json.dumps(public_edge_iteration(args[1])))
+ elif args[0] == "standalone-edges":
+ print(json.dumps(standalone_edge_operands(args[1])))
+ elif args[0] == "standalone-join":
+ print(json.dumps(standalone_join(args[1], args[2], args[3])))
+ elif args[0] == "public":
+ print(json.dumps(public_lifecycle(Path(args[1]), args[2]), default=str))
+ elif args[0] == "operators":
+ print(json.dumps(custom_operator_matrix(Path(args[1]), args[2])))
+ elif args[0] == "capture-mutation":
+ print(
+ json.dumps(capture_mutation_matrix(Path(args[1]), args[2], "clean" in args))
+ )
+ elif args[0] == "ordered":
+ print(json.dumps(ordered_case(args[1], args[2])))
+ elif args[0] == "blueprint":
+ print(json.dumps(blueprint_boundary_case(Path(args[1]), args[2], args[3])))
+ elif args[0] == "cross-store":
+ print(json.dumps(cross_store_case(Path(args[1]), args[2], args[3], args[4])))
+ elif args[0] == "exports":
+ print(
+ json.dumps(
+ {"positional_outputs": hasattr(InvocationGraph((), {}), "outputs")}
+ )
+ )
+ else:
+ print(json.dumps(stored_run(Path(args[0]), args[1]), default=str))
diff --git a/tests/test_pipeline/test_store_write_failure.py b/tests/test_pipeline/test_store_write_failure.py
index 57bc13117..c1c550437 100644
--- a/tests/test_pipeline/test_store_write_failure.py
+++ b/tests/test_pipeline/test_store_write_failure.py
@@ -399,7 +399,10 @@ def test_function_failure_is_still_skipped_under_continue(self, orchestrator_cls
job.run(orchestrator=orchestrator_cls(error_policy="continue"))
- assert sorted(job.nodes["dbl"].as_table()["k"].to_pylist()) == ["r0", "r2"]
+ assert sorted(job.nodes["dbl"].as_table()["k"].to_pylist()) == [
+ "r0",
+ "r2",
+ ]
# ---------------------------------------------------------------------------
@@ -705,7 +708,10 @@ def test_several_store_errors_raise_the_first_in_node_order(
job = build_siblings(FaultyStore(InMemoryArrowDatabase(), faults), triple_async)
first, second = sorted(
("dbl", "other"),
- key=lambda label: (job.nodes[label].pipeline_hash().to_string(), label),
+ key=lambda label: (
+ job.nodes[label].pipeline_hash().to_string(),
+ label,
+ ),
)
with caplog.at_level("WARNING"):
diff --git a/tests/test_pipeline/test_token_types_review_4.py b/tests/test_pipeline/test_token_types_review_4.py
index 7ea4a25ea..0397a06e4 100644
--- a/tests/test_pipeline/test_token_types_review_4.py
+++ b/tests/test_pipeline/test_token_types_review_4.py
@@ -101,10 +101,16 @@ def test_a_replay_over_logical_lists_reuses_its_rows(
with job:
function.pod(make(), label="f")
ran = job.run(orchestrator=ORCHESTRATORS[first]())
- assert (ran.nodes["f"].computed, ran.nodes["f"].failed) == (rows, 0)
+ assert (ran.nodes["f"].computed, ran.nodes["f"].failed) == (
+ rows,
+ 0,
+ )
cast("Any", job.nodes["f"]).clear_cache()
again = job.run(orchestrator=ORCHESTRATORS[second]())
- assert (again.nodes["f"].reused, again.nodes["f"].computed) == (rows, 0)
+ assert (again.nodes["f"].reused, again.nodes["f"].computed) == (
+ rows,
+ 0,
+ )
assert again.nodes["f"].failed == 0