Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.
feature/Dry-condition-shared-output · L-261005-1f395b (#1348)
Louis Choquel4d1cf04d2b49
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2f7593880..65dea64ad 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,14 @@- **`PIPELEX_HOME` relocates the home configuration directory**: when set and not empty, it names the directory Pipelex uses in place of `~/.pipelex`, for the configuration layers, the inference files and their overrides, the credentials `.env`, the first-boot copy of the kit, `pipelex init`, `pipelex doctor`, `pipelex update`, `pipelex migrate` and the agent CLI's `--global`. It must be in the process environment before Pipelex is imported, a relative value is resolved against the working directory at import, and a `PIPELEX_HOME` line in a `.env` file is ignored. The first boot now fills the home directory from the kit when it exists but is empty, as it already did when it was missing, so an empty volume mount or a `mktemp -d` works as it is.+### Changed++- **`GraphAnalysis.stuff_producers` lists every producer (Breaking)**: it maps a digest to a list of node ids, `get_producer` is replaced by `get_producers`, and the new `shared_stuff_controllers` names the controller a stuff with several writers belongs to, a parallel or batch controller combining or aggregating into the stuff counting as one of them. The Mermaid graph draws such a stuff once, inside that controller, with an edge from each producer.++### Fixed++- **A dry-run condition's output is one stuff every outcome produces**: in the graph of a dry run, every outcome of a `PipeCondition` now carries the condition's output digest, so the step reading the condition's result is wired to all of them rather than to the outcome whose pipe code sorts last, and the condition's own item takes its declared output concept when the outcomes write or declare different ones. Each outcome but the last now runs on a copy of the memory the condition received, so an outcome reading the condition's slot reads the value from before the condition rather than a sibling's output, and the default outcome runs last, so the steps after the condition read its value.+## [v0.74.0] - 2026-10-05### Addeddiff --git a/docs/building-methods/pipes/pipe-controllers/PipeCondition.md b/docs/building-methods/pipes/pipe-controllers/PipeCondition.mdindex 8c30e0045..b35a5a000 100644--- a/docs/building-methods/pipes/pipe-controllers/PipeCondition.md+++ b/docs/building-methods/pipes/pipe-controllers/PipeCondition.md@@ -17,6 +17,8 @@ The `PipeCondition` controller adds branching logic to your pipelines. It evaluaWhen the expression renders nothing, no outcome can be chosen and the pipe fails with `Conditional expression returned no result`, naming the pipe. That refusal and the others a condition makes are faults in your method, each reported with its reason and a next step. In a run, an expression that renders nothing, a `fail` outcome and a chosen pipe whose inputs are missing fail the run, which a hosted run answers with HTTP 422. In the dry run of `pipelex validate`, which runs every branch instead of choosing one, an expression that renders nothing over the mock inputs and a condition whose every outcome is `fail` give a `dry_run` item.+A dry run, which is what `pipelex validate` and `pipelex run … --dry-run` do, runs every outcome because it cannot know which one a live run would take. Each outcome runs on a copy of the memory the condition received, so no outcome reads what another one wrote, and the default outcome runs last: the steps after the condition read its output, which is what a live run falls back to when no key matches. The graph of a dry run draws the condition's output as one stuff that every outcome produces and the next step reads.+An expression that does not parse, whether written as `expression` or as `expression_template`, is refused when the bundle loads, before anything runs, and so is one the run could not compile, such as one naming a filter or a test that does not exist outside any conditional. Jinja2 resolves a name inside an `{% if %}` block or an inline `if` only when the expression renders, so a wrong name there fails the run rather than the load. `pipelex validate` reports either as an item on the condition naming the field and the line of it that fails, and a run of the bundle is refused with the same item, which a hosted run answers with HTTP 422. The item quotes none of the expression, which may be a host library's.## Configurationdiff --git a/docs/under-the-hood/execution-graph-tracing.md b/docs/under-the-hood/execution-graph-tracing.mdindex 57c428370..f85bbbb82 100644--- a/docs/under-the-hood/execution-graph-tracing.md+++ b/docs/under-the-hood/execution-graph-tracing.md@@ -330,6 +330,18 @@ This paradigm enables:- Visualization of data lineage across the execution graph- Debugging by tracing which pipe produced unexpected output+### A Dry-Run Condition's Output++A stuff usually has one producer. The exception is the output of a `PipeCondition` in a dry run, which runs every outcome because it cannot know which one a live run would take. Every outcome writes the condition's one slot, so the graph draws that slot as one stuff with a producer per outcome, which is also the shape the static graph builder in mthds-ui draws for the same method.++The condition runs every outcome but the last on a copy of the working memory and run params it received, as `PipeParallel` runs its branches, so no outcome reads what a sibling wrote. The last outcome is the default outcome's pipe when the default is a pipe, the others running before it in sorted order. It runs on the condition's own memory, so the steps after the condition read its stuff, which is the condition's output digest.++Once every outcome has run, the condition registers a `ConditionOutputMerge` (`pipelex/graph/condition_output_merge.py`) through the tracer's `register_condition_output_merge`, which the event log carries as a `ConditionOutputMergeEvent`. It names the condition's node, its output digest and the digests the other outcomes minted for the slot. Only a stuff minted inside the condition is merged: an outcome that hands back a stuff it was given keeps its digest, and nothing is merged when the last outcome resolves its slot absent. Both graph builders apply every merge to the finished graph through `apply_condition_output_merges`, which moves each merged digest onto the condition's, transitively for a condition run as another condition's outcome, across every io item and every edge's stuff digests. The last step of an outcome sequence and the output list of an outcome batch therefore move with their outcome.++Each outcome's io item keeps its own concept and multiplicity, so its node still says what that outcome writes. The condition's own output item types the shared stuff: when the merged outcomes write different concepts or multiplicities, or declare different ones, the merge carries the condition's declared output concept, a list when the declaration or the invocation's `nb_output` or `multiple_output` makes it one, and the rewrite retypes that item with it. The declarations count because an outcome's stuff can stand for several: an outcome that is itself a condition hands back only its last outcome's stuff, while its declaration covers every one of them. A list is recorded as `True`, never as an item count, as on every other io item. A condition run as a `PipeBatch`'s branch is given the branch's stuff code, which every outcome mints under, so there is no digest to merge; when its outcomes still write or declare different outputs, the condition records a merge with no merged digest and the typing alone.++An outcome that is a `PipeParallel` or a `PipeBatch` writes the shared stuff as a controller, combining its branches or aggregating its items into it, so it is no producer of the stuff. `GraphAnalysis` still counts it as one of the stuff's writers, so the stuff belongs to the condition all the same.+### Data Flow Edge GenerationDATA edges are generated at teardown by correlating input/output digests:@@ -366,7 +378,7 @@ is_root = analysis.is_root("node_123")# Data flowstuff_info = analysis.get_stuff_info(digest="abc123")-producer = analysis.get_producer(digest="abc123")+producers = analysis.get_producers(digest="abc123")consumers = analysis.get_consumers(digest="abc123")```@@ -378,8 +390,9 @@ consumers = analysis.get_consumers(digest="abc123")| `controller_node_ids` | Nodes with children || `root_nodes` | Top-level nodes || `stuff_registry` | Digest → StuffInfo |-| `stuff_producers` | Digest → producer node ID |+| `stuff_producers` | Digest → producer node IDs, more than one for a dry-run condition's output || `stuff_consumers` | Digest → consumer node IDs |+| `shared_stuff_controllers` | Digest → the deepest controller containing every writer, for a stuff with several writers: its producers, and the parallel or batch controllers combining or aggregating into it. That controller's output item types the stuff in `stuff_registry` |---@@ -408,6 +421,7 @@ print(mermaidflow.mermaid_code)- Operators rendered as rectangles inside subgraphs- Stuff nodes (data items) rendered as stadium shapes- DATA edges connect producers → stuff → consumers+- A stuff with several writers is rendered once, inside the deepest controller containing them all, never inside a parallel outcome combining into it, with an edge from each producerIn the standalone viewer (`mermaidflow.html`), clicking a stuff node opens its JSON content, and an image or PDF output also offers a preview rendered from the URL that JSON carries.@@ -533,6 +547,7 @@ validate_graphspec(graph_spec)| `pipelex/system/trace_context.py` | Serializable tracing context — sits below `graph/` because it rides in every job's metadata || `pipelex/system/data_inclusion_config.py` | Data-capture flags carried by the trace context, surfaced in the TOML under `interpreter.pipeline_execution.graph.data_inclusion` || `pipelex/graph/graph_analysis.py` | Pre-computed graph analysis |+| `pipelex/graph/condition_output_merge.py` | The merge record of a dry-run condition and the rewrite both graph builders apply || `pipelex/graph/graph_factory.py` | Output generation factory || `pipelex/graph/graph_config.py` | Configuration models || `pipelex/graph/validation.py` | GraphSpec validation |diff --git a/pipelex/graph/condition_output_merge.py b/pipelex/graph/condition_output_merge.pynew file mode 100644index 000000000..eef7c6e2d--- /dev/null+++ b/pipelex/graph/condition_output_merge.py@@ -0,0 +1,115 @@+"""One output stuff for a dry-run condition: the record a condition leaves, and the rewrite applying it.++A dry run of a `PipeCondition` runs every outcome, since it cannot know which one a live run would+take, and each outcome writes its own stuff into the condition's one slot. The step after the+condition reads the last outcome's stuff, which is the condition's own output. To draw the+condition's result as one stuff that every outcome produces, the condition records which digests+its outcomes minted, and the graph builders move them onto its output digest once the graph is+built. One function for both builders (the in-process `GraphTracer` and the event-replay+`GraphSpecAssembler`) so the two cannot drift.+"""++from collections.abc import Sequence++from pydantic import BaseModel, ConfigDict, Field++from pipelex.graph.graphspec import EdgeSpec, GraphSpec, IOSpec, NodeSpec+++class ConditionOutputTyping(BaseModel):+ """The typing of a condition's shared output stuff, when its outcomes do not agree on one.++ Its multiplicity is `True` for a list and never an item count, as every io item records it+ (`stuff_io_multiplicity`), so the shared stuff reads the same on the condition and on the+ steps that read it.+ """++ model_config = ConfigDict(extra="forbid", strict=True)++ concept: str+ multiplicity: bool | None = None+++class ConditionOutputMerge(BaseModel):+ """The outcome digests a dry-run condition merges onto its own output digest.++ Attributes:+ condition_node_id: The condition's graph node.+ shared_digest: The condition's output digest, which is the last outcome's stuff.+ merged_digests: The digests the other outcomes minted for the same slot.+ shared_typing: The typing of the condition's own output item, set when the outcomes write or+ declare different concepts or multiplicities, so that the shared stuff carries the+ declaration that covers every outcome rather than whichever outcome ran last.+ """++ model_config = ConfigDict(extra="forbid", strict=True)++ condition_node_id: str+ shared_digest: str+ merged_digests: list[str] = Field(default_factory=list)+ shared_typing: ConditionOutputTyping | None = None+++def apply_condition_output_merges(*, graph: GraphSpec, merges: Sequence[ConditionOutputMerge]) -> GraphSpec:+ """Move every merged digest onto its condition's output digest, across every io item and edge.++ A merged digest is resolved transitively, so a condition run as another condition's outcome+ lands on the outer condition's digest. Each io item keeps its own concept, multiplicity and+ data, except the condition's own output item when its merge carries a typing. Applied once the+ graph is built, the rewrite does not depend on the order the merges were recorded in.+ """+ if not merges:+ return graph++ renames: dict[str, str] = {}+ for merge in merges:+ for merged_digest in merge.merged_digests:+ if merged_digest != merge.shared_digest:+ renames[merged_digest] = merge.shared_digest+ # A typing names the condition's item by the digest it carried when the merge was recorded.+ typings: dict[tuple[str, str], ConditionOutputTyping] = {+ (merge.condition_node_id, merge.shared_digest): merge.shared_typing for merge in merges if merge.shared_typing is not None+ }++ return graph.model_copy(+ update={+ "nodes": [_rewrite_node(node=node, renames=renames, typings=typings) for node in graph.nodes],+ "edges": [_rewrite_edge(edge=edge, renames=renames) for edge in graph.edges],+ }+ )+++def _resolve_digest(*, digest: str | None, renames: dict[str, str]) -> str | None:+ """Follow the renames from `digest` to the digest it finally lands on."""+ visited: set[str] = set()+ current = digest+ while current is not None and current in renames and current not in visited:+ visited.add(current)+ current = renames[current]+ return current+++def _rewrite_item(*, item: IOSpec, renames: dict[str, str], typing: ConditionOutputTyping | None) -> IOSpec:+ update: dict[str, object] = {"digest": _resolve_digest(digest=item.digest, renames=renames)}+ if typing is not None:+ update["concept"] = typing.concept+ update["multiplicity"] = typing.multiplicity+ return item.model_copy(update=update)+++def _rewrite_node(*, node: NodeSpec, renames: dict[str, str], typings: dict[tuple[str, str], ConditionOutputTyping]) -> NodeSpec:+ inputs = [_rewrite_item(item=item, renames=renames, typing=None) for item in node.node_io.inputs]+ outputs = [+ _rewrite_item(item=item, renames=renames, typing=typings.get((node.node_id, item.digest)) if item.digest is not None else None)+ for item in node.node_io.outputs+ ]+ return node.model_copy(update={"node_io": node.node_io.model_copy(update={"inputs": inputs, "outputs": outputs})})+++def _rewrite_edge(*, edge: EdgeSpec, renames: dict[str, str]) -> EdgeSpec:+ return edge.model_copy(+ update={+ "source_stuff_digest": _resolve_digest(digest=edge.source_stuff_digest, renames=renames),+ "target_stuff_digest": _resolve_digest(digest=edge.target_stuff_digest, renames=renames),+ }+ )diff --git a/pipelex/graph/graph_analysis.py b/pipelex/graph/graph_analysis.pyindex 99cb15efc..d720b085c 100644--- a/pipelex/graph/graph_analysis.py+++ b/pipelex/graph/graph_analysis.py@@ -80,14 +80,25 @@ class GraphAnalysis(BaseModel):default_factory=dict,description="Map of digest to StuffInfo for all stuffs in the graph",)- stuff_producers: dict[str, str] = Field(+ stuff_producers: dict[str, list[str]] = Field(default_factory=dict,- description="Map of digest to producer node_id",+ description=(+ "Map of digest to its producer node_ids, in node order. A stuff has several producers when a dry-run "+ "condition's outcomes all write the condition's one output stuff."+ ),)stuff_consumers: dict[str, list[str]] = Field(default_factory=dict,description="Map of digest to list of consumer node_ids",)+ shared_stuff_controllers: dict[str, str] = Field(+ default_factory=dict,+ description=(+ "Map of digest to the deepest controller containing every writer, for a stuff with several writers: its "+ "producers, and the parallel or batch controllers whose branches combine or whose items aggregate into it. "+ "A renderer places the stuff inside that controller, whose own output item types it."+ ),+ )@classmethoddef from_graphspec(cls, graph: GraphSpec) -> "GraphAnalysis":@@ -128,7 +139,7 @@ class GraphAnalysis(BaseModel):# Build stuff registry and producer/consumer mapsstuff_registry: dict[str, StuffInfo] = {}- stuff_producers: dict[str, str] = {}+ stuff_producers: dict[str, list[str]] = defaultdict(list)stuff_consumers: dict[str, list[str]] = defaultdict(list)for node in graph.nodes:@@ -145,7 +156,8 @@ class GraphAnalysis(BaseModel):multiplicity=output_spec.multiplicity,data=output_spec.data,)- stuff_producers[output_spec.digest] = node.node_id+ if node.node_id not in stuff_producers[output_spec.digest]:+ stuff_producers[output_spec.digest].append(node.node_id)# Collect inputs (this node consumes these stuffs)for input_spec in node.node_io.inputs:@@ -160,9 +172,40 @@ class GraphAnalysis(BaseModel):)stuff_consumers[input_spec.digest].append(node.node_id)- # Convert defaultdict to regular dict for Pydantic+ # Convert defaultdicts to regular dicts for Pydantic+ stuff_producers = dict(stuff_producers)stuff_consumers = dict(stuff_consumers)+ # A stuff with several writers belongs to the deepest controller containing them all: the+ # condition whose outcomes write it. A writer is a producer, or a parallel or batch controller+ # whose combined or aggregated output it is, since such an outcome writes the stuff as a+ # controller. That controller's own output item types the stuff, since only its declaration+ # covers every writer when the outcomes write different concepts.+ stuff_writers: dict[str, list[str]] = {digest: list(producer_node_ids) for digest, producer_node_ids in stuff_producers.items()}+ for edge in graph.edges:+ if (edge.kind.is_parallel_combine or edge.kind.is_batch_aggregate) and edge.target_stuff_digest:+ writer_node_ids = stuff_writers.setdefault(edge.target_stuff_digest, [])+ if edge.target not in writer_node_ids:+ writer_node_ids.append(edge.target)+ parent_by_node: dict[str, str] = {child_id: parent_id for parent_id, child_ids in containment_tree.items() for child_id in child_ids}+ shared_stuff_controllers: dict[str, str] = {}+ for digest, writer_node_ids in stuff_writers.items():+ if len(writer_node_ids) < 2:+ continue+ common_controller_id = cls._deepest_common_controller(node_ids=writer_node_ids, parent_by_node=parent_by_node)+ if common_controller_id is None:+ continue+ shared_stuff_controllers[digest] = common_controller_id+ for output_spec in nodes_by_id[common_controller_id].node_io.outputs:+ if output_spec.digest == digest:+ stuff_registry[digest] = StuffInfo(+ name=output_spec.name,+ concept=output_spec.concept,+ multiplicity=output_spec.multiplicity,+ data=output_spec.data,+ )+ break+return cls(nodes_by_id=nodes_by_id,containment_tree=containment_tree,@@ -172,8 +215,28 @@ class GraphAnalysis(BaseModel):stuff_registry=stuff_registry,stuff_producers=stuff_producers,stuff_consumers=stuff_consumers,+ shared_stuff_controllers=shared_stuff_controllers,)+ @classmethod+ def _deepest_common_controller(cls, *, node_ids: list[str], parent_by_node: dict[str, str]) -> str | None:+ """The deepest controller containing every node of `node_ids`, or None when they share no ancestor."""+ other_ancestor_sets = [set(cls._ancestors_of(node_id=node_id, parent_by_node=parent_by_node)) for node_id in node_ids[1:]]+ for candidate in cls._ancestors_of(node_id=node_ids[0], parent_by_node=parent_by_node):+ if all(candidate in ancestor_set for ancestor_set in other_ancestor_sets):+ return candidate+ return None++ @classmethod+ def _ancestors_of(cls, *, node_id: str, parent_by_node: dict[str, str]) -> list[str]:+ """The controllers containing `node_id`, from its parent up to its root."""+ ancestors: list[str] = []+ current = parent_by_node.get(node_id)+ while current is not None and current not in ancestors:+ ancestors.append(current)+ current = parent_by_node.get(current)+ return ancestors+def get_children(self, node_id: str) -> list[str]:"""Get the child node IDs for a given parent node.@@ -218,16 +281,16 @@ class GraphAnalysis(BaseModel):"""return self.stuff_registry.get(digest)- def get_producer(self, digest: str) -> str | None:- """Get the producer node ID for a stuff.+ def get_producers(self, digest: str) -> list[str]:+ """Get the producer node IDs for a stuff.Args:digest: The stuff digest.Returns:- Producer node ID if found, None otherwise.+ List of producer node IDs in node order, or empty list if no producer is known."""- return self.stuff_producers.get(digest)+ return self.stuff_producers.get(digest, [])def get_consumers(self, digest: str) -> list[str]:"""Get the consumer node IDs for a stuff.diff --git a/pipelex/graph/graph_tracer.py b/pipelex/graph/graph_tracer.pyindex d6f13faff..407598d89 100644--- a/pipelex/graph/graph_tracer.py+++ b/pipelex/graph/graph_tracer.py@@ -5,6 +5,7 @@ from typing import Anyfrom typing_extensions import override+from pipelex.graph.condition_output_merge import ConditionOutputMerge, apply_condition_output_mergesfrom pipelex.graph.graph_tracer_protocol import GraphTracerProtocolfrom pipelex.graph.graphspec import (EdgeKind,@@ -28,6 +29,7 @@ from pipelex.tracing.event_log_protocol import EventLogProtocol # ruff: ignore[from pipelex.tracing.trace_events import (BatchAggregateEvent,BatchItemEvent,+ ConditionOutputMergeEvent,ControllerOutputEvent,EdgeEvent,ExecutionDataEvent,@@ -141,6 +143,9 @@ class GraphTracer(GraphTracerProtocol):# The branch_producer_node_id is snapshotted at registration time, before register_controller_output# overrides _stuff_producer_map to point branch stuff codes to the controller nodeself._parallel_combine_map: dict[str, tuple[str, list[tuple[str, str]]]] = {}+ # Dry-run conditions whose outcome outputs merge onto the condition's output digest,+ # applied to the finished graph by the rewrite the event-replay assembler shares+ self._condition_output_merges: list[ConditionOutputMerge] = []# Whether this run emits graph (node/edge) events and assembles a GraphSpec on teardown.# In costs-only mode this is False: the tracer still mints node ids for the in-memory graph# (so usage-event node_id correlation stays valid) but teardown skips the discarded spec build.@@ -266,6 +271,7 @@ class GraphTracer(GraphTracerProtocol):self._batch_item_map = {}self._batch_aggregate_map = {}self._parallel_combine_map = {}+ self._condition_output_merges = []self._event_log = event_logself._workflow_id = workflow_idself._pipeline_run_id = pipeline_run_id@@ -324,6 +330,7 @@ class GraphTracer(GraphTracerProtocol):pipe_registry=dict(self._pipe_registry),concept_registry=dict(self._concept_registry),)+ graph = apply_condition_output_merges(graph=graph, merges=self._condition_output_merges)self._is_active = False@@ -337,6 +344,7 @@ class GraphTracer(GraphTracerProtocol):self._batch_item_map = {}self._batch_aggregate_map = {}self._parallel_combine_map = {}+ self._condition_output_merges = []if self._event_log is not None:self._event_log.close()self._event_log = None@@ -617,6 +625,34 @@ class GraphTracer(GraphTracerProtocol):))+ @override+ def register_condition_output_merge(+ self,+ *,+ merge: ConditionOutputMerge,+ ) -> None:+ """Register that a dry-run condition's outcomes all produce the condition's output stuff.++ Args:+ merge: The condition node, its output digest and the outcome digests merged onto it.+ """+ if not self._is_active:+ return+ self._condition_output_merges.append(merge)++ # Emit ConditionOutputMergeEvent+ if self._event_log is not None:+ self._emit_event(+ ConditionOutputMergeEvent(+ pipeline_run_id=self._event_pipeline_run_id,+ writer_id=self._event_writer_id(),+ workflow_id=self._workflow_id,+ timestamp=datetime.now(UTC),+ sequence=self._next_event_sequence(),+ merge=merge,+ )+ )+@overridedef on_pipe_start(self,diff --git a/pipelex/graph/graph_tracer_manager.py b/pipelex/graph/graph_tracer_manager.pyindex 2fb79814b..9388f2340 100644--- a/pipelex/graph/graph_tracer_manager.py+++ b/pipelex/graph/graph_tracer_manager.py@@ -4,6 +4,7 @@ from datetime import datetimefrom typing import Anyfrom pipelex import log+from pipelex.graph.condition_output_merge import ConditionOutputMergefrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graph_tracer_protocol import GraphTracerProtocolfrom pipelex.graph.graphspec import GraphSpec, GraphSpecMode, IOSpec, NodeKind@@ -506,3 +507,20 @@ class GraphTracerManager(metaclass=ABCSingletonMeta):branch_stuff_codes=branch_stuff_codes,parallel_controller_node_id=parallel_controller_node_id,)++ def register_condition_output_merge(+ self,+ *,+ lookup_key: str,+ merge: ConditionOutputMerge,+ ) -> None:+ """Register that a dry-run condition's outcomes all produce the condition's output stuff.++ Args:+ lookup_key: The tracer lookup key.+ merge: The condition node, its output digest and the outcome digests merged onto it.+ """+ tracer = self._get_tracer(lookup_key)+ if tracer is None:+ return+ tracer.register_condition_output_merge(merge=merge)diff --git a/pipelex/graph/graph_tracer_protocol.py b/pipelex/graph/graph_tracer_protocol.pyindex 85b7cc3fe..fd9bce8d7 100644--- a/pipelex/graph/graph_tracer_protocol.py+++ b/pipelex/graph/graph_tracer_protocol.py@@ -3,6 +3,7 @@ from typing import Any, Protocolfrom typing_extensions import override+from pipelex.graph.condition_output_merge import ConditionOutputMergefrom pipelex.graph.graphspec import EdgeKind, GraphSpec, GraphSpecMode, IOSpec, NodeKindfrom pipelex.system.data_inclusion_config import DataInclusionConfigfrom pipelex.system.trace_context import TraceContext@@ -260,6 +261,21 @@ class GraphTracerProtocol(Protocol):"""...+ def register_condition_output_merge(+ self,+ *,+ merge: ConditionOutputMerge,+ ) -> None:+ """Register that a dry-run condition's outcomes all produce the condition's output stuff.++ The merge is applied once the graph is built: every merged digest moves onto the shared+ digest, so the condition's result is one stuff with a producer per outcome.++ Args:+ merge: The condition node, its output digest and the outcome digests merged onto it.+ """+ ...+def register_execution_data(self,*,@@ -426,3 +442,11 @@ class GraphTracerNoOp(GraphTracerProtocol):parallel_controller_node_id: str,) -> None:pass++ @override+ def register_condition_output_merge(+ self,+ *,+ merge: ConditionOutputMerge,+ ) -> None:+ passdiff --git a/pipelex/graph/mermaidflow/mermaidflow_factory.py b/pipelex/graph/mermaidflow/mermaidflow_factory.pyindex 41c2dbd88..e02ffe42b 100644--- a/pipelex/graph/mermaidflow/mermaidflow_factory.py+++ b/pipelex/graph/mermaidflow/mermaidflow_factory.py@@ -140,6 +140,15 @@ class MermaidflowFactory:for output_spec in controller_node.node_io.outputs:if output_spec.digest and output_spec.digest in digest_map:digest_map[output_spec.digest] = (output_spec.name, output_spec.concept_label)+ # A stuff with several writers (a dry-run condition's one output stuff, which every outcome+ # writes) is rendered once, inside the deepest controller containing all its writers, and+ # never inside a parallel outcome that combines into it.+ for digest_map in controller_output_stuffs.values():+ for digest in analysis.shared_stuff_controllers:+ digest_map.pop(digest, None)+ for digest, controller_id in analysis.shared_stuff_controllers.items():+ if digest in stuff_registry:+ controller_output_stuffs.setdefault(controller_id, {})[digest] = stuff_registry[digest]# Render pipe nodes and their produced stuff within controller subgraphslines.append("")@@ -152,6 +161,7 @@ class MermaidflowFactory:children_map=analysis.containment_tree,stuff_registry=stuff_registry,stuff_producers=analysis.stuff_producers,+ shared_stuff_digests=set(analysis.shared_stuff_controllers),stuff_consumers=analysis.stuff_consumers,stuff_id_mapping=stuff_id_mapping,subgraph_depths=subgraph_depths,@@ -187,7 +197,7 @@ class MermaidflowFactory:lines.append(" %% Pipe nodes (flat view)")# Only render pipes that participate in data flow- participating_pipes: set[str] = set(analysis.stuff_producers.values())+ participating_pipes: set[str] = {producer_id for producer_ids in analysis.stuff_producers.values() for producer_id in producer_ids}for consumers in analysis.stuff_consumers.values():participating_pipes.update(consumers)@@ -229,11 +239,14 @@ class MermaidflowFactory:lines.append("")lines.append(" %% Data flow edges: producer -> stuff -> consumer")- for digest, producer_node_id in sorted(analysis.stuff_producers.items(), key=operator.itemgetter(0)):- producer_mermaid_id = id_mapping.get(producer_node_id)+ for digest, producer_node_ids in sorted(analysis.stuff_producers.items(), key=operator.itemgetter(0)):prod_stuff_mermaid_id = stuff_id_mapping.get(digest)- if producer_mermaid_id and prod_stuff_mermaid_id:- lines.append(f" {producer_mermaid_id} --> {prod_stuff_mermaid_id}")+ if not prod_stuff_mermaid_id:+ continue+ for producer_node_id in producer_node_ids:+ producer_mermaid_id = id_mapping.get(producer_node_id)+ if producer_mermaid_id:+ lines.append(f" {producer_mermaid_id} --> {prod_stuff_mermaid_id}")# Render edges: stuff -> consumerfor digest, consumer_node_ids in sorted(analysis.stuff_consumers.items(), key=operator.itemgetter(0)):@@ -481,7 +494,8 @@ class MermaidflowFactory:id_mapping: dict[str, str],children_map: dict[str, list[str]],stuff_registry: dict[str, tuple[str, str | None]],- stuff_producers: dict[str, str],+ stuff_producers: dict[str, list[str]],+ shared_stuff_digests: set[str],stuff_consumers: dict[str, list[str]],stuff_id_mapping: dict[str, str],subgraph_depths: dict[str, int],@@ -505,7 +519,8 @@ class MermaidflowFactory:id_mapping: Map of node_id to sanitized Mermaid ID.children_map: Map of parent node_id to list of child node_ids.stuff_registry: Map of digest to (name, concept) for all stuffs.- stuff_producers: Map of digest to producer node_id.+ stuff_producers: Map of digest to its producer node_ids.+ shared_stuff_digests: Digests of the stuffs with several producers that a common controller renders.stuff_consumers: Map of digest to list of consumer node_ids.stuff_id_mapping: Map to store stuff mermaid IDs (mutated).subgraph_depths: Map to track subgraph IDs and their depths (mutated).@@ -555,6 +570,7 @@ class MermaidflowFactory:children_map=children_map,stuff_registry=stuff_registry,stuff_producers=stuff_producers,+ shared_stuff_digests=shared_stuff_digests,stuff_consumers=stuff_consumers,stuff_id_mapping=stuff_id_mapping,subgraph_depths=subgraph_depths,@@ -608,9 +624,10 @@ class MermaidflowFactory:lines.append(stuff_line)rendered_orphan_stuffs.add(digest)- # Also render any stuff nodes produced by this pipe- for digest, producer_node_id in stuff_producers.items():- if producer_node_id == node_id and digest in stuff_registry:+ # Also render any stuff nodes produced by this pipe. A stuff with several producers is+ # rendered once: by their common controller, or by its first producer when they have none.+ for digest, producer_node_ids in stuff_producers.items():+ if producer_node_ids[0] == node_id and digest not in shared_stuff_digests and digest in stuff_registry:name, concept = stuff_registry[digest]stuff_line = cls._render_stuff_node(digest=digest,diff --git a/pipelex/pipe_controllers/condition/pipe_condition.py b/pipelex/pipe_controllers/condition/pipe_condition.pyindex a28d561d9..4e7c5096a 100644--- a/pipelex/pipe_controllers/condition/pipe_condition.py+++ b/pipelex/pipe_controllers/condition/pipe_condition.py@@ -1,5 +1,6 @@from typing import TYPE_CHECKING, Any, Literal+from pydantic import BaseModel, ConfigDictfrom typing_extensions import overridefrom pipelex import log@@ -12,13 +13,16 @@ from pipelex.core.pipes.exceptions import PipeRunError, PipeValidationErrorfrom pipelex.core.pipes.inputs.input_stuff_specs import InputStuffSpecsfrom pipelex.core.pipes.inputs.input_stuff_specs_factory import InputStuffSpecsFactoryfrom pipelex.core.pipes.pipe_output import PipeOutput+from pipelex.core.stuffs.stuff import Stuff+from pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTyping+from pipelex.graph.graph_tracer_manager import GraphTracerManagerfrom pipelex.interpreter_hub import get_optional_pipe, get_pipe_router, get_required_pipefrom pipelex.pipe_controllers.condition.pipe_condition_blueprint import describe_expression_parse_failurefrom pipelex.pipe_controllers.condition.special_outcome import SpecialOutcomefrom pipelex.pipe_controllers.pipe_controller import PipeControllerfrom pipelex.pipe_machinery.template_guard_lint import lint_authored_templatefrom pipelex.pipe_run.pipe_job_factory import PipeJobFactory-from pipelex.pipe_run.pipe_run_params import PipeRunParams+from pipelex.pipe_run.pipe_run_params import PipeRunParams, output_multiplicity_to_applyfrom pipelex.system.job_metadata import JobMetadatafrom pipelex.tools.jinja2.exceptions import Jinja2DetectVariablesErrorfrom pipelex.tools.jinja2.jinja2_required_variables import detect_jinja2_required_variables@@ -32,6 +36,32 @@ if TYPE_CHECKING:ConditionOutcomeMap = dict[str, str | SpecialOutcome]+class DryRunOutcomeSlot(BaseModel):+ """What one outcome of a dry-run condition left in the condition's slot, beside what it declares.++ Attributes:+ declared_concept: The concept code the outcome pipe declares as its output.+ declared_list: Whether the outcome pipe declares a list output.+ stuff: The stuff the outcome wrote into the slot, or None where it resolved the slot absent.+ """++ model_config = ConfigDict(extra="forbid", frozen=True)++ declared_concept: str+ declared_list: bool+ stuff: Stuff | None++ @property+ def declared_typing(self) -> tuple[str, bool]:+ return (self.declared_concept, self.declared_list)++ @property+ def written_typing(self) -> tuple[str, bool] | None:+ if self.stuff is None:+ return None+ return (self.stuff.concept.code, self.stuff.is_list)++class PipeCondition(PipeController):type: Literal["PipeCondition"] = "PipeCondition"expression: str@@ -436,22 +466,40 @@ class PipeCondition(PipeController):))- # Here, it should launch the dry run of all the pipes in the outcomes map.- # pipe_dependencies() is a set, and every branch dry-runs into the SAME- # working memory under the SAME output_name — so the branch iterated last- # is the one whose stuff the caller sees as this condition's output. Left- # unsorted, that is string-hash order, which varies per process: the same- # bundle dry-run twice yields two different graphs. Sort so the last writer- # is a property of the method, not of PYTHONHASHSEED.- for pipe_code in sorted(self.pipe_dependencies()):- pipe = get_required_pipe(pipe_code=pipe_code)- await pipe.run_pipe(+ # A dry run cannot know which outcome a live run takes, so every pipe outcome runs. Each+ # outcome but the last runs on a copy of the memory and run params this condition received,+ # as PipeParallel runs its branches: no outcome sees what a sibling wrote, and the memory+ # this condition leaves is the one a live run choosing the last outcome would leave. The+ # last outcome is the default outcome's pipe, so the steps after the condition read the+ # value a live run falls back to when nothing matches, and the order is a property of the+ # method rather than of set iteration order. The graph then shows the condition's result+ # as one stuff that every outcome produces, which the merge registered below records.+ received_stuff_codes = {stuff.stuff_code for stuff in working_memory.root.values()}+ outcome_slots: list[DryRunOutcomeSlot] = []+ outcome_pipe_codes = self._dry_run_outcome_order()+ for outcome_index, pipe_code in enumerate(outcome_pipe_codes):+ is_last_outcome = outcome_index == len(outcome_pipe_codes) - 1+ outcome_pipe = get_required_pipe(pipe_code=pipe_code)+ outcome_output = await outcome_pipe.run_pipe(job_metadata=job_metadata,- working_memory=working_memory,- pipe_run_params=pipe_run_params,+ working_memory=working_memory if is_last_outcome else working_memory.make_deep_copy(),+ pipe_run_params=pipe_run_params if is_last_outcome else pipe_run_params.make_deep_copy(),output_name=output_name,library_crate=library_crate,)+ outcome_slots.append(+ DryRunOutcomeSlot(+ declared_concept=outcome_pipe.output.concept.code,+ declared_list=bool(outcome_pipe.output.multiplicity),+ stuff=outcome_output.working_memory.get_optional_main_stuff(),+ )+ )+ self._register_dry_run_output_merge(+ job_metadata=job_metadata,+ pipe_run_params=pipe_run_params,+ received_stuff_codes=received_stuff_codes,+ outcome_slots=outcome_slots,+ )execution_data_dict: dict[str, Any] = {"evaluated_expression": "dry_run","selected_outcome": "all_outcomes",@@ -483,6 +531,85 @@ class PipeCondition(PipeController):)return PipeOutput(working_memory=working_memory, pipeline_run_id=job_metadata.run_metadata.pipeline_run_id)+ def _dry_run_outcome_order(self) -> list[str]:+ """The pipe outcomes in the order a dry run runs them: sorted, with the default outcome's pipe last."""+ pipe_codes = sorted(self.pipe_dependencies())+ if self.default_outcome in pipe_codes:+ pipe_codes.remove(self.default_outcome)+ pipe_codes.append(self.default_outcome)+ return pipe_codes++ def _register_dry_run_output_merge(+ self,+ *,+ job_metadata: JobMetadata,+ pipe_run_params: PipeRunParams,+ received_stuff_codes: set[str],+ outcome_slots: list[DryRunOutcomeSlot],+ ) -> None:+ """Record that every outcome's output is this condition's one output stuff, for the graph.++ The shared stuff is the last outcome's, which the steps after the condition already read.+ Only a stuff minted inside the condition is merged: an outcome handing back a stuff it was+ given would otherwise drag that stuff's own producer into the condition's result. When the+ merged outcomes write or declare different concepts or multiplicities, the shared stuff is+ typed by this condition's declared output, the one typing that covers them all. The+ declarations count because an outcome's stuff can stand for several: a nested condition+ hands back only its last outcome's stuff, while its declaration covers all of them. A+ record carrying a typing and no merged digest is still left when the outcomes already+ share the stuff code, as under a batch that gives its branch its own stuff code.++ Args:+ job_metadata: The condition's job metadata, whose trace context names its graph node.+ pipe_run_params: The condition's run params, carrying the invocation's output multiplicity.+ received_stuff_codes: The stuff codes in the memory the condition received.+ outcome_slots: What each outcome left in the slot and what it declares, in run order.+ """+ trace_context = job_metadata.trace_context+ if trace_context is None or not trace_context.emit_graph_events or trace_context.parent_node_id is None:+ return+ tracer_manager = GraphTracerManager.get_instance()+ if tracer_manager is None or not outcome_slots:+ return+ shared_slot = outcome_slots[-1]+ shared_stuff = shared_slot.stuff+ if shared_stuff is None or shared_stuff.stuff_code in received_stuff_codes:+ return+ # The outcomes that wrote a stuff minted inside the condition. Their stuffs can already carry+ # the shared digest: a condition run as a batch's branch is given the branch's stuff code,+ # which every outcome mints under, so only the typing is left to record.+ merging_slots = [slot for slot in outcome_slots[:-1] if slot.stuff is not None and slot.stuff.stuff_code not in received_stuff_codes]+ if not merging_slots:+ return+ merging_slots.append(shared_slot)+ merged_digests = sorted(+ {slot.stuff.stuff_code for slot in merging_slots if slot.stuff is not None and slot.stuff.stuff_code != shared_stuff.stuff_code}+ )++ shared_typing: ConditionOutputTyping | None = None+ if len({slot.written_typing for slot in merging_slots}) > 1 or len({slot.declared_typing for slot in merging_slots}) > 1:+ multiplicity_resolution = output_multiplicity_to_apply(+ base_multiplicity=self.output.multiplicity,+ override_multiplicity=pipe_run_params.output_multiplicity,+ )+ shared_typing = ConditionOutputTyping(+ concept=self.output.concept.code,+ multiplicity=True if multiplicity_resolution.is_multiple_outputs_enabled else None,+ )++ if not merged_digests and shared_typing is None:+ return++ tracer_manager.register_condition_output_merge(+ lookup_key=trace_context.lookup_key,+ merge=ConditionOutputMerge(+ condition_node_id=trace_context.parent_node_id,+ shared_digest=shared_stuff.stuff_code,+ merged_digests=merged_digests,+ shared_typing=shared_typing,+ ),+ )+def _record_declared_absent_output(self, *, working_memory: WorkingMemory, output_name: str | None, reason: str) -> None:"""Resolve this pipe's declared output as a declared-absent record (the `continue` arm)."""record = AbsenceRecord(diff --git a/pipelex/tracing/graphspec_assembler.py b/pipelex/tracing/graphspec_assembler.pyindex 7feab95ba..5f823fe77 100644--- a/pipelex/tracing/graphspec_assembler.py+++ b/pipelex/tracing/graphspec_assembler.py@@ -11,6 +11,7 @@ from datetime import UTC, datetimefrom typing import Anyfrom pipelex import log+from pipelex.graph.condition_output_merge import ConditionOutputMerge, apply_condition_output_mergesfrom pipelex.graph.graphspec import (EdgeKind,EdgeSpec,@@ -33,6 +34,7 @@ from pipelex.tracing.trace_events import (UNATTRIBUTED_NODE_ID,BatchAggregateEvent,BatchItemEvent,+ ConditionOutputMergeEvent,ControllerOutputEvent,EdgeEvent,ExecutionDataEvent,@@ -173,6 +175,7 @@ class _AssemblerState:self._batch_item_map: dict[str, tuple[str | None, list[tuple[str, int]]]] = {}self._batch_aggregate_map: dict[str, tuple[str | None, list[tuple[str, int]]]] = {}self._parallel_combine_map: dict[str, tuple[str, list[tuple[str, str]]]] = {}+ self._condition_output_merges: list[ConditionOutputMerge] = []# Registries (accumulated from events, deduplicated)self._pipe_registry: dict[str, dict[str, Any]] = {}@@ -212,6 +215,8 @@ class _AssemblerState:self._handle_batch_aggregate(event)elif isinstance(event, ParallelCombineEvent):self._handle_parallel_combine(event)+ elif isinstance(event, ConditionOutputMergeEvent):+ self._handle_condition_output_merge(event)elif isinstance(event, ExecutionDataEvent):self._handle_execution_data(event)elif isinstance(event, UsageReportEvent):@@ -235,7 +240,7 @@ class _AssemblerState:nodes = [node_data.to_node_spec() for node_data in self._nodes.values()]all_edges = self._explicit_edges + self._get_generated_edges()- return GraphSpec(+ graph = GraphSpec(graph_id=self._graph_id,created_at=self._earliest_timestamp or datetime.now(UTC),pipeline_ref=self._pipeline_ref,@@ -246,6 +251,8 @@ class _AssemblerState:pipe_registry=dict(self._pipe_registry),concept_registry=dict(self._concept_registry),)+ # Mirrors GraphTracer.teardown(): the merges apply to the finished graph, through the same rewrite.+ return apply_condition_output_merges(graph=graph, merges=self._condition_output_merges)# ------------------------------------------------------------------# Pass 1 handlers@@ -404,6 +411,9 @@ class _AssemblerState:list(event.branch_producer_node_ids),)+ def _handle_condition_output_merge(self, event: ConditionOutputMergeEvent) -> None:+ self._condition_output_merges.append(event.merge)+def _mark_canceled_nodes(self) -> None:"""Mark any still-RUNNING nodes as CANCELED (mirrors graph_tracer.py:160-164)."""for node_data in self._nodes.values():diff --git a/pipelex/tracing/trace_events.py b/pipelex/tracing/trace_events.pyindex 2ae77943d..b0592c632 100644--- a/pipelex/tracing/trace_events.py+++ b/pipelex/tracing/trace_events.py@@ -11,6 +11,7 @@ from typing import Annotated, Any, Literalfrom pydantic import BaseModel, Field+from pipelex.graph.condition_output_merge import ConditionOutputMergefrom pipelex.graph.graphspec import EdgeKind, ErrorSpec, IOSpec, NodeKindfrom pipelex.reporting.reporting_types import AnyTokensUsagefrom pipelex.tools.typing.pydantic_utils import empty_list_factory_of@@ -28,6 +29,7 @@ class TraceEventKind(StrEnum):BATCH_ITEM = "batch_item"BATCH_AGGREGATE = "batch_aggregate"PARALLEL_COMBINE = "parallel_combine"+ CONDITION_OUTPUT_MERGE = "condition_output_merge"EXECUTION_DATA = "execution_data"USAGE_REPORT = "usage_report"@@ -171,6 +173,16 @@ class ParallelCombineEvent(TraceEvent):branch_producer_node_ids: list[tuple[str, str]]+class ConditionOutputMergeEvent(TraceEvent):+ """Emitted when a dry-run condition merges its outcomes' outputs onto its own output digest.++ Applied by the assembler once the graph is built, through the same rewrite as GraphTracer's.+ """++ event_kind: Literal[TraceEventKind.CONDITION_OUTPUT_MERGE] = TraceEventKind.CONDITION_OUTPUT_MERGE+ merge: ConditionOutputMerge++class ExecutionDataEvent(TraceEvent):"""Emitted when a pipe registers execution metadata (rendered prompts, resolved models, etc.)."""@@ -207,6 +219,7 @@ AnyTraceEvent = Annotated[| BatchItemEvent| BatchAggregateEvent| ParallelCombineEvent+ | ConditionOutputMergeEvent| ExecutionDataEvent| UsageReportEvent,Field(discriminator="event_kind"),diff --git a/subject_grants.toml b/subject_grants.tomlindex 708f660b3..891d452ec 100644--- a/subject_grants.toml+++ b/subject_grants.toml@@ -3152,7 +3152,7 @@ rationale = "Query accessor keyed by the node it inspects; single operand."param = "digest"rationale = "Query accessor keyed by the stuff digest it inspects; single operand."-["pipelex/graph/graph_analysis.py::GraphAnalysis.get_producer"]+["pipelex/graph/graph_analysis.py::GraphAnalysis.get_producers"]param = "digest"rationale = "Query accessor keyed by the stuff digest it inspects; single operand."@@ -6996,6 +6996,10 @@ rationale = "Dispatch handler: handles the event; single operand."param = "event"rationale = "Dispatch handler: handles the event; single operand."+["pipelex/tracing/graphspec_assembler.py::_AssemblerState._handle_condition_output_merge"]+param = "event"+rationale = "An event handler of the assembler's pass one, called with the one event it folds in, like its sibling handlers."+["pipelex/tracing/graphspec_assembler.py::_AssemblerState._handle_controller_output"]param = "event"rationale = "Dispatch handler: handles the event; single operand."diff --git a/tests/integration/pipelex/pipeline/dry_run_condition/graph_reading.py b/tests/integration/pipelex/pipeline/dry_run_condition/graph_reading.pynew file mode 100644index 000000000..1401cb408--- /dev/null+++ b/tests/integration/pipelex/pipeline/dry_run_condition/graph_reading.py@@ -0,0 +1,34 @@+"""Read a dry run's GraphSpec by pipe code, for the tests of a dry-run condition's shared output."""++from pipelex.graph.graphspec import GraphSpec, IOSpec, NodeSpec+++def node_by_code(graph_spec: GraphSpec, pipe_code: str) -> NodeSpec:+ matches = nodes_by_code(graph_spec, pipe_code)+ assert len(matches) == 1, f"expected one node for '{pipe_code}', found {len(matches)}"+ return matches[0]+++def nodes_by_code(graph_spec: GraphSpec, pipe_code: str) -> list[NodeSpec]:+ return [node for node in graph_spec.nodes if node.pipe_code == pipe_code]+++def only_output(node: NodeSpec) -> IOSpec:+ assert len(node.node_io.outputs) == 1, f"expected one output on '{node.pipe_code}', found {node.node_io.outputs}"+ return node.node_io.outputs[0]+++def input_named(node: NodeSpec, name: str) -> IOSpec:+ matches = [input_spec for input_spec in node.node_io.inputs if input_spec.name == name]+ assert len(matches) == 1, f"expected one input '{name}' on '{node.pipe_code}', found {node.node_io.inputs}"+ return matches[0]+++def read_digests(graph_spec: GraphSpec) -> set[str]:+ return {input_spec.digest for node in graph_spec.nodes for input_spec in node.node_io.inputs if input_spec.digest is not None}+++def output_named(node: NodeSpec, name: str) -> IOSpec:+ matches = [output_spec for output_spec in node.node_io.outputs if output_spec.name == name]+ assert len(matches) == 1, f"expected one output '{name}' on '{node.pipe_code}', found {node.node_io.outputs}"+ return matches[0]diff --git a/tests/integration/pipelex/pipeline/dry_run_condition/test_data.py b/tests/integration/pipelex/pipeline/dry_run_condition/test_data.pynew file mode 100644index 000000000..6c3e681e8--- /dev/null+++ b/tests/integration/pipelex/pipeline/dry_run_condition/test_data.py@@ -0,0 +1,522 @@+from typing import ClassVar+++class DryRunConditionTestData:+ """Bundles whose dry runs run a condition's every outcome, one per shape an outcome can take."""++ REPORT_SHAPE_MTHDS: ClassVar[str] = """+domain = "dry_condition_report_shape"+description = "Judge a CV, route the follow-up, assemble both"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.route]+type = "PipeCondition"+description = "Route the follow-up on the verdict"+inputs = { verdict = "Text", cv = "Text" }+output = "Text"+expression = "verdict"+outcomes = { fit = "write_questions", no_fit = "write_rejection" }+default_outcome = "write_rejection"++[pipe.write_questions]+type = "PipeLLM"+description = "Write interview questions"+inputs = { cv = "Text" }+output = "Text"+prompt = "Questions for $cv"++[pipe.write_rejection]+type = "PipeLLM"+description = "Write a rejection"+inputs = { cv = "Text" }+output = "Text"+prompt = "Rejection for $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Text" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # The condition writes `draft`, a slot that already holds `first_draft`'s value, and `b_polish`+ # reads that slot. Run last and unisolated, `b_polish` would read the draft `a_rewrite` just wrote.+ SLOT_CROSS_READ_MTHDS: ClassVar[str] = """+domain = "dry_condition_slot_cross_read"+description = "A condition whose outcome reads the slot the condition writes"+main_pipe = "flow"++[pipe.flow]+type = "PipeSequence"+description = "Draft, judge, then rewrite or polish the draft"+inputs = { text = "Text" }+output = "Text"+steps = [+ { pipe = "first_draft", result = "draft" },+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "draft" },+]++[pipe.first_draft]+type = "PipeLLM"+description = "Write a first draft"+inputs = { text = "Text" }+output = "Text"+prompt = "Draft $text"++[pipe.judge]+type = "PipeLLM"+description = "Judge the draft"+inputs = { draft = "Text" }+output = "Text"+prompt = "Judge $draft"++[pipe.route]+type = "PipeCondition"+description = "Rewrite from scratch or polish the draft"+inputs = { verdict = "Text", text = "Text", draft = "Text" }+output = "Text"+expression = "verdict"+outcomes = { rewrite = "a_rewrite", polish = "b_polish" }+default_outcome = "b_polish"++[pipe.a_rewrite]+type = "PipeLLM"+description = "Rewrite from the original text"+inputs = { text = "Text" }+output = "Text"+prompt = "Rewrite $text"++[pipe.b_polish]+type = "PipeLLM"+description = "Polish the draft"+inputs = { draft = "Text" }+output = "Text"+prompt = "Polish $draft"+"""++ # The outcomes write different concepts and multiplicities, so only the condition's declaration+ # covers both: the shared stuff is typed `Anything`, single.+ DIFFERING_OUTCOMES_MTHDS: ClassVar[str] = """+domain = "dry_condition_differing_outcomes"+description = "A condition whose outcomes write different concepts"+main_pipe = "screen"++[concept.Question]+description = "An interview question"+refines = "Text"++[concept.Rejection]+description = "A rejection letter"+refines = "Text"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.route]+type = "PipeCondition"+description = "Route the follow-up on the verdict"+inputs = { verdict = "Text", cv = "Text" }+output = "Anything"+expression = "verdict"+outcomes = { fit = "write_questions", no_fit = "write_rejection" }+default_outcome = "write_rejection"++[pipe.write_questions]+type = "PipeLLM"+description = "Write interview questions"+inputs = { cv = "Text" }+output = "Question[]"+prompt = "Questions for $cv"++[pipe.write_rejection]+type = "PipeLLM"+description = "Write a rejection"+inputs = { cv = "Text" }+output = "Rejection"+prompt = "Rejection for $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Anything" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # An outcome that is a sequence: its last step's output is the sequence's output, so it moves too.+ SEQUENCE_OUTCOME_MTHDS: ClassVar[str] = """+domain = "dry_condition_sequence_outcome"+description = "A condition whose non-default outcome is a sequence"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.route]+type = "PipeCondition"+description = "Route the follow-up on the verdict"+inputs = { verdict = "Text", cv = "Text" }+output = "Text"+expression = "verdict"+outcomes = { fit = "questions_flow", no_fit = "write_rejection" }+default_outcome = "write_rejection"++[pipe.questions_flow]+type = "PipeSequence"+description = "Draft then finalize the questions"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "draft_questions", result = "question_draft" },+ { pipe = "finalize_questions", result = "questions" },+]++[pipe.draft_questions]+type = "PipeLLM"+description = "Draft the questions"+inputs = { cv = "Text" }+output = "Text"+prompt = "Draft questions for $cv"++[pipe.finalize_questions]+type = "PipeLLM"+description = "Finalize the questions"+inputs = { question_draft = "Text" }+output = "Text"+prompt = "Finalize $question_draft"++[pipe.write_rejection]+type = "PipeLLM"+description = "Write a rejection"+inputs = { cv = "Text" }+output = "Text"+prompt = "Rejection for $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Text" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # An outcome that is a batch: the aggregate edge into its output list names that list's digest,+ # which moves onto the condition's.+ BATCH_OUTCOME_MTHDS: ClassVar[str] = """+domain = "dry_condition_batch_outcome"+description = "A condition whose non-default outcome is a batch"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV over topics"+inputs = { cv = "Text", topics = "Text[]" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.route]+type = "PipeCondition"+description = "Route the follow-up on the verdict"+inputs = { verdict = "Text", cv = "Text", topics = "Text[]" }+output = "Text[]"+expression = "verdict"+outcomes = { fit = "ask_each_topic", no_fit = "write_rejections" }+default_outcome = "write_rejections"++[pipe.ask_each_topic]+type = "PipeBatch"+description = "Ask one question per topic"+inputs = { topics = "Text[]" }+output = "Text[]"+branch_pipe_code = "ask_topic"+input_list_name = "topics"+input_item_name = "topic"++[pipe.ask_topic]+type = "PipeLLM"+description = "Ask a question on one topic"+inputs = { topic = "Text" }+output = "Text"+prompt = "Ask about $topic"++[pipe.write_rejections]+type = "PipeLLM"+description = "Write rejection paragraphs"+inputs = { cv = "Text" }+output = "Text[]"+prompt = "Rejection paragraphs for $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Text[]" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # An outcome that is itself a condition hands back only its last outcome's stuff, `summarize_cv`'s+ # Text, as does the outer default. Both conditions declare `Anything`, which only the+ # declarations reveal: the outer condition's shared stuff, written by a Number and two Texts,+ # must be typed `Anything`.+ NESTED_CONDITIONS_MTHDS: ClassVar[str] = """+domain = "dry_condition_nested_conditions"+description = "A condition whose non-default outcome is a condition"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "outer", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.outer]+type = "PipeCondition"+description = "Score the CV or write a note"+inputs = { verdict = "Text", cv = "Text" }+output = "Anything"+expression = "verdict"+outcomes = { scored = "inner" }+default_outcome = "write_note"++[pipe.inner]+type = "PipeCondition"+description = "Score the CV or summarize it"+inputs = { verdict = "Text", cv = "Text" }+output = "Anything"+expression = "verdict"+outcomes = { numeric = "score_cv" }+default_outcome = "summarize_cv"++[pipe.score_cv]+type = "PipeLLM"+description = "Score the CV"+inputs = { cv = "Text" }+output = "Number"+prompt = "Score $cv"++[pipe.summarize_cv]+type = "PipeLLM"+description = "Summarize the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Summarize $cv"++[pipe.write_note]+type = "PipeLLM"+description = "Write a note"+inputs = { cv = "Text" }+output = "Text"+prompt = "Note on $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Anything" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # An outcome that is a parallel: it writes the shared stuff as a controller, combining its+ # branches into it, so it is no producer of it, and the stuff still has two writers.+ PARALLEL_OUTCOME_MTHDS: ClassVar[str] = """+domain = "dry_condition_parallel_outcome"+description = "A condition whose non-default outcome is a parallel"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen a CV"+inputs = { cv = "Text" }+output = "Text"+steps = [+ { pipe = "judge", result = "verdict" },+ { pipe = "route", result = "follow_up" },+ { pipe = "assemble", result = "result" },+]++[pipe.judge]+type = "PipeLLM"+description = "Judge the CV"+inputs = { cv = "Text" }+output = "Text"+prompt = "Judge $cv"++[pipe.route]+type = "PipeCondition"+description = "Route the follow-up on the verdict"+inputs = { verdict = "Text", cv = "Text" }+output = "Anything"+expression = "verdict"+outcomes = { fit = "write_both" }+default_outcome = "write_rejection"++[pipe.write_both]+type = "PipeParallel"+description = "Write questions and notes at once"+inputs = { cv = "Text" }+output = "Composite"+add_each_output = true+branches = [+ { pipe = "write_questions", result = "questions" },+ { pipe = "write_notes", result = "notes" },+]++[pipe.write_questions]+type = "PipeLLM"+description = "Write interview questions"+inputs = { cv = "Text" }+output = "Text"+prompt = "Questions for $cv"++[pipe.write_notes]+type = "PipeLLM"+description = "Write interview notes"+inputs = { cv = "Text" }+output = "Text"+prompt = "Notes for $cv"++[pipe.write_rejection]+type = "PipeLLM"+description = "Write a rejection"+inputs = { cv = "Text" }+output = "Text"+prompt = "Rejection for $cv"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the verdict and the follow-up"+inputs = { verdict = "Text", follow_up = "Anything" }+output = "Text"+prompt = "Assemble $verdict and $follow_up"+"""++ # A condition run as a batch's branch: the batch gives the branch its stuff code, so both+ # outcomes mint the same digest and nothing is merged, but they write a Number and a Text, so+ # the condition's `Anything` must still type the stuff.+ BATCH_BRANCH_CONDITION_MTHDS: ClassVar[str] = """+domain = "dry_condition_batch_branch"+description = "A batch whose branch is a condition with differing outcomes"+main_pipe = "screen"++[pipe.screen]+type = "PipeSequence"+description = "Screen topics"+inputs = { topics = "Text[]" }+output = "Text"+steps = [+ { pipe = "route_each", result = "follow_ups" },+ { pipe = "assemble", result = "result" },+]++[pipe.route_each]+type = "PipeBatch"+description = "Route each topic"+inputs = { topics = "Text[]" }+output = "Anything[]"+branch_pipe_code = "route"+input_list_name = "topics"+input_item_name = "topic"++[pipe.route]+type = "PipeCondition"+description = "Score or summarize one topic"+inputs = { topic = "Text" }+output = "Anything"+expression = "topic"+outcomes = { numeric = "score_topic" }+default_outcome = "summarize_topic"++[pipe.score_topic]+type = "PipeLLM"+description = "Score the topic"+inputs = { topic = "Text" }+output = "Number"+prompt = "Score $topic"++[pipe.summarize_topic]+type = "PipeLLM"+description = "Summarize the topic"+inputs = { topic = "Text" }+output = "Text"+prompt = "Summarize $topic"++[pipe.assemble]+type = "PipeLLM"+description = "Assemble the follow-ups"+inputs = { follow_ups = "Anything[]" }+output = "Text"+prompt = "Assemble $follow_ups"+"""diff --git a/tests/integration/pipelex/pipeline/dry_run_condition/test_merge_record.py b/tests/integration/pipelex/pipeline/dry_run_condition/test_merge_record.pynew file mode 100644index 000000000..026957856--- /dev/null+++ b/tests/integration/pipelex/pipeline/dry_run_condition/test_merge_record.py@@ -0,0 +1,170 @@+"""The merge record a dry-run condition leaves, read off what its outcomes left in the slot and what they declare."""++from collections.abc import Callable++import pytest+from pytest_mock import MockerFixture, MockType++from pipelex.core.concepts.concept_factory import ConceptFactory+from pipelex.core.concepts.native.concept_native import NativeConceptCode+from pipelex.core.stuffs.list_content import ListContent+from pipelex.core.stuffs.stuff import Stuff+from pipelex.core.stuffs.stuff_factory import StuffFactory+from pipelex.core.stuffs.text_content import TextContent+from pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTyping+from pipelex.graph.graph_tracer_manager import GraphTracerManager+from pipelex.interpreter_hub import get_library_manager, get_required_pipe+from pipelex.mthds_parsing.parser import MthdsParser+from pipelex.pipe_controllers.condition.pipe_condition import DryRunOutcomeSlot, PipeCondition+from pipelex.pipe_run.pipe_run_params_factory import PipeRunParamsFactory+from pipelex.system.job_metadata import JobMetadata, RunMetadata+from tests.integration.pipelex.pipeline.dry_run_condition.test_data import DryRunConditionTestData+from tests.unit.pipelex.graph.conftest import make_trace_context++_CONDITION_NODE_ID = "graph:node_route"+++def _text_stuff(*, text: str) -> Stuff:+ return StuffFactory.make_stuff(+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),+ content=TextContent(text=text),+ name="follow_up",+ )+++def _text_list_stuff(*, texts: list[str]) -> Stuff:+ return StuffFactory.make_stuff(+ concept=ConceptFactory.make_native_concept(native_concept_code=NativeConceptCode.TEXT),+ content=ListContent[TextContent](items=[TextContent(text=text) for text in texts]),+ name="follow_up",+ )+++def _slot(stuff: Stuff | None, *, declared_concept: str = "Text", declared_list: bool = False) -> DryRunOutcomeSlot:+ return DryRunOutcomeSlot(declared_concept=declared_concept, declared_list=declared_list, stuff=stuff)+++class TestDryRunConditionMergeRecord:+ @pytest.fixture+ def route(self, load_empty_library: Callable[[], str]) -> PipeCondition:+ library_id = load_empty_library()+ blueprint = MthdsParser.make_pipelex_bundle_blueprint(mthds_content=DryRunConditionTestData.REPORT_SHAPE_MTHDS)+ get_library_manager().load_from_blueprints(library_id=library_id, blueprints=[blueprint])+ condition = get_required_pipe(pipe_code="dry_condition_report_shape.route")+ assert isinstance(condition, PipeCondition)+ return condition++ @pytest.fixture+ def tracer_manager(self, mocker: MockerFixture) -> MockType:+ manager: MockType = mocker.MagicMock(spec=GraphTracerManager)+ mocker.patch.object(GraphTracerManager, "get_instance", return_value=manager)+ return manager++ def _register(+ self,+ *,+ route: PipeCondition,+ received: list[Stuff],+ outcome_slots: list[DryRunOutcomeSlot],+ output_multiplicity: int | None = None,+ ) -> None:+ route._register_dry_run_output_merge( # ruff: ignore[private-member-access] # pyright: ignore[reportPrivateUsage]+ job_metadata=JobMetadata(+ run_metadata=RunMetadata(storage_scope="test/scope", read_scope=None, user_id="user_test", pipeline_run_id="run_merge_record"),+ pipe_code="route",+ trace_context=make_trace_context(graph_id="graph", parent_node_id=_CONDITION_NODE_ID),+ ),+ pipe_run_params=PipeRunParamsFactory.make_run_params(output_multiplicity=output_multiplicity),+ received_stuff_codes={stuff.stuff_code for stuff in received},+ outcome_slots=outcome_slots,+ )++ def _recorded_merges(self, tracer_manager: MockType) -> list[ConditionOutputMerge]:+ return [call.kwargs["merge"] for call in tracer_manager.register_condition_output_merge.call_args_list]++ def test_outcomes_that_agree_merge_without_a_typing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ questions, rejection = _text_stuff(text="questions"), _text_stuff(text="rejection")++ self._register(route=route, received=[], outcome_slots=[_slot(questions), _slot(rejection)])++ assert self._recorded_merges(tracer_manager) == [+ ConditionOutputMerge(condition_node_id=_CONDITION_NODE_ID, shared_digest=rejection.stuff_code, merged_digests=[questions.stuff_code])+ ]++ def test_outcomes_that_write_differently_carry_the_declared_typing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ questions, rejection = _text_list_stuff(texts=["one", "two"]), _text_stuff(text="rejection")++ self._register(route=route, received=[], outcome_slots=[_slot(questions, declared_list=True), _slot(rejection)])++ [merge] = self._recorded_merges(tracer_manager)+ assert merge.shared_typing == ConditionOutputTyping(concept="Text", multiplicity=None)++ def test_outcomes_that_declare_differently_carry_the_declared_typing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ """A nested condition hands back one outcome's stuff, which can agree with its sibling's while its declaration does not."""+ nested, fallback = _text_stuff(text="nested"), _text_stuff(text="fallback")++ self._register(route=route, received=[], outcome_slots=[_slot(nested, declared_concept="Anything"), _slot(fallback)])++ [merge] = self._recorded_merges(tracer_manager)+ assert merge.shared_typing == ConditionOutputTyping(concept="Text", multiplicity=None)++ def test_an_output_count_types_the_stuff_as_a_list_not_a_count(self, route: PipeCondition, tracer_manager: MockType) -> None:+ """Every io item records a list as `True`, so the shared stuff reads the same on the condition and its readers."""+ questions, rejection = _text_list_stuff(texts=["one", "two"]), _text_stuff(text="rejection")++ self._register(route=route, received=[], outcome_slots=[_slot(questions, declared_list=True), _slot(rejection)], output_multiplicity=3)++ [merge] = self._recorded_merges(tracer_manager)+ assert merge.shared_typing == ConditionOutputTyping(concept="Text", multiplicity=True)++ def test_outcomes_sharing_one_stuff_code_still_carry_the_declared_typing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ """Run as a batch's branch, every outcome mints under the branch's stuff code: nothing to merge, a typing to record."""+ branch_stuff = _text_stuff(text="branch")++ self._register(route=route, received=[], outcome_slots=[_slot(branch_stuff, declared_concept="Number"), _slot(branch_stuff)])++ assert self._recorded_merges(tracer_manager) == [+ ConditionOutputMerge(+ condition_node_id=_CONDITION_NODE_ID,+ shared_digest=branch_stuff.stuff_code,+ merged_digests=[],+ shared_typing=ConditionOutputTyping(concept="Text", multiplicity=None),+ )+ ]++ def test_outcomes_sharing_one_stuff_code_and_agreeing_record_nothing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ branch_stuff = _text_stuff(text="branch")++ self._register(route=route, received=[], outcome_slots=[_slot(branch_stuff), _slot(branch_stuff)])++ assert self._recorded_merges(tracer_manager) == []++ def test_a_received_stuff_is_never_merged(self, route: PipeCondition, tracer_manager: MockType) -> None:+ """An outcome handing back a stuff it was given would drag that stuff's producer into the result."""+ cv, rejection = _text_stuff(text="cv"), _text_stuff(text="rejection")++ self._register(route=route, received=[cv], outcome_slots=[_slot(cv), _slot(rejection)])++ assert self._recorded_merges(tracer_manager) == []++ def test_a_received_shared_stuff_merges_nothing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ cv, questions = _text_stuff(text="cv"), _text_stuff(text="questions")++ self._register(route=route, received=[cv], outcome_slots=[_slot(questions), _slot(cv)])++ assert self._recorded_merges(tracer_manager) == []++ def test_an_absent_last_outcome_merges_nothing(self, route: PipeCondition, tracer_manager: MockType) -> None:+ self._register(route=route, received=[], outcome_slots=[_slot(_text_stuff(text="questions")), _slot(None)])++ assert self._recorded_merges(tracer_manager) == []++ def test_an_absent_outcome_is_left_out(self, route: PipeCondition, tracer_manager: MockType) -> None:+ """An absent outcome neither merges nor counts towards the typing, even when it declares another concept."""+ questions, rejection = _text_stuff(text="questions"), _text_stuff(text="rejection")++ self._register(route=route, received=[], outcome_slots=[_slot(None, declared_concept="Number"), _slot(questions), _slot(rejection)])++ [merge] = self._recorded_merges(tracer_manager)+ assert merge.merged_digests == [questions.stuff_code]+ assert merge.shared_typing is Nonediff --git a/tests/integration/pipelex/pipeline/dry_run_condition/test_outcome_isolation.py b/tests/integration/pipelex/pipeline/dry_run_condition/test_outcome_isolation.pynew file mode 100644index 000000000..1be5a04b5--- /dev/null+++ b/tests/integration/pipelex/pipeline/dry_run_condition/test_outcome_isolation.py@@ -0,0 +1,52 @@+"""A dry-run condition runs every outcome but the last on a copy of the memory it received.++A dry run cannot know which outcome a live run would take, so ``PipeCondition`` dry-runs every+outcome, and the default outcome runs last. No outcome reads what a sibling wrote, and the steps+after the condition read the value a live run falls back to when nothing matches.+"""++from collections.abc import Sequence++import pytest+from pytest_mock import MockerFixture++from pipelex.core.memory import working_memory as working_memory_module+from pipelex.pipeline.dry_run_pipeline import dry_run_pipeline+from tests.integration.pipelex.pipeline.dry_run_condition.graph_reading import input_named, node_by_code, only_output+from tests.integration.pipelex.pipeline.dry_run_condition.test_data import DryRunConditionTestData+++def _replaced_key_warnings(warning_calls: Sequence[object], *, key: str) -> list[str]:+ needle = f"Key '{key}' already exists in WorkingMemory and will be replaced"+ return [str(call) for call in warning_calls if needle in str(call)]++[email protected](loop_scope="class")+class TestDryRunConditionOutcomeIsolation:+ async def test_an_outcome_reads_the_slot_as_the_condition_received_it(self) -> None:+ """`b_polish` runs after `a_rewrite` and reads `draft`: it must read `first_draft`'s value."""+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.SLOT_CROSS_READ_MTHDS])++ first_draft_digest = only_output(node_by_code(graph_spec, "first_draft")).digest+ polish_read_digest = input_named(node_by_code(graph_spec, "b_polish"), "draft").digest+ rewrite_digest = only_output(node_by_code(graph_spec, "a_rewrite")).digest++ assert first_draft_digest is not None+ assert polish_read_digest == first_draft_digest+ assert polish_read_digest != rewrite_digest++ async def test_no_outcome_replaces_a_sibling_value_in_the_slot(self, mocker: MockerFixture) -> None:+ """`follow_up` holds nothing before the condition, so no outcome may find it already written."""+ warning_spy = mocker.spy(working_memory_module.log, "warning")++ await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.REPORT_SHAPE_MTHDS])++ assert _replaced_key_warnings(warning_spy.call_args_list, key="follow_up") == []++ async def test_the_default_outcome_names_the_shared_stuff(self) -> None:+ """The default outcome runs last, so its value is the one the next step reads."""+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.SLOT_CROSS_READ_MTHDS])++ shared_digest = only_output(node_by_code(graph_spec, "route")).digest+ assert only_output(node_by_code(graph_spec, "b_polish")).digest == shared_digest+ assert only_output(node_by_code(graph_spec, "a_rewrite")).digest == shared_digestdiff --git a/tests/integration/pipelex/pipeline/dry_run_condition/test_shared_output.py b/tests/integration/pipelex/pipeline/dry_run_condition/test_shared_output.pynew file mode 100644index 000000000..87d15316c--- /dev/null+++ b/tests/integration/pipelex/pipeline/dry_run_condition/test_shared_output.py@@ -0,0 +1,178 @@+"""A dry-run condition's result is one stuff, with a writer per outcome.++A dry run cannot know which outcome a live run would take, so ``PipeCondition`` dry-runs every+outcome. Each outcome writes the condition's one slot, so the GraphSpec must show the condition's+result as one stuff that every outcome writes and the step after the condition reads, rather than+one outcome wired to that step and every other outcome's output left as a stuff nobody reads. Every+outcome's output is merged onto the last outcome's digest, which is the condition's own output+digest, by a record both graph builders apply once the graph is built.+"""++import re++import pytest++from pipelex.graph.graph_analysis import GraphAnalysis+from pipelex.graph.graphspec import EdgeKind, GraphSpec+from pipelex.graph.mermaidflow.mermaidflow_factory import MermaidflowFactory+from pipelex.graph.mermaidflow.mermaidflow_utils import make_stuff_id+from pipelex.pipeline.dry_run_pipeline import dry_run_pipeline+from pipelex.tools.mermaid.mermaid_utils import sanitize_mermaid_id+from tests.integration.pipelex.pipeline.dry_run_condition.graph_reading import (+ input_named,+ node_by_code,+ nodes_by_code,+ only_output,+ output_named,+ read_digests,+)+from tests.integration.pipelex.pipeline.dry_run_condition.test_data import DryRunConditionTestData+from tests.unit.pipelex.graph.conftest import make_graph_config++_SUBGRAPH_OPENING = re.compile(r"^\s*subgraph (\S+?)\[")+++def _subgraphs_declaring(*, mermaid_code: str, mermaid_id: str) -> list[str | None]:+ """The innermost subgraph around each declaration of `mermaid_id`, None at top level."""+ open_subgraphs: list[str] = []+ enclosing: list[str | None] = []+ for line in mermaid_code.splitlines():+ if opening := _SUBGRAPH_OPENING.match(line):+ open_subgraphs.append(opening.group(1))+ elif line.strip() == "end":+ open_subgraphs.pop()+ elif line.strip().startswith(f"{mermaid_id}(["):+ enclosing.append(open_subgraphs[-1] if open_subgraphs else None)+ return enclosing+++def _shared_digest(graph_spec: GraphSpec, *, condition_code: str) -> str:+ digest = only_output(node_by_code(graph_spec, condition_code)).digest+ assert digest is not None+ return digest++[email protected](loop_scope="class")+class TestDryRunConditionSharedOutput:+ async def test_every_outcome_produces_the_stuff_the_next_step_reads(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.REPORT_SHAPE_MTHDS])++ shared_digest = _shared_digest(graph_spec, condition_code="route")+ assert only_output(node_by_code(graph_spec, "write_questions")).digest == shared_digest+ assert only_output(node_by_code(graph_spec, "write_rejection")).digest == shared_digest+ assert input_named(node_by_code(graph_spec, "assemble"), "follow_up").digest == shared_digest++ # The step after the condition reads it through the condition, as in a live run.+ route_node_id = node_by_code(graph_spec, "route").node_id+ assemble_node_id = node_by_code(graph_spec, "assemble").node_id+ data_edges_into_assemble = {+ (edge.source, edge.label) for edge in graph_spec.edges if edge.kind == EdgeKind.DATA and edge.target == assemble_node_id+ }+ assert (route_node_id, "follow_up") in data_edges_into_assemble++ # No outcome's output is left as a stuff nobody reads.+ digests_read = read_digests(graph_spec)+ for outcome_code in ("write_questions", "write_rejection"):+ assert only_output(node_by_code(graph_spec, outcome_code)).digest in digests_read++ async def test_outcomes_that_disagree_type_the_stuff_by_the_declaration(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.DIFFERING_OUTCOMES_MTHDS])++ route_output = only_output(node_by_code(graph_spec, "route"))+ questions_output = only_output(node_by_code(graph_spec, "write_questions"))+ rejection_output = only_output(node_by_code(graph_spec, "write_rejection"))++ assert questions_output.digest == route_output.digest+ assert rejection_output.digest == route_output.digest+ # The condition's own item types the shared stuff by its declaration...+ assert route_output.concept == "Anything"+ assert not route_output.multiplicity+ # ...while each outcome's card keeps what that outcome writes.+ assert questions_output.concept == "Question"+ assert questions_output.multiplicity is True+ assert rejection_output.concept == "Rejection"+ assert not rejection_output.multiplicity++ async def test_outcomes_that_agree_keep_their_typing(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.REPORT_SHAPE_MTHDS])++ route_output = only_output(node_by_code(graph_spec, "route"))+ assert route_output.concept == "Text"+ assert not route_output.multiplicity++ async def test_a_sequence_outcome_moves_its_last_step_with_it(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.SEQUENCE_OUTCOME_MTHDS])++ shared_digest = _shared_digest(graph_spec, condition_code="route")+ assert only_output(node_by_code(graph_spec, "questions_flow")).digest == shared_digest+ assert only_output(node_by_code(graph_spec, "finalize_questions")).digest == shared_digest+ # The sequence's first step is internal to the outcome and keeps its own stuff.+ assert only_output(node_by_code(graph_spec, "draft_questions")).digest != shared_digest++ async def test_a_batch_outcome_moves_its_aggregate_with_it(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.BATCH_OUTCOME_MTHDS])++ shared_digest = _shared_digest(graph_spec, condition_code="route")+ batch_node = node_by_code(graph_spec, "ask_each_topic")+ assert only_output(batch_node).digest == shared_digest++ aggregate_edges = [edge for edge in graph_spec.edges if edge.kind == EdgeKind.BATCH_AGGREGATE and edge.target == batch_node.node_id]+ assert aggregate_edges, "the batch outcome aggregates its items"+ assert {edge.target_stuff_digest for edge in aggregate_edges} == {shared_digest}+ # The batch's items are internal to the outcome and keep their own stuffs.+ item_digests = {only_output(node).digest for node in nodes_by_code(graph_spec, "ask_topic")}+ assert shared_digest not in item_digests+ # The batch writes the stuff as a controller, so the condition still owns it.+ analysis = GraphAnalysis.from_graphspec(graph_spec)+ assert analysis.shared_stuff_controllers == {shared_digest: node_by_code(graph_spec, "route").node_id}++ async def test_a_nested_condition_types_the_outer_stuff_by_the_declaration(self) -> None:+ """Both of `outer`'s outcomes hand back Text, but `inner` declares `Anything` over a Number outcome."""+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.NESTED_CONDITIONS_MTHDS])++ shared_digest = _shared_digest(graph_spec, condition_code="outer")+ for writer_code in ("inner", "score_cv", "summarize_cv", "write_note"):+ assert only_output(node_by_code(graph_spec, writer_code)).digest == shared_digest+ assert only_output(node_by_code(graph_spec, "score_cv")).concept == "Number"++ assert only_output(node_by_code(graph_spec, "outer")).concept == "Anything"+ analysis = GraphAnalysis.from_graphspec(graph_spec)+ assert analysis.shared_stuff_controllers == {shared_digest: node_by_code(graph_spec, "outer").node_id}+ assert analysis.stuff_registry[shared_digest].concept == "Anything"++ async def test_a_condition_run_as_a_batch_branch_types_its_stuff_by_the_declaration(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.BATCH_BRANCH_CONDITION_MTHDS])++ analysis = GraphAnalysis.from_graphspec(graph_spec)+ route_nodes = nodes_by_code(graph_spec, "route")+ assert route_nodes, "the batch runs its condition branch"+ for route_node in route_nodes:+ branch_output = only_output(route_node)+ assert branch_output.digest is not None+ # Both outcomes already write the branch's stuff code; only the typing had to move.+ producer_codes = {analysis.nodes_by_id[node_id].pipe_code for node_id in analysis.get_producers(branch_output.digest)}+ assert producer_codes == {"score_topic", "summarize_topic"}+ assert branch_output.concept == "Anything"+ assert analysis.stuff_registry[branch_output.digest].concept == "Anything"++ async def test_a_parallel_outcome_writes_the_stuff_its_condition_owns(self) -> None:+ graph_spec, _ = await dry_run_pipeline(mthds_contents=[DryRunConditionTestData.PARALLEL_OUTCOME_MTHDS])++ shared_digest = _shared_digest(graph_spec, condition_code="route")+ parallel_node = node_by_code(graph_spec, "write_both")+ # The parallel also lists each branch's output, which stays its own.+ assert output_named(parallel_node, "follow_up").digest == shared_digest+ assert output_named(parallel_node, "questions").digest != shared_digest+ combine_edges = [edge for edge in graph_spec.edges if edge.kind == EdgeKind.PARALLEL_COMBINE and edge.target == parallel_node.node_id]+ assert {edge.target_stuff_digest for edge in combine_edges} == {shared_digest}++ route_node_id = node_by_code(graph_spec, "route").node_id+ analysis = GraphAnalysis.from_graphspec(graph_spec)+ assert analysis.shared_stuff_controllers == {shared_digest: route_node_id}+ # The parallel's Composite and the fallback's Text disagree, so the condition's `Anything` types the stuff.+ assert analysis.stuff_registry[shared_digest].concept == "Anything"++ # The stuff is drawn once, inside the condition, never inside the parallel outcome.+ mermaidflow = MermaidflowFactory.make_from_graphspec(graph_spec, graph_config=make_graph_config())+ declarations = _subgraphs_declaring(mermaid_code=mermaidflow.mermaid_code, mermaid_id=make_stuff_id(shared_digest))+ assert declarations == [f"sg_{sanitize_mermaid_id(route_node_id)}"]diff --git a/tests/integration/pipelex/pipeline/test_dry_run_condition_branch_order.py b/tests/integration/pipelex/pipeline/test_dry_run_condition_branch_order.pyindex 9def277e7..9fea9b163 100644--- a/tests/integration/pipelex/pipeline/test_dry_run_condition_branch_order.py+++ b/tests/integration/pipelex/pipeline/test_dry_run_condition_branch_order.py@@ -1,14 +1,15 @@"""Regression test: a dry run of a ``PipeCondition`` must not depend on set iteration order.``PipeCondition.pipe_dependencies()`` returns a ``set[str]``, and ``_dry_run_controller_pipe``-dry-runs **every** branch into the same working memory under the same ``output_name`` — so the-branch iterated last is the one whose stuff the caller sees as the condition's output. Iterating-the raw set made that "last" a function of string-hash order, which varies per process: the same-bundle dry-run in two processes produced two different graphs, and any consumer diffing graph-specs (the mthds-ui fixture corpus, a static-vs-dry parity check) saw phantom changes.--The loop sorts now. This test pins the property that makes the sort load-bearing: forcing the-dependency set to iterate in either order must produce the same graph.+dry-runs **every** branch under the same ``output_name``, the last one into the condition's own+working memory — so the branch run last is the one whose stuff the caller sees as the condition's+output. Iterating the raw set made that "last" a function of string-hash order, which varies per+process: the same bundle dry-run in two processes produced two different graphs, and any consumer+diffing graph specs (the mthds-ui fixture corpus, a static-vs-dry parity check) saw phantom changes.++The order is a property of the method now: the branches run sorted, with the default outcome's+pipe last. This test pins the property that makes that load-bearing: forcing the dependency set+to iterate in either order must produce the same graph."""from collections.abc import Iterator@@ -139,7 +140,7 @@ class TestDryRunConditionBranchOrder:reverse = await self._graph_output_names(mocker=mocker, reverse=True)assert forward == reverse- # Pin the value too, not just the agreement: the sorted loop ends on the branch whose- # pipe code sorts last, so the enclosing sequence's output is always beta's stuff.- # Without the sort these two runs disagree — alpha_result one way, beta_result the other.- assert forward["respond"] == ["beta_result"]+ # Pin the value too, not just the agreement: the loop ends on the default outcome's pipe,+ # so the enclosing sequence's output is always alpha's stuff, although alpha sorts first.+ # Following set iteration order instead, these two runs disagree.+ assert forward["respond"] == ["alpha_result"]diff --git a/tests/unit/pipelex/graph/test_condition_output_merge.py b/tests/unit/pipelex/graph/test_condition_output_merge.pynew file mode 100644index 000000000..36f8e6441--- /dev/null+++ b/tests/unit/pipelex/graph/test_condition_output_merge.py@@ -0,0 +1,220 @@+"""Unit tests for the rewrite that gives every outcome of a dry-run condition the condition's output digest."""++from datetime import UTC, datetime+from typing import ClassVar++import pytest++from pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTyping, apply_condition_output_merges+from pipelex.graph.graphspec import EdgeKind, EdgeSpec, GraphSpec, IOSpec, NodeIOSpec, NodeKind, NodeSpec, NodeStatus+++def _node(*, node_id: str, kind: NodeKind = NodeKind.OPERATOR, inputs: list[IOSpec] | None = None, outputs: list[IOSpec] | None = None) -> NodeSpec:+ return NodeSpec(+ node_id=node_id,+ kind=kind,+ pipe_code=node_id,+ status=NodeStatus.SUCCEEDED,+ node_io=NodeIOSpec(inputs=inputs or [], outputs=outputs or []),+ )+++def _contains(*, source: str, target: str) -> EdgeSpec:+ return EdgeSpec(edge_id=f"contains_{source}_{target}", source=source, target=target, kind=EdgeKind.CONTAINS)+++def _outputs_by_node(graph: GraphSpec) -> dict[str, list[IOSpec]]:+ return {node.node_id: node.node_io.outputs for node in graph.nodes}+++def _inputs_by_node(graph: GraphSpec) -> dict[str, list[IOSpec]]:+ return {node.node_id: node.node_io.inputs for node in graph.nodes}+++class TestApplyConditionOutputMerges:+ CREATED_AT: ClassVar[datetime] = datetime(2026, 10, 5, 12, 0, 0, tzinfo=UTC)++ def _graph(self, *, nodes: list[NodeSpec], edges: list[EdgeSpec]) -> GraphSpec:+ return GraphSpec(graph_id="merge_test", created_at=self.CREATED_AT, nodes=nodes, edges=edges)++ def _report_shape(self) -> GraphSpec:+ """`route` runs `write_questions` then `write_rejection`, whose stuff `assemble` reads."""+ return self._graph(+ nodes=[+ _node(+ node_id="route",+ kind=NodeKind.CONTROLLER,+ inputs=[IOSpec(name="verdict", concept="Text", digest="d_verdict")],+ outputs=[IOSpec(name="follow_up", concept="Rejection", digest="d_rejection")],+ ),+ _node(node_id="write_questions", outputs=[IOSpec(name="follow_up", concept="Question", multiplicity=True, digest="d_questions")]),+ _node(node_id="write_rejection", outputs=[IOSpec(name="follow_up", concept="Rejection", digest="d_rejection")]),+ _node(+ node_id="assemble",+ inputs=[+ IOSpec(name="verdict", concept="Text", digest="d_verdict"),+ IOSpec(name="follow_up", concept="Anything", digest="d_rejection"),+ ],+ outputs=[IOSpec(name="result", concept="Text", digest="d_result")],+ ),+ ],+ edges=[+ _contains(source="route", target="write_questions"),+ _contains(source="route", target="write_rejection"),+ EdgeSpec(edge_id="data_route_assemble", source="route", target="assemble", kind=EdgeKind.DATA, label="follow_up"),+ ],+ )++ def test_no_merge_leaves_the_graph_alone(self) -> None:+ graph = self._report_shape()+ assert apply_condition_output_merges(graph=graph, merges=[]) == graph++ def test_every_outcome_takes_the_shared_digest(self) -> None:+ graph = self._report_shape()+ merge = ConditionOutputMerge(condition_node_id="route", shared_digest="d_rejection", merged_digests=["d_questions"])++ merged = apply_condition_output_merges(graph=graph, merges=[merge])++ outputs = _outputs_by_node(merged)+ assert [spec.digest for spec in outputs["write_questions"]] == ["d_rejection"]+ assert [spec.digest for spec in outputs["write_rejection"]] == ["d_rejection"]+ assert [spec.digest for spec in outputs["route"]] == ["d_rejection"]+ assert [spec.digest for spec in _inputs_by_node(merged)["assemble"]] == ["d_verdict", "d_rejection"]+ # Each outcome keeps what it writes: only the digest moves.+ assert outputs["write_questions"][0].concept == "Question"+ assert outputs["write_questions"][0].multiplicity is True+ # Without a typing, the condition's own item is untouched.+ assert outputs["route"][0].concept == "Rejection"++ def test_a_typing_retypes_the_condition_item_only(self) -> None:+ graph = self._report_shape()+ merge = ConditionOutputMerge(+ condition_node_id="route",+ shared_digest="d_rejection",+ merged_digests=["d_questions"],+ shared_typing=ConditionOutputTyping(concept="Anything", multiplicity=None),+ )++ merged = apply_condition_output_merges(graph=graph, merges=[merge])++ outputs = _outputs_by_node(merged)+ assert outputs["route"][0].concept == "Anything"+ assert outputs["route"][0].multiplicity is None+ assert outputs["write_questions"][0].concept == "Question"+ assert outputs["write_questions"][0].multiplicity is True+ assert outputs["write_rejection"][0].concept == "Rejection"+ assert _inputs_by_node(merged)["assemble"][1].concept == "Anything"+ assert _inputs_by_node(merged)["route"][0].concept == "Text"++ def test_a_typing_types_a_list(self) -> None:+ graph = self._report_shape()+ merge = ConditionOutputMerge(+ condition_node_id="route",+ shared_digest="d_rejection",+ merged_digests=["d_questions"],+ shared_typing=ConditionOutputTyping(concept="Question", multiplicity=True),+ )++ merged = apply_condition_output_merges(graph=graph, merges=[merge])++ route_output = _outputs_by_node(merged)["route"][0]+ assert route_output.concept_label == "Question[]"++ @pytest.mark.parametrize("inner_first", [True, False])+ def test_a_nested_condition_lands_on_the_outer_digest(self, *, inner_first: bool) -> None:+ """`outer` runs `inner` then `fallback`; `inner` runs `x` then `y`. Every one ends on `fallback`'s digest."""+ graph = self._graph(+ nodes=[+ _node(node_id="outer", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="slot", digest="d_fallback")]),+ _node(node_id="inner", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="slot", digest="d_y")]),+ _node(node_id="x", outputs=[IOSpec(name="slot", digest="d_x")]),+ _node(node_id="y", outputs=[IOSpec(name="slot", digest="d_y")]),+ _node(node_id="fallback", outputs=[IOSpec(name="slot", digest="d_fallback")]),+ ],+ edges=[+ _contains(source="outer", target="inner"),+ _contains(source="outer", target="fallback"),+ _contains(source="inner", target="x"),+ _contains(source="inner", target="y"),+ ],+ )+ inner_merge = ConditionOutputMerge(condition_node_id="inner", shared_digest="d_y", merged_digests=["d_x"])+ outer_merge = ConditionOutputMerge(condition_node_id="outer", shared_digest="d_fallback", merged_digests=["d_y"])+ merges = [inner_merge, outer_merge] if inner_first else [outer_merge, inner_merge]++ merged = apply_condition_output_merges(graph=graph, merges=merges)++ assert {node_id: [spec.digest for spec in specs] for node_id, specs in _outputs_by_node(merged).items()} == {+ "outer": ["d_fallback"],+ "inner": ["d_fallback"],+ "x": ["d_fallback"],+ "y": ["d_fallback"],+ "fallback": ["d_fallback"],+ }++ def test_a_nested_typing_retypes_the_inner_condition_item(self) -> None:+ """A typing names the item by the digest it had when recorded, which a later merge may move."""+ graph = self._graph(+ nodes=[+ _node(node_id="outer", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="slot", concept="Text", digest="d_fallback")]),+ _node(node_id="inner", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="slot", concept="Email", digest="d_y")]),+ _node(node_id="x", outputs=[IOSpec(name="slot", concept="Question", digest="d_x")]),+ _node(node_id="y", outputs=[IOSpec(name="slot", concept="Email", digest="d_y")]),+ _node(node_id="fallback", outputs=[IOSpec(name="slot", concept="Text", digest="d_fallback")]),+ ],+ edges=[],+ )+ merges = [+ ConditionOutputMerge(+ condition_node_id="inner",+ shared_digest="d_y",+ merged_digests=["d_x"],+ shared_typing=ConditionOutputTyping(concept="Anything", multiplicity=None),+ ),+ ConditionOutputMerge(condition_node_id="outer", shared_digest="d_fallback", merged_digests=["d_y"]),+ ]++ merged = apply_condition_output_merges(graph=graph, merges=merges)++ inner_output = _outputs_by_node(merged)["inner"][0]+ assert inner_output.digest == "d_fallback"+ assert inner_output.concept == "Anything"+ assert _outputs_by_node(merged)["outer"][0].concept == "Text"++ def test_stuff_to_stuff_edges_follow_the_merge(self) -> None:+ graph = self._graph(+ nodes=[+ _node(node_id="route", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="answers", digest="d_default")]),+ _node(node_id="ask_each", kind=NodeKind.CONTROLLER, outputs=[IOSpec(name="answers", multiplicity=True, digest="d_batch")]),+ _node(node_id="ask_one", outputs=[IOSpec(name="answer", digest="d_item_0")]),+ _node(node_id="write_default", outputs=[IOSpec(name="answers", multiplicity=True, digest="d_default")]),+ ],+ edges=[+ EdgeSpec(+ edge_id="aggregate",+ source="ask_one",+ target="ask_each",+ kind=EdgeKind.BATCH_AGGREGATE,+ source_stuff_digest="d_item_0",+ target_stuff_digest="d_batch",+ ),+ EdgeSpec(+ edge_id="combine",+ source="ask_one",+ target="ask_each",+ kind=EdgeKind.PARALLEL_COMBINE,+ source_stuff_digest="d_batch",+ target_stuff_digest="d_other",+ ),+ _contains(source="route", target="ask_each"),+ ],+ )+ merge = ConditionOutputMerge(condition_node_id="route", shared_digest="d_default", merged_digests=["d_batch"])++ merged = apply_condition_output_merges(graph=graph, merges=[merge])++ edges = {edge.edge_id: edge for edge in merged.edges}+ assert (edges["aggregate"].source_stuff_digest, edges["aggregate"].target_stuff_digest) == ("d_item_0", "d_default")+ assert (edges["combine"].source_stuff_digest, edges["combine"].target_stuff_digest) == ("d_default", "d_other")+ assert (edges["contains_route_ask_each"].source_stuff_digest, edges["contains_route_ask_each"].target_stuff_digest) == (None, None)+ assert _outputs_by_node(merged)["ask_one"][0].digest == "d_item_0"diff --git a/tests/unit/pipelex/graph/test_graph_analysis.py b/tests/unit/pipelex/graph/test_graph_analysis.pyindex 9f336eaae..4bc70ef98 100644--- a/tests/unit/pipelex/graph/test_graph_analysis.py+++ b/tests/unit/pipelex/graph/test_graph_analysis.py@@ -245,7 +245,7 @@ class TestGraphAnalysis:assert stuff_info.data == "input content"def test_stuff_producers_map(self) -> None:- """Test that stuff_producers maps digest to producer node_id."""+ """Test that stuff_producers maps digest to its producer node_ids."""producer_node = {"node_id": "producer_1","kind": NodeKind.OPERATOR,@@ -259,7 +259,7 @@ class TestGraphAnalysis:graph = self._make_graph(nodes=[producer_node])analysis = GraphAnalysis.from_graphspec(graph)- assert analysis.stuff_producers.get("digest_abc") == "producer_1"+ assert analysis.stuff_producers.get("digest_abc") == ["producer_1"]def test_stuff_consumers_map(self) -> None:"""Test that stuff_consumers maps digest to list of consumer node_ids."""@@ -334,9 +334,9 @@ class TestGraphAnalysis:analysis = GraphAnalysis.from_graphspec(graph)# Controller should not be in producers- assert analysis.stuff_producers.get("ctrl_out_digest") != "ctrl_1"+ assert "ctrl_out_digest" not in analysis.stuff_producers# Child should be the producer- assert analysis.stuff_producers.get("child_digest") == "child_1"+ assert analysis.stuff_producers.get("child_digest") == ["child_1"]def test_deterministic_analysis(self) -> None:"""Test that same GraphSpec yields same analysis."""@@ -470,8 +470,8 @@ class TestGraphAnalysis:assert analysis.get_stuff_info("nonexistent") is None- def test_get_producer_helper(self) -> None:- """Test the get_producer helper method."""+ def test_get_producers_helper(self) -> None:+ """Test the get_producers helper method."""producer_node = {"node_id": "producer_1","kind": NodeKind.OPERATOR,@@ -485,8 +485,8 @@ class TestGraphAnalysis:graph = self._make_graph(nodes=[producer_node])analysis = GraphAnalysis.from_graphspec(graph)- assert analysis.get_producer("digest_001") == "producer_1"- assert analysis.get_producer("nonexistent") is None+ assert analysis.get_producers("digest_001") == ["producer_1"]+ assert analysis.get_producers("nonexistent") == []def test_get_consumers_helper(self) -> None:"""Test the get_consumers helper method."""@@ -600,3 +600,141 @@ class TestGraphAnalysis:# Only outer_ctrl should be in root_nodesroot_ids = {node.node_id for node in analysis.root_nodes}assert root_ids == {"ctrl_outer"}++ def _merged_condition_graph(self) -> GraphSpec:+ """A dry-run condition whose two outcomes both produce the stuff the next step reads."""+ return self._make_graph(+ nodes=[+ {"node_id": "screen", "kind": NodeKind.CONTROLLER, "pipe_code": "screen", "status": NodeStatus.SUCCEEDED},+ {+ "node_id": "route",+ "kind": NodeKind.CONTROLLER,+ "pipe_code": "route",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Anything", digest="d_shared")]),+ },+ {+ "node_id": "write_questions",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_questions",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="questions", concept="Question", multiplicity=True, digest="d_shared")]),+ },+ {+ "node_id": "write_rejection",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_rejection",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Rejection", digest="d_shared")]),+ },+ {+ "node_id": "assemble",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "assemble",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(inputs=[IOSpec(name="follow_up", concept="Anything", digest="d_shared")]),+ },+ ],+ edges=[+ {"edge_id": "c1", "source": "screen", "target": "route", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c2", "source": "screen", "target": "assemble", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c3", "source": "route", "target": "write_questions", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c4", "source": "route", "target": "write_rejection", "kind": EdgeKind.CONTAINS},+ ],+ )++ def test_a_stuff_lists_every_producer(self) -> None:+ analysis = GraphAnalysis.from_graphspec(self._merged_condition_graph())++ assert analysis.get_producers("d_shared") == ["write_questions", "write_rejection"]+ assert analysis.get_consumers("d_shared") == ["assemble"]++ def test_a_stuff_with_several_producers_belongs_to_their_deepest_common_controller(self) -> None:+ analysis = GraphAnalysis.from_graphspec(self._merged_condition_graph())++ assert analysis.shared_stuff_controllers == {"d_shared": "route"}+ # The controller's own item types the stuff, since only its declaration covers every producer.+ stuff_info = analysis.get_stuff_info("d_shared")+ assert stuff_info is not None+ assert (stuff_info.name, stuff_info.concept, stuff_info.multiplicity) == ("follow_up", "Anything", None)++ def _parallel_outcome_graph(self, *, with_fallback: bool) -> GraphSpec:+ """A dry-run condition whose parallel outcome combines its branches into the stuff its fallback produces."""+ nodes: list[dict[str, Any]] = [+ {+ "node_id": "route",+ "kind": NodeKind.CONTROLLER,+ "pipe_code": "route",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Anything", digest="d_shared")]),+ },+ {+ "node_id": "write_both",+ "kind": NodeKind.CONTROLLER,+ "pipe_code": "write_both",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Composite", digest="d_shared")]),+ },+ {+ "node_id": "write_questions",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_questions",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="questions", concept="Text", digest="d_questions")]),+ },+ {+ "node_id": "write_notes",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_notes",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="notes", concept="Text", digest="d_notes")]),+ },+ ]+ edges: list[dict[str, Any]] = [+ {"edge_id": "c1", "source": "route", "target": "write_both", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c2", "source": "write_both", "target": "write_questions", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c3", "source": "write_both", "target": "write_notes", "kind": EdgeKind.CONTAINS},+ {+ "edge_id": "p1",+ "source": "write_questions",+ "target": "write_both",+ "kind": EdgeKind.PARALLEL_COMBINE,+ "source_stuff_digest": "d_questions",+ "target_stuff_digest": "d_shared",+ },+ {+ "edge_id": "p2",+ "source": "write_notes",+ "target": "write_both",+ "kind": EdgeKind.PARALLEL_COMBINE,+ "source_stuff_digest": "d_notes",+ "target_stuff_digest": "d_shared",+ },+ ]+ if with_fallback:+ nodes.append(+ {+ "node_id": "write_rejection",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_rejection",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Text", digest="d_shared")]),+ }+ )+ edges.append({"edge_id": "c4", "source": "route", "target": "write_rejection", "kind": EdgeKind.CONTAINS})+ return self._make_graph(nodes=nodes, edges=edges)++ def test_a_parallel_outcome_writes_the_shared_stuff_as_a_controller(self) -> None:+ analysis = GraphAnalysis.from_graphspec(self._parallel_outcome_graph(with_fallback=True))++ # The parallel combines into the stuff without producing it, and still makes it shared.+ assert analysis.get_producers("d_shared") == ["write_rejection"]+ assert analysis.shared_stuff_controllers == {"d_shared": "route"}+ stuff_info = analysis.get_stuff_info("d_shared")+ assert stuff_info is not None+ assert stuff_info.concept == "Anything"++ def test_a_parallel_alone_does_not_share_its_combined_stuff(self) -> None:+ analysis = GraphAnalysis.from_graphspec(self._parallel_outcome_graph(with_fallback=False))++ assert analysis.shared_stuff_controllers == {}diff --git a/tests/unit/pipelex/graph/test_mermaidflow.py b/tests/unit/pipelex/graph/test_mermaidflow.pyindex 67bf47edf..99b69bf3b 100644--- a/tests/unit/pipelex/graph/test_mermaidflow.py+++ b/tests/unit/pipelex/graph/test_mermaidflow.py@@ -15,6 +15,7 @@ from pipelex.graph.graphspec import (from pipelex.graph.mermaidflow.mermaidflow_factory import MermaidflowFactoryfrom pipelex.graph.mermaidflow.mermaidflow_utils import make_stuff_idfrom pipelex.graph.mermaidflow.stuff_collector import collect_stuff_metadata+from pipelex.tools.mermaid.mermaid_utils import sanitize_mermaid_idfrom .conftest import make_graph_config@@ -507,3 +508,74 @@ class TestMermaidflow:metadata = collect_stuff_metadata(graph)assert metadata[make_stuff_id("records_digest")]["concept"] == "Record[]"assert metadata[make_stuff_id("summary_digest")]["concept"] == "Text"++ def _merged_condition_graph(self) -> GraphSpec:+ """A dry-run condition whose two outcomes both produce the stuff the next step reads."""+ return self._make_graph(+ nodes=[+ {"node_id": "screen", "kind": NodeKind.CONTROLLER, "pipe_code": "screen", "status": NodeStatus.SUCCEEDED},+ {+ "node_id": "route",+ "kind": NodeKind.CONTROLLER,+ "pipe_code": "route",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Anything", digest="d_shared")]),+ },+ {+ "node_id": "write_questions",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_questions",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Question", multiplicity=True, digest="d_shared")]),+ },+ {+ "node_id": "write_rejection",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "write_rejection",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(outputs=[IOSpec(name="follow_up", concept="Rejection", digest="d_shared")]),+ },+ {+ "node_id": "assemble",+ "kind": NodeKind.OPERATOR,+ "pipe_code": "assemble",+ "status": NodeStatus.SUCCEEDED,+ "node_io": NodeIOSpec(+ inputs=[IOSpec(name="follow_up", concept="Anything", digest="d_shared")],+ outputs=[IOSpec(name="result", concept="Text", digest="d_result")],+ ),+ },+ ],+ edges=[+ {"edge_id": "c1", "source": "screen", "target": "route", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c2", "source": "screen", "target": "assemble", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c3", "source": "route", "target": "write_questions", "kind": EdgeKind.CONTAINS},+ {"edge_id": "c4", "source": "route", "target": "write_rejection", "kind": EdgeKind.CONTAINS},+ ],+ )++ def test_a_merged_stuff_renders_once_inside_its_condition(self) -> None:+ result = MermaidflowFactory.make_from_graphspec(self._merged_condition_graph(), graph_config=make_graph_config())+ lines = result.mermaid_code.split("\n")+ stuff_id = make_stuff_id("d_shared")++ stuff_node_lines = [+ index for index, line in enumerate(lines) if line.strip().startswith(f"{stuff_id}[") or line.strip().startswith(f"{stuff_id}(")+ ]+ assert len(stuff_node_lines) == 1, result.mermaid_code+ route_start = next(index for index, line in enumerate(lines) if line.strip().startswith(f"subgraph sg_{sanitize_mermaid_id('route')}"))+ route_end = next(index for index in range(route_start, len(lines)) if lines[index].strip() == "end")+ assert route_start < stuff_node_lines[0] < route_end, result.mermaid_code+ # Typed by the condition's own item, which covers both outcomes.+ assert "Anything" in lines[stuff_node_lines[0]]++ def test_a_merged_stuff_has_an_edge_from_each_producer(self) -> None:+ for include_subgraphs in (True, False):+ result = MermaidflowFactory.make_from_graphspec(+ self._merged_condition_graph(), graph_config=make_graph_config(), include_subgraphs=include_subgraphs+ )+ stuff_id = make_stuff_id("d_shared")++ assert f"{sanitize_mermaid_id('write_questions')} --> {stuff_id}" in result.mermaid_code+ assert f"{sanitize_mermaid_id('write_rejection')} --> {stuff_id}" in result.mermaid_code+ assert f"{stuff_id} --> {sanitize_mermaid_id('assemble')}" in result.mermaid_codediff --git a/tests/unit/pipelex/tracing/test_assembler_equivalence.py b/tests/unit/pipelex/tracing/test_assembler_equivalence.pyindex 21fab505d..83337d929 100644--- a/tests/unit/pipelex/tracing/test_assembler_equivalence.py+++ b/tests/unit/pipelex/tracing/test_assembler_equivalence.py@@ -17,6 +17,7 @@ import pytestfrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategoryfrom pipelex.cogt.usage.token_category import TokenCategory+from pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTypingfrom pipelex.graph.graph_tracer import GraphTracerfrom pipelex.graph.graphspec import EdgeKind, EdgeSpec, GraphSpec, IOSpec, NodeKind, NodeSpecfrom pipelex.system.job_metadata import JobCategory, JobMetadata, RunMetadata, UnitJobId@@ -60,25 +61,27 @@ def _normalize_node(node: NodeSpec) -> dict[str, Any]:"error_type": node.error.error_type if node.error else None,"error_message": node.error.message if node.error else None,"metrics": node.metrics,- # Multiplicity rides along so both builders are held to carry each io item's marker.+ # Concept and multiplicity ride along so both builders are held to carry each io item's typing."inputs": sorted(- [(spec.name, spec.digest, spec.multiplicity) for spec in node.node_io.inputs],- key=lambda triple: (triple[0] or "", triple[1] or ""),+ [(spec.name, spec.digest, spec.concept, spec.multiplicity) for spec in node.node_io.inputs],+ key=lambda item: (item[0] or "", item[1] or ""),),"outputs": sorted(- [(spec.name, spec.digest, spec.multiplicity) for spec in node.node_io.outputs],- key=lambda triple: (triple[0] or "", triple[1] or ""),+ [(spec.name, spec.digest, spec.concept, spec.multiplicity) for spec in node.node_io.outputs],+ key=lambda item: (item[0] or "", item[1] or ""),),}-def _normalize_edge(edge: EdgeSpec) -> tuple[str, str, EdgeKind, str | None]:+def _normalize_edge(edge: EdgeSpec) -> tuple[str, str, EdgeKind, str | None, str | None, str | None]:"""Extract structurally comparable fields from an EdgeSpec."""return (_normalize_id(edge.source),_normalize_id(edge.target),edge.kind,edge.label,+ edge.source_stuff_digest,+ edge.target_stuff_digest,)@@ -525,6 +528,107 @@ def _scenario_condition_selected_outcome(tracer: GraphTracer, context: TraceCont)+def _scenario_dry_condition_merge(tracer: GraphTracer, context: TraceContext) -> None:+ """Dry-run condition whose two outcomes write different concepts into the slot a consumer reads.++ `write_questions` is a batch whose aggregate edge names its output list; `write_rejection` runs+ last, so its stuff is the condition's output and the one `assemble` reads.+ """+ started_at = _T0++ seq_id, seq_ctx = tracer.on_pipe_start(+ trace_context=context,+ pipe_code="screen",+ pipe_type="PipeSequence",+ node_kind=NodeKind.CONTROLLER,+ started_at=started_at,+ )+ cond_id, cond_ctx = tracer.on_pipe_start(+ trace_context=seq_ctx,+ pipe_code="route",+ pipe_type="PipeCondition",+ node_kind=NodeKind.CONTROLLER,+ started_at=started_at + timedelta(seconds=1),+ input_specs=[IOSpec(name="verdict", concept="Text", digest="digest_verdict")],+ )++ batch_id, batch_ctx = tracer.on_pipe_start(+ trace_context=cond_ctx,+ pipe_code="write_questions",+ pipe_type="PipeBatch",+ node_kind=NodeKind.CONTROLLER,+ started_at=started_at + timedelta(seconds=2),+ )+ item_id, _ = tracer.on_pipe_start(+ trace_context=batch_ctx,+ pipe_code="write_question",+ pipe_type="PipeLLM",+ node_kind=NodeKind.OPERATOR,+ started_at=started_at + timedelta(seconds=3),+ )+ tracer.on_pipe_end_success(+ node_id=item_id,+ ended_at=started_at + timedelta(seconds=4),+ output_spec=IOSpec(name="follow_up", concept="Question", digest="digest_question_0"),+ )+ tracer.register_batch_aggregation(+ output_list_stuff_code="digest_questions",+ item_stuff_code="digest_question_0",+ item_index=0,+ batch_controller_node_id=batch_id,+ )+ tracer.on_pipe_end_success(+ node_id=batch_id,+ ended_at=started_at + timedelta(seconds=5),+ output_spec=IOSpec(name="follow_up", concept="Question", multiplicity=True, digest="digest_questions"),+ )++ rejection_id, _ = tracer.on_pipe_start(+ trace_context=cond_ctx,+ pipe_code="write_rejection",+ pipe_type="PipeLLM",+ node_kind=NodeKind.OPERATOR,+ started_at=started_at + timedelta(seconds=6),+ )+ tracer.on_pipe_end_success(+ node_id=rejection_id,+ ended_at=started_at + timedelta(seconds=7),+ output_spec=IOSpec(name="follow_up", concept="Rejection", digest="digest_rejection"),+ )+ tracer.register_condition_output_merge(+ merge=ConditionOutputMerge(+ condition_node_id=cond_id,+ shared_digest="digest_rejection",+ merged_digests=["digest_questions"],+ shared_typing=ConditionOutputTyping(concept="Anything"),+ ),+ )+ tracer.on_pipe_end_success(+ node_id=cond_id,+ ended_at=started_at + timedelta(seconds=8),+ output_spec=IOSpec(name="follow_up", concept="Rejection", digest="digest_rejection"),+ )++ assemble_id, _ = tracer.on_pipe_start(+ trace_context=seq_ctx,+ pipe_code="assemble",+ pipe_type="PipeLLM",+ node_kind=NodeKind.OPERATOR,+ started_at=started_at + timedelta(seconds=9),+ input_specs=[IOSpec(name="follow_up", concept="Anything", digest="digest_rejection")],+ )+ tracer.on_pipe_end_success(+ node_id=assemble_id,+ ended_at=started_at + timedelta(seconds=10),+ output_spec=IOSpec(name="result", concept="Text", digest="digest_result"),+ )+ tracer.on_pipe_end_success(+ node_id=seq_id,+ ended_at=started_at + timedelta(seconds=11),+ output_spec=IOSpec(name="result", concept="Text", digest="digest_result"),+ )++# ---------------------------------------------------------------------------# Tests# ---------------------------------------------------------------------------@@ -542,6 +646,7 @@ class TestAssemblerEquivalence:pytest.param(_scenario_partial_failure, id="partial_failure"),pytest.param(_scenario_pass_through, id="pass_through"),pytest.param(_scenario_condition_selected_outcome, id="condition_selected_outcome"),+ pytest.param(_scenario_dry_condition_merge, id="dry_condition_merge"),],)def test_equivalence(self, scenario_fn: ScenarioFn) -> None:@@ -563,6 +668,17 @@ class TestAssemblerEquivalence:assert multiplicity_by_digest["digest_item_0"] is Noneassert multiplicity_by_digest["digest_result_0"] is None+ def test_condition_merge_survives_both_builders(self) -> None:+ """Agreement alone would pass if both builders dropped the merge, so pin the merged shape too."""+ direct_spec, assembled_spec = _run_both_paths(_scenario_dry_condition_merge)+ for spec in (direct_spec, assembled_spec):+ outputs_by_code = {node.pipe_code: node.node_io.outputs for node in spec.nodes}+ assert [(item.digest, item.concept) for item in outputs_by_code["route"]] == [("digest_rejection", "Anything")]+ assert [(item.digest, item.concept) for item in outputs_by_code["write_questions"]] == [("digest_rejection", "Question")]+ assert [(item.digest, item.concept) for item in outputs_by_code["write_rejection"]] == [("digest_rejection", "Rejection")]+ aggregate_edges = [edge for edge in spec.edges if edge.kind == EdgeKind.BATCH_AGGREGATE]+ assert [(edge.source_stuff_digest, edge.target_stuff_digest) for edge in aggregate_edges] == [("digest_question_0", "digest_rejection")]+def test_usage_is_the_one_intentional_divergence(self) -> None:"""The two builders stay structurally equivalent, and diverge on `usage` on purpose.diff --git a/tests/unit/pipelex/tracing/test_trace_events.py b/tests/unit/pipelex/tracing/test_trace_events.pyindex 171f71220..9219da969 100644--- a/tests/unit/pipelex/tracing/test_trace_events.py+++ b/tests/unit/pipelex/tracing/test_trace_events.py@@ -9,12 +9,14 @@ from pydantic import TypeAdapterfrom pipelex.cogt.llm.llm_report import LLMTokensUsagefrom pipelex.cogt.usage.cost_category import CostCategoryfrom pipelex.cogt.usage.token_category import TokenCategory+from pipelex.graph.condition_output_merge import ConditionOutputMerge, ConditionOutputTypingfrom pipelex.graph.graphspec import EdgeKind, ErrorSpec, IOSpec, NodeKindfrom pipelex.system.job_metadata import JobCategory, JobMetadata, RunMetadata, UnitJobIdfrom pipelex.tracing.trace_events import (AnyTraceEvent,BatchAggregateEvent,BatchItemEvent,+ ConditionOutputMergeEvent,ControllerOutputEvent,EdgeEvent,ExecutionDataEvent,@@ -185,6 +187,18 @@ class TestTraceEvents:"branch_producer_node_ids": [("branch_a", "graph_1:wf_a:node_0"), ("branch_b", "graph_1:wf_b:node_0")],},),+ (+ "condition_output_merge",+ TraceEventKind.CONDITION_OUTPUT_MERGE,+ {+ "merge": ConditionOutputMerge(+ condition_node_id=_Shared.PARENT_NODE_ID,+ shared_digest="shared_001",+ merged_digests=["outcome_a"],+ shared_typing=ConditionOutputTyping(concept="Anything", multiplicity=True),+ ),+ },+ ),("execution_data",TraceEventKind.EXECUTION_DATA,@@ -213,6 +227,7 @@ class TestTraceEvents:TraceEventKind.BATCH_ITEM: BatchItemEvent,TraceEventKind.BATCH_AGGREGATE: BatchAggregateEvent,TraceEventKind.PARALLEL_COMBINE: ParallelCombineEvent,+ TraceEventKind.CONDITION_OUTPUT_MERGE: ConditionOutputMergeEvent,TraceEventKind.EXECUTION_DATA: ExecutionDataEvent,TraceEventKind.USAGE_REPORT: UsageReportEvent,}