Skip to content

Commit a597d31

Browse files
aryamangodaraclaudedavidsbatista
authored
fix: let Pipeline.connect accept a Literal output for an input of its value type (#13642)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: David S. Batista <dsbatista@gmail.com>
1 parent c1528ea commit a597d31

5 files changed

Lines changed: 74 additions & 1 deletion

File tree

‎haystack/core/type_utils.py‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,16 @@ def _strict_types_are_compatible(sender: Any, receiver: Any) -> bool: # noqa: P
165165
if (sender_origin is Union and not sender_args) or (receiver_origin is Union and not receiver_args):
166166
return False
167167

168+
# A Literal stands for its values: each one must match the receiver, either by its type or, when the receiver is
169+
# a Union, as a member of one of its Literal arguments. Literal receivers are matched by membership below.
170+
if sender_origin is Literal and receiver_origin is not Literal:
171+
if receiver_origin is Union:
172+
return all(
173+
any(_strict_types_are_compatible(Literal[value], union_arg) for union_arg in receiver_args)
174+
for value in sender_args
175+
)
176+
return all(_strict_types_are_compatible(type(value), receiver) for value in sender_args)
177+
168178
if sender_origin is not Union and receiver_origin is Union:
169179
return any(_strict_types_are_compatible(sender, union_arg) for union_arg in receiver_args)
170180

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
fixes:
3+
- |
4+
``Pipeline.connect()`` now accepts a ``Literal`` output connected to an input that takes the type of its values.
5+
For example, an output declared as ``Literal["positive", "negative"]`` can feed a ``str`` input, and
6+
``Literal["a"]`` can feed ``str | None`` or ``list[str]``. Before, these connections raised a
7+
``PipelineConnectError`` even though every value the sender can produce is valid for the receiver.

‎test/core/pipeline/test_pipeline.py‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import logging
66
from concurrent.futures import ThreadPoolExecutor
7+
from typing import Literal
78

89
import pytest
910

@@ -551,3 +552,32 @@ def run(self, text: str) -> dict[str, str]:
551552
p.add_component("consumer", SingleStrConsumer())
552553
p.connect("producer.texts", "consumer.text")
553554
assert p.run({}) == {"consumer": {"out": "only-one"}}
555+
556+
def test_run_wraps_literal_output_into_list_input(self):
557+
@component
558+
class LiteralProducer:
559+
@component.output_types(label=Literal["a", "b"])
560+
def run(self) -> dict[str, str]:
561+
return {"label": "a"}
562+
563+
p = Pipeline()
564+
p.add_component("producer", LiteralProducer())
565+
p.add_component("receiver", ListStrAcceptor())
566+
p.connect("producer.label", "receiver.texts")
567+
568+
assert p.run({}) == {"receiver": {"result": ["a"]}}
569+
570+
@pytest.mark.asyncio
571+
async def test_run_async_wraps_literal_output_into_list_input(self):
572+
@component
573+
class LiteralProducer:
574+
@component.output_types(label=Literal["a", "b"])
575+
def run(self) -> dict[str, str]:
576+
return {"label": "a"}
577+
578+
p = Pipeline()
579+
p.add_component("producer", LiteralProducer())
580+
p.add_component("receiver", ListStrAcceptor())
581+
p.connect("producer.label", "receiver.texts")
582+
583+
assert await p.run_async({}) == {"receiver": {"result": ["a"]}}

‎test/core/pipeline/test_pipeline_base.py‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44

55
import logging
66
from collections.abc import Iterable
7-
from typing import Any
7+
from typing import Any, Literal
88
from unittest.mock import patch
99

1010
import pytest
@@ -2320,6 +2320,16 @@ def test_connect_list_output_to_iterable_input(self):
23202320
assert list(pipe.graph.edges) == [("producer", "consumer", "items/sources")]
23212321
assert pipe.graph["producer"]["consumer"]["items/sources"]["conversion_strategy"] is None
23222322

2323+
def test_connect_literal_output_to_str_input(self):
2324+
producer = component_class("Producer", output_types={"label": Literal["positive", "negative"]})()
2325+
consumer = component_class("Consumer", input_types={"text": str})()
2326+
pipe = PipelineBase()
2327+
pipe.add_component("producer", producer)
2328+
pipe.add_component("consumer", consumer)
2329+
pipe.connect("producer.label", "consumer.text")
2330+
assert list(pipe.graph.edges) == [("producer", "consumer", "label/text")]
2331+
assert pipe.graph["producer"]["consumer"]["label/text"]["conversion_strategy"] is None
2332+
23232333
def test_connect_list_output_to_list_or_iterable_input_is_ambiguous(self):
23242334
producer = component_class("Producer", output_types={"value": list[str]})()
23252335
consumer = component_class("Consumer", input_types={"list_items": list[str], "iterable_items": Iterable[str]})()

‎test/core/test_type_utils.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,16 @@ def generate_strict_asymmetric_cases():
181181
pytest.param(bool, int, id="different-primitives"),
182182
pytest.param((Literal["a", "b"]), (Literal["a", "b", "c"]), id="sending-subset-literal"),
183183
pytest.param((Literal["b", "c"]), (Literal["a", "b", "c"]), id="sending-non-prefix-subset-literal"),
184+
pytest.param(Literal["a", "b"], str, id="string-literal-to-str"),
185+
pytest.param(Literal[1, 2], int, id="int-literal-to-int"),
186+
pytest.param(Literal[Enum1.TEST1], Enum1, id="enum-literal-to-enum"),
187+
pytest.param(Literal["a"], str | None, id="string-literal-to-optional-str-pep604"),
188+
pytest.param(Literal["a"], Optional[str], id="string-literal-to-optional-str"),
189+
pytest.param(Literal[1, "a"], Union[int, str], id="mixed-literal-to-typing-union-of-value-types"),
190+
pytest.param(Literal[None], str | None, id="none-literal-to-optional-str"),
191+
pytest.param(Literal[1, "a"], int | str, id="mixed-literal-to-union-of-value-types"),
192+
pytest.param(Literal["a", 1], Literal["a"] | int, id="mixed-literal-to-union-of-literal-and-type"),
193+
pytest.param(list[Literal["a"]], list[str], id="list-of-string-literal-to-list-of-str"),
184194
pytest.param((Optional[str]), (Union[int, str, None]), id="union-to-superset-union-in-other-order"),
185195
pytest.param(str | None, str | int | None, id="union-to-superset-union-in-other-order-pep604"),
186196
pytest.param(
@@ -554,6 +564,9 @@ def test_list_and_iterable_are_not_compatible_strict(sender_type, receiver_type)
554564
pytest.param((Literal["a", "b", "c"]), (Literal["x", "y"]), id="different-literal-of-same-primitive"),
555565
pytest.param((Literal["a", "x"]), (Literal["a", "b", "c"]), id="partially-overlapping-literals"),
556566
pytest.param((Literal[Enum1.TEST1]), (Literal[Enum1.TEST2]), id="different-literal-of-same-enum"),
567+
pytest.param(Literal["a"], int, id="string-literal-to-different-primitive"),
568+
pytest.param(Literal[1, "a"], int, id="mixed-literal-to-type-of-some-values"),
569+
pytest.param(Literal["a", "x"], Literal["a"] | int, id="literal-partially-matching-union-of-literal-and-type"),
557570
pytest.param(
558571
(List[Set[Sequence[str]]]), (List[Set[Sequence[bool]]]), id="nested-sequences-of-different-primitives"
559572
),
@@ -1031,6 +1044,9 @@ def test_types_are_compatible_with_conversion(self):
10311044

10321045
assert _types_are_compatible(sender=str, receiver=List[str]) == (True, ConversionStrategy.WRAP)
10331046
assert _types_are_compatible(sender=str, receiver=list[str]) == (True, ConversionStrategy.WRAP)
1047+
assert _types_are_compatible(sender=Literal["a"], receiver=list[str]) == (True, ConversionStrategy.WRAP)
1048+
assert _types_are_compatible(sender=Literal["a", "b"], receiver=List[str]) == (True, ConversionStrategy.WRAP)
1049+
assert _types_are_compatible(sender=Literal["a"], receiver=list[int]) == (False, None)
10341050

10351051
assert _types_are_compatible(sender=ChatMessage, receiver=List[str]) == (
10361052
True,

0 commit comments

Comments
 (0)