Pipeline stream reader hangs when the handle closes before the producer starts
Describe the bug
If a request creates a Pipeline.stream() handle and then closes it before the producer task first runs, await handle.aclose() returns and handle.result reports cancellation. A consumer of that same handle stays blocked waiting for the next item.
The producer normally sends the end-of-stream marker in the runner coroutine's finally block. A task cancelled before its first step never enters that block.
Expected behavior
The reader should terminate or receive cancellation once the producer is cancelled. A concurrent shutdown should not need to cancel the reader separately.
To reproduce
This uses the public API and a built-in PromptBuilder. The normal completion path is included as a control.
import asyncio
import os
os.environ["HAYSTACK_TELEMETRY_ENABLED"] = "false"
from haystack import Pipeline
from haystack.components.builders import PromptBuilder
async def collect(handle):
return [chunk async for chunk in handle]
async def main():
pipe = Pipeline()
pipe.add_component("prompt", PromptBuilder(template="Hello {{ name }}", required_variables=["name"]))
data = {"prompt": {"name": "reader"}}
control = pipe.stream(data)
await asyncio.wait_for(collect(control), timeout=2)
assert control.result == {"prompt": {"prompt": "Hello reader"}}
handle = pipe.stream(data)
reader = asyncio.create_task(collect(handle))
await handle.aclose()
try:
handle.result
except RuntimeError as exc:
print("Producer:", exc)
done, _ = await asyncio.wait({reader}, timeout=0.25)
print("Reader still waiting after close:", not done)
if not reader.done():
reader.cancel()
await asyncio.gather(reader, return_exceptions=True)
asyncio.run(main())
Observed output:
Producer: Pipeline was cancelled; no result available.
Reader still waiting after close: True
System
Linux x86-64, Python 3.13.7. Reproduced on Haystack 3.5.0 and on main at bbe4efe50c716d6d05a0637980db3b641236e613. The reproduction was prepared and verified locally with AI assistance. I checked the FAQ and searched the existing issues.
Opened #13706 for this.
Root cause is what you described: the end-of-stream marker is queued from the runner's finally, and a task cancelled before its first step never executes the coroutine, so nothing is ever queued.
Reproduced with no await between stream() and aclose():
task cancelled: True | queue size: 0
reader hung after aclose
The marker is now also queued from the task's cancellation (a done callback that only acts when the task was cancelled), so a normal finish still sends it once from the runner. __aiter__ also returns instead of re-raising when the pipeline task is cancelled — awaiting a cancelled task raised CancelledError in the reader, and the cancellation is already visible via result.