Compare commits

..
Author SHA1 Message Date
GitHub Actions faa6f09f28 Auto translate strings 2026-11-23 19:47:58 +00:00
Trenton H 098694c6e4 Chore: Remove dead code (#14817)
* Chore: remove unused is_file_ext_supported

Nothing in production called it, only its own test.

* Chore: remove unused Tag.parent_pk

It was an alias of tn_parent_id used only by two test asserts, which now use tn_parent_id directly.

* Chore: remove unused SanityCheckMessages summary properties

has_global_issues was never referenced and total_issue_count was only asserted in tests. The two private issue counters that fed it are removed as well, and the tests assert on has_error and has_warning instead.

* Chore: remove unused DocumentViewSet._has_document_permissions

It duplicated has_document_operation_permissions and had no callers.

* Chore: remove legacy DocumentParser base class

Parsers are resolved through the parser registry and ParserProtocol now, and nothing referenced this class. Its now unused imports are removed too.

* Chore: remove unused ColorField and DeprecatedColors

No serializer used ColorField, and DeprecatedColors was only referenced by it.

* Chore: remove unused RtlLanguageException

A leftover from the old tesseract parser, nothing referenced it.

* Chore: remove unused TASK_WORKERS setting

An alias of CELERY_WORKER_CONCURRENCY that nothing read. PAPERLESS_TASK_WORKERS is unchanged.

* Chore: remove unused GNUPG_HOME setting

Nothing read it. The mail GPG code uses EMAIL_GNUPG_HOME.

* Chore: remove unused test helpers

Drops the shared_samples_dir fixture, MailAttachmentMock, _SHORT_TEXT and _make_extract_text, none of which any test used.
2026-11-23 19:46:34 +00:00
shamoon 0399008fb7 Fix: fix password removal for non-ASCII passwords on older PDFs (#14856) 2026-11-23 10:12:11 -08:00
23 changed files with 633 additions and 1253 deletions

No files matched your search

-6
View File
@@ -153,12 +153,6 @@ def fake_progress_manager(
return FakeProgressManager
@pytest.fixture(scope="session")
def shared_samples_dir() -> Path:
"""Directory of sample files used by more than one app's tests."""
return samples.SHARED_SAMPLES_DIR
@pytest.fixture(scope="session")
def simple_digital_pdf_file() -> Path:
"""One-page PDF with a text layer."""
-4
View File
@@ -138,10 +138,6 @@ class Tag(MatchingModel):
return TagHierarchy(cls.objects.values_list("pk", "tn_parent_id"))
@property
def parent_pk(self) -> int | None:
return self.tn_parent_id
def get_parent(self) -> "Tag | None":
return self.tn_parent
-93
View File
@@ -4,21 +4,13 @@ import logging
import mimetypes
import shutil
import subprocess
import tempfile
from pathlib import Path
from typing import TYPE_CHECKING
from typing import Final
from django.conf import settings
from documents.loggers import LoggingMixin
from documents.utils import copy_file_with_basic_stats
from documents.utils import run_subprocess
from paperless.parsers.registry import get_parser_registry
if TYPE_CHECKING:
import datetime
logger = logging.getLogger("paperless.parsing")
@@ -44,17 +36,6 @@ def get_default_file_extension(mime_type: str) -> str:
return ext if ext else ""
def is_file_ext_supported(ext: str) -> bool:
"""
Returns True if the file extension is supported, False otherwise
TODO: Investigate why this really exists, why not use mimetype
"""
if ext:
return ext.lower() in get_supported_file_extensions()
else:
return False
def get_supported_file_extensions() -> set[str]:
extensions = set()
for parser_class in get_parser_registry().all_parsers():
@@ -276,77 +257,3 @@ def make_thumbnail_from_pdf(in_path: Path, temp_dir: Path, logging_group=None) -
class ParseError(Exception):
pass
class DocumentParser(LoggingMixin):
"""
Subclass this to make your own parser. Have a look at
`paperless_tesseract.parsers` for inspiration.
"""
logging_name = "paperless.parsing"
def __init__(self, logging_group, progress_callback=None) -> None:
super().__init__()
self.renew_logging_group()
self.logging_group = logging_group
self.settings = self.get_settings()
settings.SCRATCH_DIR.mkdir(parents=True, exist_ok=True)
self.tempdir = Path(
tempfile.mkdtemp(prefix="paperless-", dir=settings.SCRATCH_DIR),
)
self.archive_path = None
self.text = None
self.date: datetime.datetime | None = None
self.progress_callback = progress_callback
def progress(self, current_progress, max_progress) -> None:
if self.progress_callback:
self.progress_callback(current_progress, max_progress)
def get_settings(self): # pragma: no cover
"""
A parser must implement this
"""
raise NotImplementedError
def read_file_handle_unicode_errors(self, filepath: Path) -> str:
"""
Helper utility for reading from a file, and handling a problem with its
unicode, falling back to ignoring the error to remove the invalid bytes
"""
try:
text = filepath.read_text(encoding="utf-8")
except UnicodeDecodeError as e:
self.log.warning(f"Unicode error during text reading, continuing: {e}")
text = filepath.read_bytes().decode("utf-8", errors="replace")
return text
def extract_metadata(self, document_path, mime_type):
return []
def get_page_count(self, document_path, mime_type) -> None:
return None
def parse(self, document_path, mime_type, file_name=None):
raise NotImplementedError
def get_archive_path(self):
return self.archive_path
def get_thumbnail(self, document_path, mime_type, file_name=None):
"""
Returns the path to a file we can use as a thumbnail for this document.
"""
raise NotImplementedError
def get_text(self):
return self.text
def get_date(self) -> datetime.datetime | None:
return self.date
def cleanup(self) -> None:
self.log.debug(f"Deleting directory {self.tempdir}")
shutil.rmtree(self.tempdir)
+13 -1
View File
@@ -162,7 +162,19 @@ def decrypt_pdf(src: Path, make_dst: Callable[[], Path], password: str) -> Path:
"""
import pikepdf
with pikepdf.open(src, password=password) as pdf:
try:
pdf = pikepdf.open(src, password=password)
except pikepdf.PasswordError as password_error:
if password.isascii():
raise
# pikepdf opens strings as UTF-8, but older PDFs use PDFDocEncoding.
try:
legacy_password = password.encode("pdfdoc")
except UnicodeEncodeError:
raise password_error from None
pdf = pikepdf.open(src, password=legacy_password)
with pdf:
pdf.remove_unreferenced_resources()
dst = make_dst()
pdf.save(dst)
+5 -22
View File
@@ -49,8 +49,6 @@ class SanityCheckMessages:
self._document_error_pks: set[int] = set()
self._document_warning_pks: set[int] = set()
self._document_info_pks: set[int] = set()
self._document_error_issue_count: int = 0
self._document_warning_issue_count: int = 0
self.has_error: bool = False
self.has_warning: bool = False
self.has_info: bool = False
@@ -76,17 +74,17 @@ class SanityCheckMessages:
def error(self, doc_pk: int | None, message: str) -> None:
self._messages[doc_pk].append({"level": logging.ERROR, "message": message})
self.has_error = True
if doc_pk is not None:
self._document_error_issue_count += 1
if self._add_document_issue(doc_pk, self._document_error_pks):
self.document_error_count += 1
if doc_pk is not None and self._add_document_issue(
doc_pk,
self._document_error_pks,
):
self.document_error_count += 1
def warning(self, doc_pk: int | None, message: str) -> None:
self._messages[doc_pk].append({"level": logging.WARNING, "message": message})
self.has_warning = True
if doc_pk is not None:
self._document_warning_issue_count += 1
if self._add_document_issue(doc_pk, self._document_warning_pks):
self.document_warning_count += 1
else:
@@ -116,21 +114,6 @@ class SanityCheckMessages:
def __getitem__(self, item: int | None) -> list[MessageEntry]:
return self._messages[item]
# -- Summarize Helpers --------------------------------------------------
@property
def has_global_issues(self) -> bool:
return None in self._messages
@property
def total_issue_count(self) -> int:
"""Total number of error and warning messages across all documents and global."""
return (
self._document_error_issue_count
+ self._document_warning_issue_count
+ self.global_warning_count
)
# -- Logging output (used by Celery task path) --------------------------
def log_messages(self) -> None:
-37
View File
@@ -536,43 +536,6 @@ class DocumentTypeSerializer(MatchingModelSerializer, OwnedObjectSerializer):
)
class DeprecatedColors:
COLOURS = (
(1, "#a6cee3"),
(2, "#1f78b4"),
(3, "#b2df8a"),
(4, "#33a02c"),
(5, "#fb9a99"),
(6, "#e31a1c"),
(7, "#fdbf6f"),
(8, "#ff7f00"),
(9, "#cab2d6"),
(10, "#6a3d9a"),
(11, "#b15928"),
(12, "#000000"),
(13, "#cccccc"),
)
@extend_schema_field(
serializers.ChoiceField(
choices=DeprecatedColors.COLOURS,
),
)
class ColorField(serializers.Field):
def to_internal_value(self, data):
for id, color in DeprecatedColors.COLOURS:
if id == data:
return color
raise serializers.ValidationError
def to_representation(self, value):
for id, color in DeprecatedColors.COLOURS:
if color == value:
return id
return 1
class TagSerializer(MatchingModelSerializer, OwnedObjectSerializer):
def get_text_color(self, obj) -> str:
try:
+74 -7
View File
@@ -9,11 +9,12 @@ 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 AsyncIterator
from collections.abc import Generator
from django.contrib.auth.models import User
from pytest_mock import MockerFixture
@@ -58,11 +59,6 @@ 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",
@@ -70,7 +66,7 @@ class TestChatStreamingViewInputValidation(APITestCase):
),
mock.patch(
"paperless_ai.chat.stream_chat_with_documents",
return_value=answer(),
return_value=(c for c in chunks),
),
):
resp = self.client.post(
@@ -167,3 +163,74 @@ 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"]
@@ -305,7 +305,8 @@ class TestExportImport(
self.assertEqual(Permission.objects.count(), num_permission_objects)
messages = check_sanity()
# everything is alright after the test
self.assertEqual(messages.total_issue_count, 0)
self.assertFalse(messages.has_error)
self.assertFalse(messages.has_warning)
def test_exporter_with_filename_format(self) -> None:
shutil.rmtree(Path(self.dirs.media_dir) / "documents")
-6
View File
@@ -14,7 +14,6 @@ from documents.parsers import encode_thumbnail_webp
from documents.parsers import get_default_file_extension
from documents.parsers import get_default_thumbnail
from documents.parsers import get_supported_file_extensions
from documents.parsers import is_file_ext_supported
from documents.parsers import make_thumbnail_from_pdf
from documents.parsers import rasterize_pdf_page_to_png
from paperless.parsers.registry import get_parser_registry
@@ -132,11 +131,6 @@ class TestParserAvailability:
# Test invalid mimetype returns no extension
assert get_default_file_extension("aasdasd/dgfgf") == ""
def test_file_extension_support(self) -> None:
assert is_file_ext_supported(".pdf")
assert not is_file_ext_supported(".hsdfh")
assert not is_file_ext_supported("")
class TestComputeThumbnailDpi:
@pytest.mark.parametrize(
+38 -1
View File
@@ -437,9 +437,46 @@ class TestDecrypt:
assert result == dst
assert pdf_ops.needs_decrypt(dst) is False
@pytest.mark.parametrize(
"encryption",
[
pytest.param(
pikepdf.Encryption(
owner="owner",
user="grün",
R=3,
aes=False,
metadata=False,
),
id="legacy-rc4",
),
pytest.param(
pikepdf.Encryption(owner="owner", user="grün", R=6),
id="modern-aes",
),
],
)
def test_decrypt_with_non_ascii_password(
self,
tmp_path: Path,
encryption: pikepdf.Encryption,
source_fingerprints: list[str],
) -> None:
src = tmp_path / "encrypted.pdf"
dst = tmp_path / "out.pdf"
with pikepdf.open(THREE_PAGES) as pdf:
pdf.save(src, encryption=encryption)
assert pdf_ops.decrypt_pdf(src, constant(dst), encryption.user) == dst
assert pdf_ops.needs_decrypt(dst) is False
assert fingerprints(dst) == source_fingerprints
assert pdf_ops.needs_decrypt(src) is True
@pytest.mark.parametrize("password", ["wrong", "fälsch", "間違い"])
def test_wrong_password_raises_and_never_requests_a_destination(
self,
tmp_path: Path,
password: str,
) -> None:
"""
GIVEN:
@@ -457,7 +494,7 @@ class TestDecrypt:
return requested[-1]
with pytest.raises(pikepdf.PasswordError):
pdf_ops.decrypt_pdf(ENCRYPTED, make_dst, "wrong")
pdf_ops.decrypt_pdf(ENCRYPTED, make_dst, password)
assert requested == []
-3
View File
@@ -39,7 +39,6 @@ class TestSanityCheckMessages:
assert messages.document_warning_count == 1
assert messages.document_info_count == 1
assert messages.global_warning_count == 1
assert messages.total_issue_count == 5
@pytest.mark.django_db
@@ -51,7 +50,6 @@ class TestCheckSanityNoDocuments:
messages = check_sanity()
assert not messages.has_error
assert not messages.has_warning
assert messages.total_issue_count == 0
@pytest.mark.usefixtures("paperless_dirs")
def test_no_issues_logs_clean(self, caplog: pytest.LogCaptureFixture) -> None:
@@ -67,7 +65,6 @@ class TestCheckSanityHealthyDocument:
messages = check_sanity()
assert not messages.has_error
assert not messages.has_warning
assert messages.total_issue_count == 0
@pytest.mark.django_db
+2 -2
View File
@@ -362,7 +362,7 @@ class TestTagHierarchy(DirectoriesMixin, APITestCase):
x = Tag.objects.create(name="X2")
y = Tag.objects.create(name="Y2", tn_parent=x)
assert y.parent_pk == x.pk
assert y.tn_parent_id == x.pk
# Moving X under D would make deepest node Y exceed depth 5 -> reject
resp_fail = self.client.patch(
@@ -383,7 +383,7 @@ class TestTagHierarchy(DirectoriesMixin, APITestCase):
)
assert resp_ok.status_code in (200, 202)
x.refresh_from_db()
assert x.parent_pk == c.id
assert x.tn_parent_id == c.id
def test_is_root_filter_returns_only_root_tags(self) -> None:
other_root = Tag.objects.create(name="Other parent")
+28 -99
View File
@@ -7,7 +7,9 @@ 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 datetime import datetime
from datetime import timedelta
from http import HTTPStatus
@@ -27,6 +29,7 @@ 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
@@ -2416,6 +2419,24 @@ 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)
@@ -2475,11 +2496,13 @@ class ChatStreamingView(GenericAPIView[Any]):
)
return StreamingHttpResponse(
stream_chat_with_documents(
query_str=question,
documents=documents,
unrestricted=unrestricted,
output_language=output_language,
_iterate_in_sync_thread(
stream_chat_with_documents(
query_str=question,
documents=documents,
unrestricted=unrestricted,
output_language=output_language,
),
),
content_type="text/event-stream",
)
@@ -3000,100 +3023,6 @@ class DocumentOperationPermissionMixin(PassUserMixin, DocumentSelectionMixin):
)
return Response({"result": "OK", "task_id": task.id})
def _has_document_permissions(
self,
*,
user: User,
documents: list[int],
method,
parameters: dict[str, Any],
) -> bool:
if user.is_superuser:
return True
root_docs = {
get_root_document(doc)
for doc in Document.objects.select_related(
"owner",
"root_document__owner",
).filter(pk__in=documents)
}
user_is_owner_of_all_documents = all(
(doc.owner == user or doc.owner is None) for doc in root_docs
)
# check global and object permissions for all documents
has_perms = (
user.has_perm(
"documents.change_document",
)
and not Document.global_objects.filter(pk__in=documents)
.exclude(pk__in=permitted_document_ids(user, perm="change_document"))
.exists()
)
# check ownership for methods that change original document
if (
(
has_perms
and method
in [
bulk_edit.set_permissions,
bulk_edit.delete,
bulk_edit.rotate,
bulk_edit.delete_pages,
bulk_edit.edit_pdf,
bulk_edit.merge_as_versions,
bulk_edit.remove_password,
bulk_edit.run_workflow,
]
)
or (
method in [bulk_edit.merge, bulk_edit.split]
and parameters.get("delete_originals")
)
or (method == bulk_edit.edit_pdf and parameters.get("update_document"))
):
has_perms = has_perms and user_is_owner_of_all_documents
# check global add permissions for methods that create documents
if (
has_perms
and (
method in [bulk_edit.split, bulk_edit.merge]
or (
method in [bulk_edit.edit_pdf, bulk_edit.remove_password]
and not parameters.get("update_document")
)
)
and not user.has_perm("documents.add_document")
):
has_perms = False
# check global delete permissions for methods that delete documents
if (
has_perms
and (
method == bulk_edit.delete
# Sources stop being documents of their own, and removing one
# again afterwards needs delete_document
or method == bulk_edit.merge_as_versions
or (
method in [bulk_edit.merge, bulk_edit.split]
and parameters.get("delete_originals")
)
or (
method in [bulk_edit.edit_pdf, bulk_edit.remove_password]
and parameters.get("delete_original")
and not parameters.get("update_document")
)
)
and not user.has_perm("documents.delete_document")
):
has_perms = False
return has_perms
def _execute_document_action(
self,
*,
File diff suppressed because it is too large. Load diff
+1 -4
View File
@@ -1,4 +1,3 @@
import asyncio
import ipaddress
import socket
from collections.abc import Collection
@@ -176,9 +175,7 @@ class PinnedHostAsyncHTTPTransport(httpx.AsyncHTTPTransport):
self.allow_internal = allow_internal
async def handle_async_request(self, request: httpx.Request) -> httpx.Response:
# Resolving the host blocks, so keep it off the event loop
request = await asyncio.to_thread(
_rewrite_request_to_pinned_ip,
request = _rewrite_request_to_pinned_ip(
request,
allow_internal=self.allow_internal,
)
-4
View File
@@ -65,10 +65,6 @@ class NoTextFoundException(Exception):
pass
class RtlLanguageException(Exception):
pass
class RasterisedDocumentParser:
"""
This parser uses Tesseract to try and get some text out of a rasterised
-4
View File
@@ -714,7 +714,6 @@ CELERY_TIMEZONE = TIME_ZONE
CELERY_WORKER_HIJACK_ROOT_LOGGER = False
CELERY_WORKER_CONCURRENCY: Final[int] = get_int_from_env("PAPERLESS_TASK_WORKERS", 1)
TASK_WORKERS = CELERY_WORKER_CONCURRENCY
CELERY_WORKER_MAX_TASKS_PER_CHILD = 1
CELERY_WORKER_SEND_TASK_EVENTS = True
CELERY_TASK_SEND_SENT_EVENT = True
@@ -996,9 +995,6 @@ MAX_IMAGE_PIXELS: Final[int | None] = get_int_from_env(
"PAPERLESS_MAX_IMAGE_PIXELS",
)
# GNUPG needs a home directory for some reason
GNUPG_HOME = os.getenv("HOME", "/tmp")
# Fallback layout for .eml consumption
EMAIL_PARSE_DEFAULT_LAYOUT = get_int_from_env(
"PAPERLESS_EMAIL_PARSE_DEFAULT_LAYOUT",
@@ -37,13 +37,6 @@ def extract_text(pdf_path: Path) -> str:
return tmp.read()
class MailAttachmentMock:
def __init__(self, payload: bytes, content_id: str) -> None:
self.payload = payload
self.content_id = content_id
self.content_type = "image/png"
@pytest.mark.live
@pytest.mark.nginx
@pytest.mark.skipif(
@@ -29,16 +29,6 @@ if TYPE_CHECKING:
# ---------------------------------------------------------------------------
_LONG_TEXT = "This is a test document with enough text. " * 5 # >50 chars
_SHORT_TEXT = "Hi." # <50 chars
def _make_extract_text(text: str | None):
"""Return a side_effect function for ``extract_text`` that returns *text*."""
def _extract(sidecar_file, pdf_file):
return text
return _extract
# ---------------------------------------------------------------------------
-60
View File
@@ -1,19 +1,11 @@
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)
@@ -59,58 +51,6 @@ 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",
[
+36 -137
View File
@@ -1,11 +1,7 @@
import json
import logging
from collections.abc import AsyncIterator
from typing import TYPE_CHECKING
from typing import NamedTuple
import sys
from asgiref.sync import sync_to_async
from django.db import connections
from django.db.models import QuerySet
from documents.models import Document
@@ -21,11 +17,6 @@ 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__"
@@ -112,138 +103,38 @@ def _format_chat_metadata_trailer(references: list[dict[str, int | str]]) -> str
)
async def stream_chat_with_documents(
def stream_chat_with_documents(
query_str: str,
documents: QuerySet[Document],
*,
unrestricted: bool = False,
output_language: str | None = None,
) -> AsyncIterator[str]:
):
try:
async for chunk in _stream_chat_with_documents(
yield from _stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
):
yield chunk
)
except Exception as e:
logger.exception("Failed to stream document chat response: %s", e)
yield CHAT_ERROR_MESSAGE
async def _stream_chat_with_documents(
def _stream_chat_with_documents(
query_str: str,
documents: QuerySet[Document],
*,
unrestricted: bool = False,
output_language: str | None = None,
) -> AsyncIterator[str]:
prepared = await sync_to_async(_prepare_chat)(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
)
if prepared is None:
):
if not documents.exists():
yield CHAT_NO_CONTENT_MESSAGE
return
logger.debug("Document chat query: %s", query_str)
try:
first_chunk, chunks = 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 = await _start_answer(
prepared.fallback_synthesizer,
query_str,
prepared.top_nodes,
)
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]]:
"""Begin the answer and pull its first chunk, so a server rejecting the prompt
surfaces here, before anything has been streamed to the user."""
response_stream = await synthesizer.asynthesize(query_str, top_nodes)
chunks = response_stream.async_response_gen()
return await anext(chunks, None), chunks
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()
@@ -259,6 +150,8 @@ def _prepare_chat(
# 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)
@@ -286,29 +179,35 @@ def _prepare_chat(
if not top_nodes:
logger.warning("No nodes found for the given documents.")
return None
yield CHAT_NO_CONTENT_MESSAGE
return
client = AIClient()
references = _get_document_references(documents, top_nodes)
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,
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,
)
# 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()
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()
return _PreparedChat(synthesizer, fallback_synthesizer, top_nodes, references)
if references:
yield _format_chat_metadata_trailer(references)
+26 -55
View File
@@ -4,12 +4,10 @@ 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
@@ -28,7 +26,6 @@ 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
@@ -69,26 +66,6 @@ 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
return MagicMock(async_response_gen=response_gen)
def _fake_documents_queryset(pks: list[int]) -> MagicMock:
qs = MagicMock()
qs.exists.return_value = bool(pks)
@@ -193,19 +170,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.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk1", "chunk2"]),
)
mock_synthesizer.synthesize.return_value = mock_response_stream
with patch(
"llama_index.core.retrievers.VectorIndexRetriever",
return_value=mock_retriever_instance,
):
output = collect(stream_chat_with_documents("What is this?", documents))
output = list(stream_chat_with_documents("What is this?", documents))
mock_retriever_instance.retrieve.assert_called_once_with("What is this?")
mock_synthesizer.asynthesize.assert_awaited_once_with(
mock_synthesizer.synthesize.assert_called_once_with(
"What is this?",
mock_retriever_instance.retrieve.return_value,
)
@@ -259,19 +236,20 @@ 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.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk1", "chunk2"]),
)
mock_synthesizer.synthesize.return_value = mock_response_stream
with patch(
"llama_index.core.retrievers.VectorIndexRetriever",
return_value=mock_retriever_instance,
):
output = collect(stream_chat_with_documents("What's up?", documents))
output = list(stream_chat_with_documents("What's up?", documents))
mock_retriever_instance.retrieve.assert_called_once_with("What's up?")
mock_synthesizer.asynthesize.assert_awaited_once_with(
mock_synthesizer.synthesize.assert_called_once_with(
"What's up?",
mock_retriever_instance.retrieve.return_value,
)
@@ -288,9 +266,7 @@ 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 = collect(
stream_chat_with_documents("Any info?", Document.objects.none()),
)
output = list(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."]
@@ -310,7 +286,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 = collect(
output = list(
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
)
@@ -341,7 +317,7 @@ def test_stream_chat_unexpected_failure_returns_generic_error(caplog) -> None:
)
mock_retriever_cls.return_value = mock_retriever
output = collect(
output = list(
stream_chat_with_documents("Any info?", _fake_documents_queryset([1])),
)
@@ -391,7 +367,7 @@ class TestStreamChatRetrieval:
) -> None:
doc = DocumentFactory.create(content="hello world")
# Nothing indexed for this document yet.
out = collect(
out = list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=doc.pk),
@@ -414,7 +390,7 @@ class TestStreamChatRetrieval:
indexing.llm_index_add_or_update_document(included)
indexing.llm_index_add_or_update_document(excluded)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=included.pk),
@@ -443,7 +419,7 @@ class TestStreamChatRetrieval:
document = DocumentFactory.create(content="indexed document content")
indexing.llm_index_add_or_update_document(document)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=document.pk),
@@ -479,7 +455,7 @@ class TestStreamChatRetrieval:
deleted_at=timezone.now(),
)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=kept.pk),
@@ -511,7 +487,7 @@ class TestStreamChatRetrieval:
indexing.llm_index_add_or_update_document(doc)
permitted = Document.objects.filter(pk__in=[docs[0].pk, docs[1].pk])
collect(chat.stream_chat_with_documents("question?", permitted))
list(chat.stream_chat_with_documents("question?", permitted))
metadata_filter = captured_filters[0].filters[0]
assert metadata_filter.operator == FilterOperator.NIN
@@ -544,21 +520,16 @@ class TestStreamChatRetrieval:
synthesizer = mocker.patch(
"llama_index.core.response_synthesizers.get_response_synthesizer",
).return_value
synthesizer.asynthesize = AsyncMock(
return_value=fake_response_stream(["chunk"]),
)
synthesizer.synthesize.return_value.response_gen = iter(["chunk"])
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=permitted_doc.pk),
),
)
synthesizer.asynthesize.assert_awaited_once_with(
"question?",
[permitted_node],
)
synthesizer.synthesize.assert_called_once_with("question?", [permitted_node])
@pytest.mark.django_db
def test_get_document_references_only_queries_referenced_documents(
@@ -641,9 +612,9 @@ class TestChatReadLock:
]
)
def asynthesize(*_args: object) -> MagicMock:
def synthesize(*_args: object) -> object:
events.append("synthesize")
return fake_response_stream(["chunk"])
return mocker.MagicMock(response_gen=iter(["chunk"]))
mocker.patch("paperless_ai.chat.read_store", fake_read_store)
mocker.patch("paperless_ai.chat.AIClient")
@@ -654,9 +625,9 @@ class TestChatReadLock:
)
mocker.patch(
"llama_index.core.response_synthesizers.get_response_synthesizer",
).return_value.asynthesize = AsyncMock(side_effect=asynthesize)
).return_value.synthesize.side_effect = synthesize
collect(
list(
stream_chat_with_documents(
"What is this?",
Document.objects.filter(pk=document.pk),
@@ -1,282 +0,0 @@
"""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