Ensures all the resources are closed even in odd cases and not just by gc

This commit is contained in:
stumpylog authored and GitHub committed 2026-11-24 08:43:40 -08:00
1 parent 72e9c01566
commit 29ccfe92fd
3 files changed
+77 -10

No files matched your search

+20 -9
View File
@@ -1,6 +1,7 @@
import json
import logging
from collections.abc import AsyncIterator
from contextlib import aclosing
from typing import TYPE_CHECKING
from asgiref.sync import sync_to_async
@@ -118,13 +119,16 @@ async def stream_chat_with_documents(
output_language: str | None = None,
) -> AsyncIterator[str]:
try:
async for chunk in _stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
):
yield chunk
async with aclosing(
_stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
),
) as chunks:
async for chunk in chunks:
yield chunk
except Exception as e:
logger.exception("Failed to stream document chat response: %s", e)
yield CHAT_ERROR_MESSAGE
@@ -150,8 +154,15 @@ async def _stream_chat_with_documents(
logger.debug("Document chat query: %s", query_str)
response_stream = await response_synthesizer.asynthesize(query_str, top_nodes)
async for chunk in response_stream.async_response_gen():
yield chunk
# llama-index forwards chunks without closing what it reads from, so own
# the provider stream here. Exit order closes the forwarder, then the
# provider stream, so a disconnect releases the LLM request immediately.
async with (
aclosing(response_stream.response_gen),
aclosing(response_stream.async_response_gen()) as chunks,
):
async for chunk in chunks:
yield chunk
if references:
yield _format_chat_metadata_trailer(references)
+7 -1
View File
@@ -86,7 +86,13 @@ def fake_response_stream(chunks: list[str]) -> MagicMock:
for chunk in chunks:
yield chunk
return MagicMock(async_response_gen=response_gen)
async def async_response_gen() -> AsyncIterator[str]:
async for chunk in stream.response_gen:
yield chunk
stream = MagicMock(async_response_gen=async_response_gen)
stream.response_gen = response_gen()
return stream
def _fake_documents_queryset(pks: list[int]) -> MagicMock:
@@ -0,0 +1,50 @@
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import AsyncMock
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from paperless_ai.chat import stream_chat_with_documents
if TYPE_CHECKING:
from collections.abc import AsyncIterator
@pytest.mark.asyncio
async def test_closing_after_a_chunk_closes_the_provider_stream() -> None:
provider_closed = False
async def provider_stream() -> AsyncIterator[str]:
nonlocal provider_closed
try:
yield "first"
yield "second"
finally:
provider_closed = True
provider = provider_stream()
# Like llama-index, forward chunks without closing the stream read from
async def async_response_gen() -> AsyncIterator[str]:
async for chunk in provider:
yield chunk
response_stream = MagicMock(async_response_gen=async_response_gen)
response_stream.response_gen = provider
synthesizer = MagicMock(asynthesize=AsyncMock(return_value=response_stream))
references = [{"id": 1, "title": "Doc"}]
with patch(
"paperless_ai.chat._prepare_chat",
return_value=(synthesizer, [], references),
):
chunks = stream_chat_with_documents("Any info?", MagicMock())
assert await anext(chunks) == "first"
await chunks.aclose()
assert provider_closed
with pytest.raises(StopAsyncIteration):
await anext(chunks)