diff --git a/docs/configuration.md b/docs/configuration.md index a2b064faf..5b43c8540 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -551,6 +551,12 @@ when its IPv4 and IPv6 addresses are both listed in Only trust `X-Forwarded-For` when untrusted clients cannot connect directly to Paperless-ngx. + This count also controls which address Django REST Framework uses from + `X-Forwarded-For` for the API token throttle. With a count of zero, the + throttle uses the connecting address instead. If + `PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER` is set, the token throttle + uses the connecting address regardless of this count. + Defaults to the number of entries in `PAPERLESS_TRUSTED_PROXIES`. #### [`PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER=`](#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER) {#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER} diff --git a/docs/usage.md b/docs/usage.md index 26ff87930..48417c3c0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -659,7 +659,7 @@ will be aborted and the file will be deleted. "Password Removal" actions attempt to remove password protection from encrypted PDF documents. You can specify: -- One or more passwords to try, separated by commas or new lines +- One or more passwords to try, one per line (commas within a password are supported) - Each password is tried in order until one successfully unlocks the document Password removal never modifies a file in place. Instead, once a working password is found, the diff --git a/pyproject.toml b/pyproject.toml index ef8d098f1..8ba9e5f62 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -71,7 +71,7 @@ dependencies = [ "scikit-learn~=1.9.0", "sentence-transformers>=5.6.1", "setproctitle~=1.3.4", - "sqlite-vec==0.1.9", + "sqlite-vec==0.1.10+paperless.3", "tantivy~=0.26.0", "tika-client[httpx]~=1.0", "torch>=2.13,<2.15", @@ -164,6 +164,12 @@ psycopg-c = [ { url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64' and python_version == '3.14'" }, { url = "https://github.com/paperless-ngx/builder/releases/download/psycopg-trixie-3.3.8/psycopg_c-3.3.8-cp314-cp314-manylinux_2_38_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64' and python_version == '3.14'" }, ] +# Patched sqlite-vec builds +sqlite-vec = [ + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl", marker = "sys_platform == 'linux' and platform_machine == 'x86_64'" }, + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl", marker = "sys_platform == 'linux' and platform_machine == 'aarch64'" }, + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl", marker = "sys_platform == 'darwin' and platform_machine == 'arm64'" }, +] torch = [ { index = "pytorch-cpu" }, ] diff --git a/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.spec.ts b/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.spec.ts index a3c4bd64c..2249998f8 100644 --- a/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.spec.ts +++ b/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.spec.ts @@ -1290,6 +1290,33 @@ describe('WorkflowEditDialogComponent', () => { ]) }) + it('should preserve commas in passwords when saving', () => { + component.object = { + name: 'Workflow with comma in password', + id: 1, + order: 1, + enabled: true, + triggers: [], + actions: [ + { + id: 1, + type: WorkflowActionType.PasswordRemoval, + passwords: ['first,part', 'second'], + }, + ], + } + component.ngOnInit() + + const formActions = component.objectForm.get('actions') as FormArray + expect(formActions.value[0].passwords).toBe('first,part\nsecond') + component.save() + + expect(component.objectForm.get('actions').value[0].passwords).toEqual([ + 'first,part', + 'second', + ]) + }) + it('should parse passwords again when retrying a failed save', () => { component.object = { name: 'Workflow with blank Passwords', diff --git a/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.ts b/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.ts index 6b1b80bd0..66677095b 100644 --- a/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.ts +++ b/src-ui/src/app/components/common/edit-dialog/workflow-edit-dialog/workflow-edit-dialog.component.ts @@ -1332,7 +1332,7 @@ export class WorkflowEditDialogComponent } private parsePasswords(value: string | string[] = ''): string[] { - return (Array.isArray(value) ? value : value.split(/[\n,]+/)) + return (Array.isArray(value) ? value : value.split('\n')) .map((entry) => entry.trim()) .filter((entry) => entry.length > 0) } diff --git a/src/documents/tests/test_api_chat.py b/src/documents/tests/test_api_chat.py index d8521d387..abcc96564 100644 --- a/src/documents/tests/test_api_chat.py +++ b/src/documents/tests/test_api_chat.py @@ -9,12 +9,11 @@ from rest_framework import status from rest_framework.test import APIClient from rest_framework.test import APITestCase -from documents.views import _iterate_in_sync_thread from paperless_testing.factories import UserFactory from paperless_testing.permissions import grant_global if TYPE_CHECKING: - from collections.abc import Generator + from collections.abc import AsyncIterator from django.contrib.auth.models import User from pytest_mock import MockerFixture @@ -59,6 +58,11 @@ class TestChatStreamingViewInputValidation(APITestCase): reaches the Django request the middleware sees. """ chunks = [f"token{i} " for i in range(40)] + + async def answer() -> AsyncIterator[str]: + for chunk in chunks: + yield chunk + with ( mock.patch( "documents.views.AIConfig", @@ -66,7 +70,7 @@ class TestChatStreamingViewInputValidation(APITestCase): ), mock.patch( "paperless_ai.chat.stream_chat_with_documents", - return_value=(c for c in chunks), + return_value=answer(), ), ): resp = self.client.post( @@ -163,74 +167,3 @@ class TestChatStreamingViewUnrestrictedFlag: assert ( mocked_stream_chat.call_args.kwargs["unrestricted"] is expected_unrestricted ) - - -class TestIterateInSyncThread: - @pytest.fixture - def events(self) -> list[str]: - return [] - - @pytest.fixture - def chunks(self, events: list[str]) -> Generator[str, None, None]: - def generate() -> Generator[str, None, None]: - try: - for chunk in ("first", "second"): - events.append(f"produced {chunk}") - yield chunk - finally: - events.append("closed") - - return generate() - - def test_yields_each_chunk_before_pulling_the_next( - self, - chunks: Generator[str, None, None], - events: list[str], - ) -> None: - """ - GIVEN: - - A sync generator wrapped for async iteration - WHEN: - - The wrapper is consumed - THEN: - - Each chunk is delivered before the next one is generated, - rather than the whole generator being drained up front - """ - - async def consume() -> None: - async for chunk in _iterate_in_sync_thread(chunks): - events.append(f"received {chunk}") - - async_to_sync(consume)() - - assert events == [ - "produced first", - "received first", - "produced second", - "received second", - "closed", - ] - - def test_closing_early_closes_the_source_generator( - self, - chunks: Generator[str, None, None], - events: list[str], - ) -> None: - """ - GIVEN: - - A sync generator wrapped for async iteration - WHEN: - - The consumer closes the wrapper after the first chunk, as - happens when the client disconnects - THEN: - - The source generator is closed, so its cleanup runs - """ - - async def consume_one() -> None: - wrapper = _iterate_in_sync_thread(chunks) - await anext(wrapper) - await wrapper.aclose() - - async_to_sync(consume_one)() - - assert events == ["produced first", "closed"] diff --git a/src/documents/views.py b/src/documents/views.py index 0683aab60..74de216c0 100644 --- a/src/documents/views.py +++ b/src/documents/views.py @@ -7,9 +7,7 @@ import tempfile import zipfile from collections import Counter from collections import deque -from collections.abc import AsyncIterator from collections.abc import Callable -from collections.abc import Generator from collections.abc import Sequence from datetime import datetime from datetime import timedelta @@ -31,7 +29,6 @@ from urllib.parse import urlparse import httpx import magic import pathvalidate -from asgiref.sync import sync_to_async from django.conf import settings from django.contrib.auth.models import Group from django.contrib.auth.models import User @@ -2527,24 +2524,6 @@ class DocumentViewSet( ) -async def _iterate_in_sync_thread( - chunks: Generator[str, None, None], -) -> AsyncIterator[str]: - """Serve a blocking sync generator to an ASGI server chunk by chunk. - - Under ASGI, Django drains a sync iterator with ``sync_to_async(list)`` - before sending anything. Pull each chunk in the request's sync thread - instead, where the generator's ORM access belongs. - """ - sentinel = object() # StopIteration can't cross an asyncio Future - next_chunk = sync_to_async(next) - try: - while (chunk := await next_chunk(chunks, sentinel)) is not sentinel: - yield chunk - finally: - await sync_to_async(chunks.close)() - - class ChatStreamingSerializer(serializers.Serializer[dict[str, Any]]): q = serializers.CharField(required=True, max_length=4000) document_id = serializers.IntegerField(required=False, allow_null=True) @@ -2604,13 +2583,11 @@ class ChatStreamingView(GenericAPIView[Any]): ) return StreamingHttpResponse( - _iterate_in_sync_thread( - stream_chat_with_documents( - query_str=question, - documents=documents, - unrestricted=unrestricted, - output_language=output_language, - ), + stream_chat_with_documents( + query_str=question, + documents=documents, + unrestricted=unrestricted, + output_language=output_language, ), content_type="text/event-stream", ) diff --git a/src/locale/en_US/LC_MESSAGES/django.po b/src/locale/en_US/LC_MESSAGES/django.po index b932c7c39..7cf721012 100644 --- a/src/locale/en_US/LC_MESSAGES/django.po +++ b/src/locale/en_US/LC_MESSAGES/django.po @@ -2,7 +2,7 @@ msgid "" msgstr "" "Project-Id-Version: paperless-ngx\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2026-11-23 19:47+0000\n" +"POT-Creation-Date: 2026-11-25 23:54+0000\n" "PO-Revision-Date: 2022-02-17 04:17\n" "Last-Translator: \n" "Language-Team: English\n" @@ -1669,8 +1669,8 @@ msgid "workflow runs" msgstr "" #: documents/serialisers.py:483 documents/serialisers.py:807 -#: documents/serialisers.py:2856 documents/views.py:359 documents/views.py:625 -#: documents/views.py:2783 paperless_mail/serialisers.py:145 +#: documents/serialisers.py:2856 documents/views.py:356 documents/views.py:622 +#: documents/views.py:2760 paperless_mail/serialisers.py:145 msgid "Insufficient permissions." msgstr "" @@ -1710,7 +1710,7 @@ msgstr "" msgid "Duplicate document identifiers are not allowed." msgstr "" -#: documents/serialisers.py:2942 documents/views.py:4864 +#: documents/serialisers.py:2942 documents/views.py:4841 #, python-format msgid "Documents not found: %(ids)s" msgstr "" @@ -1961,40 +1961,40 @@ msgstr "" msgid ", " msgstr "" -#: documents/views.py:314 +#: documents/views.py:311 msgid "Specify only one of text, title_search, query, or more_like_id." msgstr "" -#: documents/views.py:352 documents/views.py:2780 +#: documents/views.py:349 documents/views.py:2757 msgid "Invalid more_like_id" msgstr "" -#: documents/views.py:1684 +#: documents/views.py:1681 msgid "Invalid AI configuration." msgstr "" -#: documents/views.py:1695 +#: documents/views.py:1692 msgid "AI backend request timed out." msgstr "" -#: documents/views.py:1707 +#: documents/views.py:1704 msgid "AI backend rejected the request. Check logs for details." msgstr "" -#: documents/views.py:4880 +#: documents/views.py:4857 #, python-format msgid "Insufficient permissions to share document %(id)s." msgstr "" -#: documents/views.py:4927 +#: documents/views.py:4904 msgid "Bundle is already being processed." msgstr "" -#: documents/views.py:4993 +#: documents/views.py:4970 msgid "The share link bundle is still being prepared. Please try again later." msgstr "" -#: documents/views.py:5007 +#: documents/views.py:4984 msgid "The share link bundle is unavailable." msgstr "" @@ -2286,151 +2286,151 @@ msgstr "" msgid "paperless application settings" msgstr "" -#: paperless/settings/__init__.py:582 +#: paperless/settings/__init__.py:587 msgid "English (US)" msgstr "" -#: paperless/settings/__init__.py:583 +#: paperless/settings/__init__.py:588 msgid "Arabic" msgstr "" -#: paperless/settings/__init__.py:584 +#: paperless/settings/__init__.py:589 msgid "Afrikaans" msgstr "" -#: paperless/settings/__init__.py:585 +#: paperless/settings/__init__.py:590 msgid "Belarusian" msgstr "" -#: paperless/settings/__init__.py:586 +#: paperless/settings/__init__.py:591 msgid "Bulgarian" msgstr "" -#: paperless/settings/__init__.py:587 +#: paperless/settings/__init__.py:592 msgid "Catalan" msgstr "" -#: paperless/settings/__init__.py:588 +#: paperless/settings/__init__.py:593 msgid "Czech" msgstr "" -#: paperless/settings/__init__.py:589 +#: paperless/settings/__init__.py:594 msgid "Danish" msgstr "" -#: paperless/settings/__init__.py:590 +#: paperless/settings/__init__.py:595 msgid "German" msgstr "" -#: paperless/settings/__init__.py:591 +#: paperless/settings/__init__.py:596 msgid "Greek" msgstr "" -#: paperless/settings/__init__.py:592 +#: paperless/settings/__init__.py:597 msgid "English (GB)" msgstr "" -#: paperless/settings/__init__.py:593 +#: paperless/settings/__init__.py:598 msgid "Spanish" msgstr "" -#: paperless/settings/__init__.py:594 +#: paperless/settings/__init__.py:599 msgid "Persian" msgstr "" -#: paperless/settings/__init__.py:595 +#: paperless/settings/__init__.py:600 msgid "Finnish" msgstr "" -#: paperless/settings/__init__.py:596 +#: paperless/settings/__init__.py:601 msgid "French" msgstr "" -#: paperless/settings/__init__.py:597 +#: paperless/settings/__init__.py:602 msgid "Hungarian" msgstr "" -#: paperless/settings/__init__.py:598 +#: paperless/settings/__init__.py:603 msgid "Indonesian" msgstr "" -#: paperless/settings/__init__.py:599 +#: paperless/settings/__init__.py:604 msgid "Italian" msgstr "" -#: paperless/settings/__init__.py:600 +#: paperless/settings/__init__.py:605 msgid "Japanese" msgstr "" -#: paperless/settings/__init__.py:601 +#: paperless/settings/__init__.py:606 msgid "Korean" msgstr "" -#: paperless/settings/__init__.py:602 +#: paperless/settings/__init__.py:607 msgid "Luxembourgish" msgstr "" -#: paperless/settings/__init__.py:603 +#: paperless/settings/__init__.py:608 msgid "Norwegian" msgstr "" -#: paperless/settings/__init__.py:604 +#: paperless/settings/__init__.py:609 msgid "Dutch" msgstr "" -#: paperless/settings/__init__.py:605 +#: paperless/settings/__init__.py:610 msgid "Polish" msgstr "" -#: paperless/settings/__init__.py:606 +#: paperless/settings/__init__.py:611 msgid "Portuguese (Brazil)" msgstr "" -#: paperless/settings/__init__.py:607 +#: paperless/settings/__init__.py:612 msgid "Portuguese" msgstr "" -#: paperless/settings/__init__.py:608 +#: paperless/settings/__init__.py:613 msgid "Romanian" msgstr "" -#: paperless/settings/__init__.py:609 +#: paperless/settings/__init__.py:614 msgid "Russian" msgstr "" -#: paperless/settings/__init__.py:610 +#: paperless/settings/__init__.py:615 msgid "Slovak" msgstr "" -#: paperless/settings/__init__.py:611 +#: paperless/settings/__init__.py:616 msgid "Slovenian" msgstr "" -#: paperless/settings/__init__.py:612 +#: paperless/settings/__init__.py:617 msgid "Serbian" msgstr "" -#: paperless/settings/__init__.py:613 +#: paperless/settings/__init__.py:618 msgid "Swedish" msgstr "" -#: paperless/settings/__init__.py:614 +#: paperless/settings/__init__.py:619 msgid "Turkish" msgstr "" -#: paperless/settings/__init__.py:615 +#: paperless/settings/__init__.py:620 msgid "Ukrainian" msgstr "" -#: paperless/settings/__init__.py:616 +#: paperless/settings/__init__.py:621 msgid "Vietnamese" msgstr "" -#: paperless/settings/__init__.py:617 +#: paperless/settings/__init__.py:622 msgid "Chinese Simplified" msgstr "" -#: paperless/settings/__init__.py:618 +#: paperless/settings/__init__.py:623 msgid "Chinese Traditional" msgstr "" diff --git a/src/paperless/network.py b/src/paperless/network.py index b7006bf5a..018994c62 100644 --- a/src/paperless/network.py +++ b/src/paperless/network.py @@ -1,3 +1,4 @@ +import asyncio import ipaddress import socket from collections.abc import Collection @@ -175,7 +176,9 @@ class PinnedHostAsyncHTTPTransport(httpx.AsyncHTTPTransport): self.allow_internal = allow_internal async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - request = _rewrite_request_to_pinned_ip( + # Resolving the host blocks, so keep it off the event loop + request = await asyncio.to_thread( + _rewrite_request_to_pinned_ip, request, allow_internal=self.allow_internal, ) diff --git a/src/paperless/settings/__init__.py b/src/paperless/settings/__init__.py index 1bd47d697..dca4b3537 100644 --- a/src/paperless/settings/__init__.py +++ b/src/paperless/settings/__init__.py @@ -506,6 +506,11 @@ ALLAUTH_TRUSTED_PROXY_COUNT = _get_allauth_trusted_proxy_count(TRUSTED_PROXIES) ALLAUTH_TRUSTED_CLIENT_IP_HEADER = os.getenv( "PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER", ) +# Do not use client-supplied X-Forwarded-For values for the API token throttle. +# A dedicated allauth header does not imply that X-Forwarded-For is trusted. +REST_FRAMEWORK["NUM_PROXIES"] = ( + 0 if ALLAUTH_TRUSTED_CLIENT_IP_HEADER else ALLAUTH_TRUSTED_PROXY_COUNT +) USE_X_FORWARDED_HOST = get_bool_from_env("PAPERLESS_USE_X_FORWARD_HOST", "false") USE_X_FORWARDED_PORT = get_bool_from_env("PAPERLESS_USE_X_FORWARD_PORT", "false") diff --git a/src/paperless/tests/settings/test_settings.py b/src/paperless/tests/settings/test_settings.py index 232aea266..c7a56df06 100644 --- a/src/paperless/tests/settings/test_settings.py +++ b/src/paperless/tests/settings/test_settings.py @@ -90,6 +90,15 @@ def test_allauth_trusted_proxy_count_defaults_to_trusted_proxies( assert _get_allauth_trusted_proxy_count(["proxy-v4", "proxy-v6"]) == 2 +def test_token_throttle_proxy_count_uses_trusted_proxy_configuration() -> None: + expected = ( + 0 + if paperless_settings.ALLAUTH_TRUSTED_CLIENT_IP_HEADER + else paperless_settings.ALLAUTH_TRUSTED_PROXY_COUNT + ) + assert paperless_settings.REST_FRAMEWORK["NUM_PROXIES"] == expected + + def test_allauth_trusted_proxy_count_can_be_overridden( monkeypatch: pytest.MonkeyPatch, ) -> None: diff --git a/src/paperless/tests/test_api_auth.py b/src/paperless/tests/test_api_auth.py index f0a98dc7e..a2eae1fc6 100644 --- a/src/paperless/tests/test_api_auth.py +++ b/src/paperless/tests/test_api_auth.py @@ -1,14 +1,74 @@ import uuid +from unittest import mock +from django.conf import settings +from django.core.cache.backends.locmem import LocMemCache from django.test import TestCase from django.test import override_settings from django.urls import resolve from django.urls import reverse from rest_framework import status +from rest_framework.throttling import ScopedRateThrottle from paperless_testing.factories import UserFactory +@override_settings( + REST_FRAMEWORK={ + **settings.REST_FRAMEWORK, + "NUM_PROXIES": 0, + }, +) +class TestTokenThrottle(TestCase): + def setUp(self): + super().setUp() + self.enterContext( + mock.patch.object(ScopedRateThrottle, "THROTTLE_RATES", {"login": "5/min"}), + ) + self.enterContext( + mock.patch.object( + ScopedRateThrottle, + "cache", + LocMemCache(uuid.uuid4().hex, {}), + ), + ) + + def _request_token(self, forwarded_for, remote_addr="203.0.113.10"): + return self.client.post( + "/api/token/", + {"username": "unknown", "password": "wrong"}, + HTTP_X_FORWARDED_FOR=forwarded_for, + REMOTE_ADDR=remote_addr, + ) + + def test_untrusted_forwarded_for_cannot_bypass_limit(self): + for attempt in range(5): + response = self._request_token(f"198.51.100.{attempt}") + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + response = self._request_token("198.51.100.99") + self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) + + @override_settings( + REST_FRAMEWORK={ + **settings.REST_FRAMEWORK, + "NUM_PROXIES": 1, + }, + ) + def test_trusted_proxy_uses_client_address(self): + for attempt in range(5): + response = self._request_token( + f"198.51.100.{attempt}, 192.0.2.20", + ) + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + response = self._request_token("198.51.100.99, 192.0.2.20") + self.assertEqual(response.status_code, status.HTTP_429_TOO_MANY_REQUESTS) + + response = self._request_token("192.0.2.21") + self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) + + class TestApiAuthViews(TestCase): def test_api_auth_login_uses_allauth_login_view(self): response = self.client.get(reverse("rest_framework:login")) diff --git a/src/paperless/tests/test_network.py b/src/paperless/tests/test_network.py index 3fca931fe..a88260aa5 100644 --- a/src/paperless/tests/test_network.py +++ b/src/paperless/tests/test_network.py @@ -1,11 +1,19 @@ +from __future__ import annotations + +import asyncio +from typing import TYPE_CHECKING from unittest import mock import httpx import pytest +from paperless.network import PinnedHostAsyncHTTPTransport from paperless.network import PinnedHostHTTPTransport from paperless.network import is_public_ip +if TYPE_CHECKING: + from pytest_mock import MockerFixture + def test_pinned_host_transport_blocks_internal_rebinding(): transport = PinnedHostHTTPTransport(allow_internal=False) @@ -51,6 +59,58 @@ def test_pinned_host_transport_rewrites_to_vetted_ip(): assert response.status_code == 200 +class TestPinnedHostAsyncHTTPTransport: + def test_blocks_internal_rebinding(self, mocker: MockerFixture) -> None: + """ + GIVEN: + - A hostname that resolves to a loopback address + WHEN: + - The async transport sends a request to it + THEN: + - The request is refused as a non-public address + """ + mocker.patch( + "paperless.network.resolve_hostname_ips", + return_value=["127.0.0.1"], + ) + transport = PinnedHostAsyncHTTPTransport(allow_internal=False) + request = httpx.Request("GET", "http://example.com/test") + + with pytest.raises(httpx.ConnectError, match="non-public address"): + asyncio.run(transport.handle_async_request(request)) + + def test_rewrites_to_vetted_ip(self, mocker: MockerFixture) -> None: + """ + GIVEN: + - A hostname that resolves to a public address + WHEN: + - The async transport sends a request to it + THEN: + - The connection goes to that address, keeping the original Host + header and TLS SNI hostname + """ + mocker.patch( + "paperless.network.resolve_hostname_ips", + return_value=["93.184.216.34"], + ) + sent = mocker.patch.object( + httpx.AsyncHTTPTransport, + "handle_async_request", + autospec=True, + side_effect=lambda _self, req: httpx.Response(200, request=req), + ) + transport = PinnedHostAsyncHTTPTransport(allow_internal=False) + request = httpx.Request("GET", "https://example.com:8443/test") + + response = asyncio.run(transport.handle_async_request(request)) + + assert response.status_code == 200 + rewritten = sent.call_args.args[1] + assert str(rewritten.url) == "https://93.184.216.34:8443/test" + assert rewritten.headers["Host"] == "example.com:8443" + assert rewritten.extensions["sni_hostname"] == "example.com" + + @pytest.mark.parametrize( "address", [ diff --git a/src/paperless_ai/chat.py b/src/paperless_ai/chat.py index bf1c720bc..5c5fd119d 100644 --- a/src/paperless_ai/chat.py +++ b/src/paperless_ai/chat.py @@ -1,7 +1,12 @@ import json import logging -import sys +from collections.abc import AsyncIterator +from contextlib import aclosing +from typing import TYPE_CHECKING +from typing import NamedTuple +from asgiref.sync import sync_to_async +from django.db import connections from django.db.models import QuerySet from documents.models import Document @@ -17,6 +22,11 @@ from paperless_ai.prompts.context import ChatQaPromptContext from paperless_ai.prompts.context import ChatRefinePromptContext from paperless_ai.prompts.render import render_prompt +if TYPE_CHECKING: + from llama_index.core.llms import LLM + from llama_index.core.response_synthesizers import BaseSynthesizer + from llama_index.core.schema import NodeWithScore + logger = logging.getLogger("paperless_ai.chat") CHAT_METADATA_DELIMITER = "\n\n__PAPERLESS_CHAT_METADATA__" @@ -103,38 +113,146 @@ def _format_chat_metadata_trailer(references: list[dict[str, int | str]]) -> str ) -def stream_chat_with_documents( +async def stream_chat_with_documents( query_str: str, documents: QuerySet[Document], *, unrestricted: bool = False, output_language: str | None = None, -): +) -> AsyncIterator[str]: try: - yield from _stream_chat_with_documents( - query_str, - documents, - unrestricted=unrestricted, - output_language=output_language, - ) + 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 -def _stream_chat_with_documents( +async def _stream_chat_with_documents( query_str: str, documents: QuerySet[Document], *, unrestricted: bool = False, output_language: str | None = None, -): - if not documents.exists(): +) -> AsyncIterator[str]: + prepared = await sync_to_async(_prepare_chat)( + query_str, + documents, + unrestricted=unrestricted, + output_language=output_language, + ) + if prepared is None: yield CHAT_NO_CONTENT_MESSAGE return + logger.debug("Document chat query: %s", query_str) + try: + first_chunk, chunks, provider_stream = await _start_answer( + prepared.synthesizer, + query_str, + prepared.top_nodes, + ) + except Exception as e: + if not _is_bad_request(e): + raise + logger.warning( + "The LLM server rejected the prompt (%s). Retrying with smaller " + "prompts. Set PAPERLESS_AI_LLM_CONTEXT_SIZE to the context size the " + "LLM server actually uses to avoid the extra request.", + e, + ) + first_chunk, chunks, provider_stream = await _start_answer( + prepared.fallback_synthesizer, + query_str, + prepared.top_nodes, + ) + + # 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(provider_stream), aclosing(chunks): + if first_chunk is not None: + yield first_chunk + async for chunk in chunks: + yield chunk + + if prepared.references: + yield _format_chat_metadata_trailer(prepared.references) + + +class _PreparedChat(NamedTuple): + synthesizer: "BaseSynthesizer" + # Packs the retrieved chunks by the embedding chunk size, as chat did before + # it filled the context window. Used when the server rejects the larger prompt. + fallback_synthesizer: "BaseSynthesizer" + top_nodes: list["NodeWithScore"] + references: list[dict[str, int | str]] + + +def _is_bad_request(exc: Exception) -> bool: + return getattr(exc, "status_code", None) == 400 + + +async def _start_answer( + synthesizer: "BaseSynthesizer", + query_str: str, + top_nodes: list["NodeWithScore"], +) -> tuple[str | None, AsyncIterator[str], AsyncIterator[str]]: + """Begin the answer and pull its first chunk, so a server rejecting the prompt + surfaces here, before anything has been streamed to the user. Also returns the + provider stream, which the caller must close.""" + response_stream = await synthesizer.asynthesize(query_str, top_nodes) + chunks = response_stream.async_response_gen() + return await anext(chunks, None), chunks, response_stream.response_gen + + +def _build_synthesizer( + config: AIConfig, + llm: "LLM", + output_language: str | None, + *, + chunk_size: int, +) -> "BaseSynthesizer": from llama_index.core.prompts import PromptTemplate from llama_index.core.response_synthesizers import get_response_synthesizer + + return get_response_synthesizer( + llm=llm, + prompt_helper=get_rag_prompt_helper( + chunk_size=chunk_size, + context_size=config.llm_context_size, + ), + text_qa_template=PromptTemplate(template=_build_chat_prompt(output_language)), + refine_template=PromptTemplate( + template=_build_refine_prompt(output_language), + ), + streaming=True, + ) + + +def _prepare_chat( + query_str: str, + documents: QuerySet[Document], + *, + unrestricted: bool, + output_language: str | None, +) -> _PreparedChat | None: + """Everything before the answer streams, all of it blocking: ORM queries, + the index read lock and its thread-bound sqlite connection, the query + embedding, and building the LLM client. Returns None when there is no + content to answer from. + """ + if not documents.exists(): + return None + from llama_index.core.retrievers import VectorIndexRetriever config = AIConfig() @@ -150,8 +268,6 @@ def _stream_chat_with_documents( # Hold the shared read lock only while reading the index, so the compaction # swap cannot replace the database file while this connection is open. - # Everything after retrieval works on the nodes already in memory, so a slow - # LLM stream never holds the lock. with read_store() as store: if permitted_ids is not None: filters = _permitted_documents_filter(store, permitted_ids) @@ -179,35 +295,29 @@ def _stream_chat_with_documents( if not top_nodes: logger.warning("No nodes found for the given documents.") - yield CHAT_NO_CONTENT_MESSAGE - return - - client = AIClient() + return None references = _get_document_references(documents, top_nodes) - prompt_template = PromptTemplate(template=_build_chat_prompt(output_language)) - refine_template = PromptTemplate(template=_build_refine_prompt(output_language)) - response_synthesizer = get_response_synthesizer( - llm=client.llm, - prompt_helper=get_rag_prompt_helper( - chunk_size=config.llm_embedding_chunk_size, - context_size=config.llm_context_size, - ), - text_qa_template=prompt_template, - refine_template=refine_template, - streaming=True, + client = AIClient() + # Chunk size limit equal to the context size lets llama_index pack the retrieved + # chunks into as few LLM calls as the window allows, instead of one call per + # embedding-sized chunk. + synthesizer = _build_synthesizer( + config, + client.llm, + output_language, + chunk_size=config.llm_context_size, + ) + fallback_synthesizer = _build_synthesizer( + config, + client.llm, + output_language, + chunk_size=config.llm_embedding_chunk_size, ) - logger.debug("Document chat query: %s", query_str) - # Release the pooled DB connection for the slow streaming LLM response - # so it is not pinned for the whole stream; see paperless_ai.db and - # #12976. - with db_connection_released(): - response_stream = response_synthesizer.synthesize(query_str, top_nodes) - for chunk in response_stream.response_gen: - yield chunk - sys.stdout.flush() + # No ORM access happens while the answer streams, so hand the pooled DB + # connection back now rather than pin it for the whole stream. See #12976. + connections.close_all() - if references: - yield _format_chat_metadata_trailer(references) + return _PreparedChat(synthesizer, fallback_synthesizer, top_nodes, references) diff --git a/src/paperless_ai/tests/test_chat.py b/src/paperless_ai/tests/test_chat.py index 358dec8d2..c2e8e7eaa 100644 --- a/src/paperless_ai/tests/test_chat.py +++ b/src/paperless_ai/tests/test_chat.py @@ -4,10 +4,12 @@ import json from contextlib import contextmanager from typing import TYPE_CHECKING from typing import Any +from unittest.mock import AsyncMock from unittest.mock import MagicMock from unittest.mock import patch import pytest +from asgiref.sync import async_to_sync from django.db.models.signals import post_init from django.utils import timezone from llama_index.core import settings as llama_settings @@ -26,6 +28,7 @@ from paperless_ai.chat import stream_chat_with_documents from paperless_testing.factories import DocumentFactory if TYPE_CHECKING: + from collections.abc import AsyncIterator from collections.abc import Iterator from pathlib import Path @@ -66,6 +69,32 @@ def assert_chat_output( } +def collect(chunks: AsyncIterator[str]) -> list[str]: + """Drain the chat stream from sync test code. Its blocking setup then runs + on the test's own thread, inside the test's DB transaction.""" + + async def drain() -> list[str]: + return [chunk async for chunk in chunks] + + return async_to_sync(drain)() + + +def fake_response_stream(chunks: list[str]) -> MagicMock: + """An AsyncStreamingResponse stand-in yielding ``chunks``.""" + + async def response_gen() -> AsyncIterator[str]: + for chunk in chunks: + yield chunk + + 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: qs = MagicMock() qs.exists.return_value = bool(pks) @@ -170,19 +199,19 @@ def test_stream_chat_with_one_document_retrieval( ), ] - mock_response_stream = MagicMock() - mock_response_stream.response_gen = iter(["chunk1", "chunk2"]) mock_synthesizer = mock_get_response_synthesizer.return_value - mock_synthesizer.synthesize.return_value = mock_response_stream + mock_synthesizer.asynthesize = AsyncMock( + return_value=fake_response_stream(["chunk1", "chunk2"]), + ) with patch( "llama_index.core.retrievers.VectorIndexRetriever", return_value=mock_retriever_instance, ): - output = list(stream_chat_with_documents("What is this?", documents)) + output = collect(stream_chat_with_documents("What is this?", documents)) mock_retriever_instance.retrieve.assert_called_once_with("What is this?") - mock_synthesizer.synthesize.assert_called_once_with( + mock_synthesizer.asynthesize.assert_awaited_once_with( "What is this?", mock_retriever_instance.retrieve.return_value, ) @@ -236,20 +265,19 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non MagicMock(metadata={"document_id": str(doc2.pk), "title": "Document 2"}), ] - mock_response_stream = MagicMock() - mock_response_stream.response_gen = iter(["chunk1", "chunk2"]) - mock_synthesizer = mock_get_response_synthesizer.return_value - mock_synthesizer.synthesize.return_value = mock_response_stream + mock_synthesizer.asynthesize = AsyncMock( + return_value=fake_response_stream(["chunk1", "chunk2"]), + ) with patch( "llama_index.core.retrievers.VectorIndexRetriever", return_value=mock_retriever_instance, ): - output = list(stream_chat_with_documents("What's up?", documents)) + output = collect(stream_chat_with_documents("What's up?", documents)) mock_retriever_instance.retrieve.assert_called_once_with("What's up?") - mock_synthesizer.synthesize.assert_called_once_with( + mock_synthesizer.asynthesize.assert_awaited_once_with( "What's up?", mock_retriever_instance.retrieve.return_value, ) @@ -266,7 +294,9 @@ def test_stream_chat_with_multiple_documents_retrieval(patch_embed_nodes) -> Non def test_stream_chat_empty_document_list() -> None: with patch("paperless_ai.chat.load_or_build_index") as mock_load_index: - output = list(stream_chat_with_documents("Any info?", Document.objects.none())) + output = collect( + stream_chat_with_documents("Any info?", Document.objects.none()), + ) mock_load_index.assert_not_called() assert output == ["Sorry, I couldn't find any content to answer your question."] @@ -286,7 +316,7 @@ def test_stream_chat_no_matching_nodes() -> None: mock_index.vector_store.get_nodes.return_value = [] mock_load_index.return_value = mock_index - output = list( + output = collect( stream_chat_with_documents("Any info?", _fake_documents_queryset([1])), ) @@ -317,7 +347,7 @@ def test_stream_chat_unexpected_failure_returns_generic_error(caplog) -> None: ) mock_retriever_cls.return_value = mock_retriever - output = list( + output = collect( stream_chat_with_documents("Any info?", _fake_documents_queryset([1])), ) @@ -367,7 +397,7 @@ class TestStreamChatRetrieval: ) -> None: doc = DocumentFactory.create(content="hello world") # Nothing indexed for this document yet. - out = list( + out = collect( chat.stream_chat_with_documents( "question?", Document.objects.filter(pk=doc.pk), @@ -390,7 +420,7 @@ class TestStreamChatRetrieval: indexing.llm_index_add_or_update_document(included) indexing.llm_index_add_or_update_document(excluded) - list( + collect( chat.stream_chat_with_documents( "question?", Document.objects.filter(pk=included.pk), @@ -419,7 +449,7 @@ class TestStreamChatRetrieval: document = DocumentFactory.create(content="indexed document content") indexing.llm_index_add_or_update_document(document) - list( + collect( chat.stream_chat_with_documents( "question?", Document.objects.filter(pk=document.pk), @@ -455,7 +485,7 @@ class TestStreamChatRetrieval: deleted_at=timezone.now(), ) - list( + collect( chat.stream_chat_with_documents( "question?", Document.objects.filter(pk=kept.pk), @@ -487,7 +517,7 @@ class TestStreamChatRetrieval: indexing.llm_index_add_or_update_document(doc) permitted = Document.objects.filter(pk__in=[docs[0].pk, docs[1].pk]) - list(chat.stream_chat_with_documents("question?", permitted)) + collect(chat.stream_chat_with_documents("question?", permitted)) metadata_filter = captured_filters[0].filters[0] assert metadata_filter.operator == FilterOperator.NIN @@ -520,16 +550,21 @@ class TestStreamChatRetrieval: synthesizer = mocker.patch( "llama_index.core.response_synthesizers.get_response_synthesizer", ).return_value - synthesizer.synthesize.return_value.response_gen = iter(["chunk"]) + synthesizer.asynthesize = AsyncMock( + return_value=fake_response_stream(["chunk"]), + ) - list( + collect( chat.stream_chat_with_documents( "question?", Document.objects.filter(pk=permitted_doc.pk), ), ) - synthesizer.synthesize.assert_called_once_with("question?", [permitted_node]) + synthesizer.asynthesize.assert_awaited_once_with( + "question?", + [permitted_node], + ) @pytest.mark.django_db def test_get_document_references_only_queries_referenced_documents( @@ -612,9 +647,9 @@ class TestChatReadLock: ] ) - def synthesize(*_args: object) -> object: + def asynthesize(*_args: object) -> MagicMock: events.append("synthesize") - return mocker.MagicMock(response_gen=iter(["chunk"])) + return fake_response_stream(["chunk"]) mocker.patch("paperless_ai.chat.read_store", fake_read_store) mocker.patch("paperless_ai.chat.AIClient") @@ -625,9 +660,9 @@ class TestChatReadLock: ) mocker.patch( "llama_index.core.response_synthesizers.get_response_synthesizer", - ).return_value.synthesize.side_effect = synthesize + ).return_value.asynthesize = AsyncMock(side_effect=asynthesize) - list( + collect( stream_chat_with_documents( "What is this?", Document.objects.filter(pk=document.pk), diff --git a/src/paperless_ai/tests/test_chat_cancellation.py b/src/paperless_ai/tests/test_chat_cancellation.py new file mode 100644 index 000000000..50208d822 --- /dev/null +++ b/src/paperless_ai/tests/test_chat_cancellation.py @@ -0,0 +1,51 @@ +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 _PreparedChat +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=_PreparedChat(synthesizer, 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) diff --git a/src/paperless_ai/tests/test_chat_chunk_merging.py b/src/paperless_ai/tests/test_chat_chunk_merging.py new file mode 100644 index 000000000..c28946b44 --- /dev/null +++ b/src/paperless_ai/tests/test_chat_chunk_merging.py @@ -0,0 +1,282 @@ +"""Chat answers are generated from all retrieved chunks in as few LLM calls as the +configured context window allows, and fall back to the embedding chunk size when the +server rejects the larger prompt.""" + +from __future__ import annotations + +import logging +from types import SimpleNamespace +from typing import TYPE_CHECKING + +import httpx +import openai +import pytest +from asgiref.sync import async_to_sync +from llama_index.core.llms import CompletionResponse +from llama_index.core.llms import MockLLM +from llama_index.core.schema import NodeWithScore +from llama_index.core.schema import TextNode +from llama_index.core.utils import get_tokenizer +from pydantic import PrivateAttr + +from documents.models import Document +from paperless_ai.chat import CHAT_ERROR_MESSAGE +from paperless_ai.chat import stream_chat_with_documents +from paperless_ai.indexing import RAG_NUM_OUTPUT +from paperless_testing.factories import DocumentFactory + +if TYPE_CHECKING: + from collections.abc import Callable + from collections.abc import Iterator + + import pytest_mock + +CHUNK_COUNT = 5 +# About 900 tokens for the estimator llama_index uses, so five of them fit in the +# default 8192 window but not in the default 1024 token chunk size limit. +CHUNK_TEXT = " ".join(["word"] * 900) + + +def _bad_request() -> openai.BadRequestError: + request = httpx.Request("POST", "http://llm.invalid/v1/completions") + return openai.BadRequestError( + "request exceeds the available context size", + response=httpx.Response(400, request=request), + body=None, + ) + + +class ScriptedLLM(MockLLM): + """Records every prompt it is sent and fails on request, the way a real server + does: eagerly for a plain completion, lazily on the first token of a stream.""" + + _prompts: list[str] = PrivateAttr(default_factory=list) + _max_prompt_chars: int | None = PrivateAttr(default=None) + _error: Exception | None = PrivateAttr(default=None) + _tokens_before_error: int = PrivateAttr(default=0) + + def __init__( + self, + *, + max_prompt_chars: int | None = None, + error: Exception | None = None, + tokens_before_error: int = 0, + ) -> None: + super().__init__() + self._max_prompt_chars = max_prompt_chars + self._error = error + self._tokens_before_error = tokens_before_error + + @property + def prompts(self) -> list[str]: + return self._prompts + + def _failure(self, prompt: str) -> Exception | None: + if self._max_prompt_chars is not None and len(prompt) > self._max_prompt_chars: + return _bad_request() + return self._error + + def complete( + self, + prompt: str, + formatted: bool = False, # noqa: FBT001, FBT002 (mirrors the base class) + **kwargs: object, + ) -> CompletionResponse: + self._prompts.append(prompt) + failure = self._failure(prompt) + if failure is not None: + raise failure + return CompletionResponse(text="answer") + + def stream_complete( + self, + prompt: str, + formatted: bool = False, # noqa: FBT001, FBT002 (mirrors the base class) + **kwargs: object, + ) -> Iterator[CompletionResponse]: + self._prompts.append(prompt) + failure = self._failure(prompt) + + def generate() -> Iterator[CompletionResponse]: + for index in range(self._tokens_before_error): + yield CompletionResponse(text="partial", delta=f"partial{index}") + if failure is not None: + raise failure + yield CompletionResponse(text="answer", delta="answer") + + return generate() + + +@pytest.fixture +def run_chat( + mocker: pytest_mock.MockerFixture, +) -> Callable[..., list[str]]: + """Stream one chat question through the real synthesizer, with retrieval, + the index and the AI configuration stubbed.""" + + def run(llm: ScriptedLLM, *, context_size: int = 8192) -> list[str]: + document = DocumentFactory.create(title="Test Document", content="ignored") + nodes = [ + NodeWithScore( + node=TextNode( + text=CHUNK_TEXT, + metadata={"document_id": str(document.pk), "title": "Test"}, + ), + score=0.9, + ) + for _ in range(CHUNK_COUNT) + ] + retriever = mocker.MagicMock() + retriever.retrieve.return_value = nodes + + mocker.patch("paperless_ai.chat.read_store") + mocker.patch("paperless_ai.chat.load_or_build_index") + mocker.patch( + "paperless_ai.chat.AIConfig", + return_value=SimpleNamespace( + llm_context_size=context_size, + llm_embedding_chunk_size=1024, + ), + ) + mocker.patch("paperless_ai.chat.AIClient").return_value.llm = llm + mocker.patch( + "llama_index.core.retrievers.VectorIndexRetriever", + return_value=retriever, + ) + + async def drain() -> list[str]: + return [ + chunk + async for chunk in stream_chat_with_documents( + "What is this?", + Document.objects.filter(pk=document.pk), + ) + ] + + # Driven from sync test code so the blocking setup runs on the test's own + # thread, inside the test's DB transaction. + return async_to_sync(drain)() + + return run + + +@pytest.mark.django_db +class TestChunkMerging: + def test_retrieved_chunks_are_answered_in_a_single_llm_call( + self, + run_chat: Callable[..., list[str]], + ) -> None: + """ + GIVEN five retrieved chunks that together fit the configured context window + WHEN a chat question is answered + THEN the LLM is called once, with every chunk in the prompt + """ + llm = ScriptedLLM() + + output = run_chat(llm, context_size=8192) + + assert CHAT_ERROR_MESSAGE not in output + assert len(llm.prompts) == 1 + assert llm.prompts[0].count(CHUNK_TEXT) == CHUNK_COUNT + + def test_small_context_window_spreads_the_chunks_over_several_calls( + self, + run_chat: Callable[..., list[str]], + ) -> None: + """ + GIVEN a context window too small for all the retrieved chunks at once + WHEN a chat question is answered + THEN the chunks are spread over several LLM calls + AND every prompt leaves room in the window for the answer + """ + context_size = 4096 + tokenize = get_tokenizer() + llm = ScriptedLLM() + + output = run_chat(llm, context_size=context_size) + + assert CHAT_ERROR_MESSAGE not in output + assert len(llm.prompts) > 1 + assert all( + len(tokenize(prompt)) <= context_size - RAG_NUM_OUTPUT + for prompt in llm.prompts + ) + + +@pytest.mark.django_db +class TestContextWindowFallback: + def test_rejected_prompt_is_retried_with_the_embedding_chunk_size( + self, + run_chat: Callable[..., list[str]], + caplog: pytest.LogCaptureFixture, + ) -> None: + """ + GIVEN a server whose real context window is smaller than the configured one + WHEN the merged prompt is rejected with a bad request + THEN the question is answered again from smaller prompts + AND a warning names the context size setting + """ + max_prompt_chars = 12_000 + llm = ScriptedLLM(max_prompt_chars=max_prompt_chars) + + with caplog.at_level(logging.WARNING, logger="paperless_ai.chat"): + output = run_chat(llm, context_size=8192) + + assert CHAT_ERROR_MESSAGE not in output + assert "answer" in output + assert len(llm.prompts[0]) > max_prompt_chars + assert all(len(prompt) <= max_prompt_chars for prompt in llm.prompts[1:]) + assert "PAPERLESS_AI_LLM_CONTEXT_SIZE" in caplog.text + + def test_a_rejection_of_the_retry_yields_the_generic_error( + self, + run_chat: Callable[..., list[str]], + ) -> None: + """ + GIVEN a server that rejects every prompt + WHEN a chat question is answered + THEN the merged prompt is retried exactly once + AND the user gets the generic error message + """ + llm = ScriptedLLM(max_prompt_chars=0) + + output = run_chat(llm) + + assert output == [CHAT_ERROR_MESSAGE] + assert len(llm.prompts) == 2 + + def test_other_errors_are_not_retried( + self, + run_chat: Callable[..., list[str]], + caplog: pytest.LogCaptureFixture, + ) -> None: + """ + GIVEN an LLM that fails with something other than a bad request + WHEN a chat question is answered + THEN there is no retry + AND the user gets the generic error message + """ + llm = ScriptedLLM(error=RuntimeError("provider is down")) + + with caplog.at_level(logging.WARNING, logger="paperless_ai.chat"): + output = run_chat(llm) + + assert output == [CHAT_ERROR_MESSAGE] + assert len(llm.prompts) == 1 + assert "PAPERLESS_AI_LLM_CONTEXT_SIZE" not in caplog.text + + def test_a_failure_after_tokens_were_streamed_is_not_retried( + self, + run_chat: Callable[..., list[str]], + ) -> None: + """ + GIVEN an answer that has started streaming to the user + WHEN the stream then fails with a bad request + THEN the answer is not started over + """ + llm = ScriptedLLM(error=_bad_request(), tokens_before_error=1) + + output = run_chat(llm) + + assert output == ["partial0", CHAT_ERROR_MESSAGE] + assert len(llm.prompts) == 1 diff --git a/uv.lock b/uv.lock index 1b9344a90..a37009b6b 100644 --- a/uv.lock +++ b/uv.lock @@ -2562,7 +2562,9 @@ dependencies = [ { name = "scikit-learn" }, { name = "sentence-transformers" }, { name = "setproctitle" }, - { name = "sqlite-vec" }, + { name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" }, marker = "sys_platform != 'linux'" }, + { name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" }, marker = "platform_machine != 'x86_64' and sys_platform == 'linux'" }, + { name = "sqlite-vec", version = "0.1.10+paperless.3", source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" }, marker = "platform_machine == 'x86_64' and sys_platform == 'linux'" }, { name = "tantivy" }, { name = "tika-client", extra = ["httpx"] }, { name = "torch", version = "2.14.0", source = { registry = "https://download.pytorch.org/whl/cpu" }, marker = "sys_platform != 'linux'" }, @@ -2721,7 +2723,10 @@ requires-dist = [ { name = "scikit-learn", specifier = "~=1.9.0" }, { name = "sentence-transformers", specifier = ">=5.6.1" }, { name = "setproctitle", specifier = "~=1.3.4" }, - { name = "sqlite-vec", specifier = "==0.1.9" }, + { name = "sqlite-vec", marker = "(platform_machine != 'aarch64' and platform_machine != 'arm64' and platform_machine != 'x86_64') or (platform_machine == 'aarch64' and sys_platform == 'darwin') or (platform_machine == 'x86_64' and sys_platform == 'darwin') or (platform_machine == 'arm64' and sys_platform == 'linux') or (sys_platform != 'darwin' and sys_platform != 'linux')", specifier = "==0.1.10+paperless.3" }, + { name = "sqlite-vec", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" }, + { name = "sqlite-vec", marker = "platform_machine == 'aarch64' and sys_platform == 'linux'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" }, + { name = "sqlite-vec", marker = "platform_machine == 'x86_64' and sys_platform == 'linux'", url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" }, { name = "tantivy", specifier = "~=0.26.0" }, { name = "tika-client", extras = ["httpx"], specifier = "~=1.0" }, { name = "torch", specifier = ">=2.13,<2.15", index = "https://download.pytorch.org/whl/cpu" }, @@ -4108,12 +4113,42 @@ asyncio = [ [[package]] name = "sqlite-vec" -version = "0.1.9" -source = { registry = "https://pypi.org/simple" } +version = "0.1.10+paperless.3" +source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl" } +resolution-markers = [ + "python_full_version >= '3.15' and platform_machine == 'arm64' and platform_python_implementation == 'CPython' and sys_platform == 'darwin'", + "python_full_version < '3.15' and platform_machine == 'arm64' and platform_python_implementation == 'CPython' and sys_platform == 'darwin'", +] wheels = [ - { url = "https://files.pythonhosted.org/packages/a4/3d/3677e0cd2f92e5ebc43cd29fbf565b75582bff1ccfa0b8327c7508e1084f/sqlite_vec-0.1.9-py3-none-macosx_11_0_arm64.whl", hash = "sha256:1d52e30513bae4cc9778ddbf6145610434081be4c3afe57cd877893bad9f6b6c", size = 165434, upload-time = "2026-03-31T08:02:32.712Z" }, - { url = "https://files.pythonhosted.org/packages/00/d4/f2b936d3bdc38eadcbd2a87875815db36430fab0363182ba5d12cd8e0b51/sqlite_vec-0.1.9-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:4e921e592f24a5f9a18f590b6ddd530eb637e2d474e3b1972f9bbeb773aa3cb9", size = 160076, upload-time = "2026-03-31T08:02:33.796Z" }, - { url = "https://files.pythonhosted.org/packages/6f/ad/6afd073b0f817b3e03f9e37ad626ae341805891f23c74b5292818f49ac63/sqlite_vec-0.1.9-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux1_x86_64.whl", hash = "sha256:1515727990b49e79bcaf75fdee2ffc7d461f8b66905013231251f1c8938e7786", size = 163388, upload-time = "2026-03-31T08:02:34.888Z" }, + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-macosx_11_0_arm64.whl", hash = "sha256:8cd483975df4e833cfa10d3026bb6a7e71be2cbe3fcb7546952178849d45fa03" }, +] + +[[package]] +name = "sqlite-vec" +version = "0.1.10+paperless.3" +source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl" } +resolution-markers = [ + "python_full_version >= '3.15' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "python_full_version == '3.14.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "python_full_version == '3.12.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "(python_full_version < '3.12' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (python_full_version == '3.13.*' and platform_machine == 'aarch64' and platform_python_implementation == 'CPython' and sys_platform == 'linux')", +] +wheels = [ + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_aarch64.whl", hash = "sha256:71508033874aef98ef1a4006b4e1675be9bd9f866b3444491db480ce870a62c2" }, +] + +[[package]] +name = "sqlite-vec" +version = "0.1.10+paperless.3" +source = { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl" } +resolution-markers = [ + "python_full_version >= '3.15' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "python_full_version == '3.14.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "python_full_version == '3.12.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux'", + "(python_full_version < '3.12' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux') or (python_full_version == '3.13.*' and platform_machine == 'x86_64' and platform_python_implementation == 'CPython' and sys_platform == 'linux')", +] +wheels = [ + { url = "https://github.com/paperless-ngx/builder/releases/download/sqlite-vec-0.1.10%2Bpaperless.3/sqlite_vec-0.1.10%2Bpaperless.3-py3-none-manylinux_2_29_x86_64.whl", hash = "sha256:9c8972c37295498460223ed592e6d8ab8e81d093604e645821fd36ec4ca30090" }, ] [[package]]