Compare commits

..
Author SHA1 Message Date
shamoon 24961fb9e5 Merge remote-tracking branch 'origin/dev' into feature/child-processing-tasks
# Conflicts:
#	docs/api.md
#	src-ui/src/app/components/document-list/bulk-editor/bulk-editor.component.spec.ts
#	src-ui/src/app/components/document-list/bulk-editor/bulk-editor.component.ts
#	src/documents/bulk_edit.py
#	src/documents/bulk_operations.py
#	src/documents/serialisers.py
#	src/documents/tests/test_bulk_edit.py
#	src/documents/tests/test_bulk_operations.py
#	src/documents/tests/test_merge_documents_as_versions.py
#	src/documents/views.py
2026-11-23 22:39:24 -08:00
shamoon 3508877a33 Update api.md 2026-11-14 12:31:08 -08:00
shamoon fea012d5c0 Apply to the rest of the operations 2026-11-14 12:30:48 -08:00
shamoon e2aa45da4e Fix a couple dispatched renames 2026-11-14 12:21:25 -08:00
shamoon 5ad0773446 Buld this parent task into the model, dispatched. Hook up for reprocess 2026-11-14 12:16:02 -08:00
shamoon 13202f52ad Raise reprocess errors 2026-11-14 11:54:40 -08:00
shamoon 9a9d4284d7 Couple more things for sonar 2026-11-14 11:51:42 -08:00
shamoon 6043dd1c81 Be more careful about how we handle errors wrt open docs 2026-11-14 11:51:42 -08:00
shamoon 058e27e3ef Reprot more accurate notification for tasks with follow-ups 2026-11-14 11:51:42 -08:00
shamoon 6f5a192967 Propagate these errors now so they make it to the task 2026-11-14 11:51:41 -08:00
shamoon bb775a16c1 Move the merge as version heirarchy checks to the bulk edit method 2026-11-14 11:51:41 -08:00
shamoon 6d26d3f5ca Sonar loves a readonly class member 2026-11-14 10:53:49 -08:00
shamoon 2131feac73 Random test cleanup stuff 2026-11-14 09:36:10 -08:00
shamoon e2705768b4 Make the popups more helpful 2026-11-14 09:34:01 -08:00
shamoon ce3c4e0855 Yay make the task list useful 2026-11-14 09:34:01 -08:00
shamoon 3a241e51d9 Better info for bulk tasks 2026-11-14 09:34:01 -08:00
shamoon 020a2c8fc0 Dont show view task on success popups 2026-11-14 09:34:00 -08:00
shamoon b533bfe4b5 We need a tasks notification service 2026-11-14 09:34:00 -08:00
shamoon 813dfe487f We have to make this generic-er 2026-11-14 09:34:00 -08:00
shamoon 557afa6454 Move doc detail actions over 2026-11-14 09:33:59 -08:00
shamoon c72473f7bc Fix delete and undo 2026-11-14 09:33:59 -08:00
shamoon 7d79b544ae use the queued operation pathway across teh frontend 2026-11-14 09:33:58 -08:00
shamoon a9fef2b931 Update the api docs 2026-11-14 09:33:58 -08:00
shamoon adbd7561d4 Tests for the actions 2026-11-14 09:33:58 -08:00
shamoon 9f694cdd2d queue the dedicated document actions 2026-11-14 09:33:57 -08:00
shamoon 7d78716069 and add some 2026-11-14 09:33:57 -08:00
shamoon 9523d158a8 Fix the old tests 2026-11-14 09:33:57 -08:00
shamoon 91316df9b7 Move the other bulk edit actions through the new taks tracking route 2026-11-14 09:33:56 -08:00
shamoon 7e67013c42 Ensure from_webui 2026-11-14 09:33:56 -08:00
shamoon 2a0c1249fa Raise error on trash deletion so it can be tracked 2026-11-14 09:33:56 -08:00
33 changed files with 1307 additions and 962 deletions

No files matched your search

+5 -5
View File
@@ -287,12 +287,12 @@ The API supports various bulk-editing operations which are executed asynchronous
Document bulk operations, including the dedicated document action endpoints, return
`{"result":"OK","task_id":"…"}` when queued. Use `/api/tasks/?task_id={uuid}`
to check the task outcome. Actions that create or reprocess files may start further
consumption or reprocessing tasks and completion of the bulk task means those tasks
were scheduled, not that their file processing has finished.
to check the outcome, including follow-up processing, deletion, or recovery.
Failed operations may leave partial changes applied. For operations with child tasks,
`result_data` includes `succeeded_count` and `failed_count` (task counts). Merges
report skipped inputs in `failed_document_ids`.
For bulk operations on documents, use the endpoint `/api/documents/bulk_edit/` which accepts
a json payload of the format:
The `/api/documents/bulk_edit/` endpoint accepts:
```json
{
-6
View File
@@ -551,12 +551,6 @@ 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=<header-name>`](#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER) {#PAPERLESS_ALLAUTH_TRUSTED_CLIENT_IP_HEADER}
+1 -1
View File
@@ -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, one per line (commas within a password are supported)
- One or more passwords to try, separated by commas or new lines
- 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
+1 -7
View File
@@ -71,7 +71,7 @@ dependencies = [
"scikit-learn~=1.9.0",
"sentence-transformers>=5.6.1",
"setproctitle~=1.3.4",
"sqlite-vec==0.1.10+paperless.3",
"sqlite-vec==0.1.9",
"tantivy~=0.26.0",
"tika-client[httpx]~=1.0",
"torch>=2.13,<2.15",
@@ -164,12 +164,6 @@ 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" },
]
@@ -1290,33 +1290,6 @@ 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',
@@ -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)
}
+117 -45
View File
@@ -39,6 +39,8 @@ from documents.models import Tag
from documents.permissions import PermissionsSpec
from documents.permissions import set_permissions_for_objects
from documents.plugins.helpers import DocumentsStatusManager
from documents.task_tracking import queue_consumption
from documents.task_tracking import queue_processing_tasks
from documents.tasks import bulk_update_documents
from documents.tasks import consume_file
from documents.tasks import remove_document_from_index
@@ -432,7 +434,12 @@ def delete(doc_ids: list[int]) -> Literal["OK"]:
return "OK"
def reprocess(doc_ids: list[int], *, remote_ocr: bool = False) -> Literal["OK"]:
def reprocess(
doc_ids: list[int],
*,
remote_ocr: bool = False,
parent_task_id: str | None = None,
) -> Literal["OK"]:
"""
Re-run parsing for the given documents.
@@ -457,6 +464,16 @@ def reprocess(doc_ids: list[int], *, remote_ocr: bool = False) -> Literal["OK"]:
.values_list("source_id", flat=True)
.distinct()
)
if parent_task_id is not None:
from documents.task_tracking import queue_reprocessing_tasks
queue_reprocessing_tasks(
parent_task_id,
list(source_ids),
remote_ocr=remote_ocr,
)
return "OK"
for source_id in source_ids:
update_document_content_maybe_archive_file.apply_async(
kwargs={"document_id": source_id, "remote_ocr": remote_ocr},
@@ -521,6 +538,7 @@ def rotate(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
parent_task_id: str | None = None,
) -> Literal["OK"]:
logger.info(
f"Attempting to rotate {len(doc_ids)} documents by {degrees} degrees.",
@@ -559,16 +577,15 @@ def rotate(
if user is not None:
overrides.actor_id = user.id
consume_file.apply_async(
kwargs={
"input_doc": ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
"overrides": overrides,
},
headers={"trigger_source": trigger_source},
queue_consumption(
input_doc=ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
overrides=overrides,
trigger_source=trigger_source,
parent_task_id=parent_task_id,
)
logger.info(
f"Queued new rotated version for document {pair.root_doc.id} by {degrees} degrees",
@@ -594,13 +611,15 @@ def merge(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
) -> Literal["OK"]:
parent_task_id: str | None = None,
) -> Literal["OK"] | dict:
logger.info(
f"Attempting to merge {len(doc_ids)} documents into a single document.",
)
qs = Document.objects.select_related("root_document").filter(id__in=doc_ids)
docs_by_id = {doc.id: doc for doc in qs}
affected_docs: list[int] = []
failed_ids: list[int] = []
handoff_asn: int | None = None
with pdf_ops.PdfMerger() as merger:
# use doc_ids to preserve order
@@ -626,11 +645,14 @@ def merge(
if handoff_asn is None and doc.archive_serial_number is not None:
handoff_asn = doc.archive_serial_number
except Exception as e:
failed_ids.append(doc.id)
logger.exception(
f"Error merging document {doc.id}, it will not be included in the merge: {e}",
)
if len(affected_docs) == 0:
logger.warning("No documents were merged")
if parent_task_id is not None:
raise ValueError("None of the selected documents could be merged.")
return "OK"
filepath = (
@@ -673,6 +695,23 @@ def merge(
overrides=overrides,
).set(headers={"trigger_source": trigger_source})
if parent_task_id is not None:
backup = (
release_archive_serial_numbers(affected_docs) if delete_originals else {}
)
queue_processing_tasks(
parent_task_id,
[consume_task],
delete_ids=affected_docs if delete_originals else None,
asn_backup=backup,
)
if failed_ids:
return {
"failed_document_ids": failed_ids,
"error_message": f"Documents {failed_ids} were excluded from the merge.",
}
return "OK"
if delete_originals:
backup = release_archive_serial_numbers(affected_docs)
logger.info(
@@ -826,6 +865,7 @@ def split(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
parent_task_id: str | None = None,
) -> Literal["OK"]:
logger.info(
f"Attempting to split document {doc_ids[0]} into {len(pages)} documents",
@@ -869,7 +909,17 @@ def split(
).set(headers={"trigger_source": trigger_source}),
)
if delete_originals:
if parent_task_id is not None:
backup = (
release_archive_serial_numbers([doc.id]) if delete_originals else {}
)
queue_processing_tasks(
parent_task_id,
consume_tasks,
delete_ids=[doc.id] if delete_originals else None,
asn_backup=backup,
)
elif delete_originals:
backup = release_archive_serial_numbers([doc.id])
logger.info(
"Queueing removal of original document after consumption of the split documents",
@@ -901,6 +951,7 @@ def delete_pages(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
parent_task_id: str | None = None,
) -> Literal["OK"]:
logger.info(
f"Attempting to delete pages {pages} from {len(doc_ids)} documents",
@@ -919,16 +970,15 @@ def delete_pages(
overrides = DocumentMetadataOverrides().from_document(pair.root_doc)
if user is not None:
overrides.actor_id = user.id
consume_file.apply_async(
kwargs={
"input_doc": ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
"overrides": overrides,
},
headers={"trigger_source": trigger_source},
queue_consumption(
input_doc=ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
overrides=overrides,
trigger_source=trigger_source,
parent_task_id=parent_task_id,
)
logger.info(
f"Queued new version for document {pair.root_doc.id} after deleting pages {pages}",
@@ -950,6 +1000,7 @@ def edit_pdf(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
parent_task_id: str | None = None,
) -> Literal["OK"]:
"""
Operations is a list of dictionaries describing the final PDF pages.
@@ -994,16 +1045,15 @@ def edit_pdf(
if user is not None:
overrides.owner_id = user.id
overrides.actor_id = user.id
consume_file.apply_async(
kwargs={
"input_doc": ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
"overrides": overrides,
},
headers={"trigger_source": trigger_source},
queue_consumption(
input_doc=ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
overrides=overrides,
trigger_source=trigger_source,
parent_task_id=parent_task_id,
)
else:
version_filepaths = pdf_ops.build_pdfs(
@@ -1043,7 +1093,17 @@ def edit_pdf(
).set(headers={"trigger_source": trigger_source}),
)
if delete_original:
if parent_task_id is not None:
backup = (
release_archive_serial_numbers([doc.id]) if delete_original else {}
)
queue_processing_tasks(
parent_task_id,
consume_tasks,
delete_ids=[doc.id] if delete_original else None,
asn_backup=backup,
)
elif delete_original:
backup = release_archive_serial_numbers([doc.id])
try:
chord(
@@ -1077,6 +1137,7 @@ def remove_password(
source_mode: SourceMode = SourceModeChoices.LATEST_VERSION,
user: User | None = None,
trigger_source: PaperlessTask.TriggerSource = PaperlessTask.TriggerSource.WEB_UI,
parent_task_id: str | None = None,
source_paths_by_id: Mapping[int, Path] | None = None,
) -> Literal["OK"]:
"""
@@ -1119,16 +1180,15 @@ def remove_password(
if user is not None:
overrides.owner_id = user.id
overrides.actor_id = user.id
consume_file.apply_async(
kwargs={
"input_doc": ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
"overrides": overrides,
},
headers={"trigger_source": trigger_source},
queue_consumption(
input_doc=ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=filepath,
root_document_id=pair.root_doc.id,
),
overrides=overrides,
trigger_source=trigger_source,
parent_task_id=parent_task_id,
)
else:
consume_tasks = []
@@ -1151,7 +1211,19 @@ def remove_password(
).set(headers={"trigger_source": trigger_source}),
)
if delete_original:
if parent_task_id is not None:
backup = (
release_archive_serial_numbers([doc.id])
if delete_original
else {}
)
queue_processing_tasks(
parent_task_id,
consume_tasks,
delete_ids=[doc.id] if delete_original else None,
asn_backup=backup,
)
elif delete_original:
chord(
header=consume_tasks,
body=delete.si([doc.id]),
+13 -3
View File
@@ -90,8 +90,9 @@ def snapshot_field(doc_ids: list[int], field: str) -> dict[int, Any]:
return values
@shared_task
@shared_task(bind=True)
def execute_bulk_operation(
self,
operation: str,
document_ids: list[int],
parameters: dict,
@@ -117,6 +118,11 @@ def execute_bulk_operation(
if operation not in MODIFIED_FIELDS:
execution_parameters = parameters.copy()
if (
operation in TRIGGER_SOURCE_OPERATIONS | {"reprocess"}
and self.request.id is not None
):
execution_parameters["parent_task_id"] = self.request.id
if operation in USER_OPERATIONS:
execution_parameters["user"] = user
if operation in TRIGGER_SOURCE_OPERATIONS:
@@ -128,7 +134,7 @@ def execute_bulk_operation(
if settings.AUDIT_LOG_ENABLED and modified_field
else {}
)
method(document_ids, **execution_parameters)
result = method(document_ids, **execution_parameters)
if settings.AUDIT_LOG_ENABLED and modified_field:
from auditlog.models import LogEntry
@@ -143,7 +149,11 @@ def execute_bulk_operation(
actor=user,
additional_data={"reason": f"Bulk edit: {operation}"},
)
return {"operation": operation, "document_count": len(document_ids)}
return {
"operation": operation,
"document_count": len(document_ids),
**(result if isinstance(result, dict) else {}),
}
affected_ids: list[int] = []
modified_field = MODIFIED_FIELDS[operation]
@@ -0,0 +1,30 @@
# Generated by Django 5.2.18 on 2026-11-14 19:59
import django.db.models.deletion
from django.db import migrations
from django.db import models
class Migration(migrations.Migration):
dependencies = [
("documents", "0030_note_format"),
]
operations = [
migrations.AddField(
model_name="paperlesstask",
name="dispatched",
field=models.BooleanField(default=False),
),
migrations.AddField(
model_name="paperlesstask",
name="parent",
field=models.ForeignKey(
blank=True,
null=True,
on_delete=django.db.models.deletion.SET_NULL,
related_name="children",
to="documents.paperlesstask",
),
),
]
+10
View File
@@ -966,6 +966,16 @@ class PaperlessTask(ModelWithOwner):
help_text=_("Structured result data from task execution"),
)
parent = models.ForeignKey(
"self",
null=True,
blank=True,
on_delete=models.SET_NULL,
related_name="children",
)
dispatched = models.BooleanField(default=False)
# Acknowledgment
acknowledged = models.BooleanField(
default=False,
+1 -8
View File
@@ -385,16 +385,9 @@ def open_or_rebuild_index(index_dir: Path | None = None) -> tantivy.Index:
return tantivy.Index.open(str(index_dir))
except ValueError:
logger.exception(
"Search index is corrupted or incomplete. A new, empty index was "
"created, but existing documents are not indexed yet. "
"They will be reindexed on the next startup, or run "
"'document_index reindex' to do so now.",
"Search index is corrupted or incomplete - rebuilding from scratch.",
)
wipe_index(index_dir)
idx = tantivy.Index(build_schema(), path=str(index_dir))
_write_sentinels(index_dir)
# The new index is stamped as current but is empty. Flag it so the next
# `document_index reindex --if-needed` repopulates it. Reindexing here
# would block whichever process happened to open the index first.
(index_dir / REBUILD_MARKER).touch()
return idx
+3 -8
View File
@@ -106,10 +106,6 @@ if TYPE_CHECKING:
logger = logging.getLogger("paperless.serializers")
# How much of an upload is read to detect its type. libmagic examines at most
# 7 MiB (its default bytes_max), so this is more than it will ever look at.
_MIME_SNIFF_BYTES = 8 * 1024 * 1024
# https://www.django-rest-framework.org/api-guide/serializers/#example
class DynamicFieldsModelSerializer(serializers.ModelSerializer[Any]):
@@ -2310,9 +2306,8 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
)
def validate_document(self, document):
# libmagic only examines a bounded prefix, so an upload of any size is
# never read into memory just to detect its type
mime_type = magic.from_buffer(document.read(_MIME_SNIFF_BYTES), mime=True)
document_data = document.file.read()
mime_type = magic.from_buffer(document_data, mime=True)
if not is_mime_type_supported(mime_type):
if (
@@ -2328,7 +2323,7 @@ class PostDocumentSerializer(serializers.Serializer[dict[str, Any]]):
_("File type %(type)s not supported") % {"type": mime_type},
)
return document.name, document
return document.name, document_data
def validate_correspondent(self, correspondent):
if correspondent:
+44
View File
@@ -56,6 +56,8 @@ from documents.models import WorkflowRun
from documents.models import WorkflowTrigger
from documents.permissions import restrict_queryset_to_visible
from documents.plugins.helpers import DocumentsStatusManager
from documents.task_tracking import finish_dispatch
from documents.task_tracking import update_parent
from documents.templating.utils import convert_format_str_to_template_format
from documents.utils import compute_checksum
from documents.utils import copy_file_with_basic_stats
@@ -1077,6 +1079,7 @@ TRACKED_TASKS: dict[str, PaperlessTask.TaskType] = {
"documents.tasks.update_document_content_maybe_archive_file": PaperlessTask.TaskType.REPROCESS_DOCUMENT,
"documents.tasks.build_share_link_bundle": PaperlessTask.TaskType.BUILD_SHARE_LINK,
"documents.bulk_edit.delete": PaperlessTask.TaskType.BULK_DELETE,
"documents.task_tracking.finish_file_operation": PaperlessTask.TaskType.BULK_DELETE,
"documents.tasks.apply_ai_suggestions": PaperlessTask.TaskType.APPLY_AI_SUGGESTIONS,
BULK_OPERATION_TASK_NAME: PaperlessTask.TaskType.BULK_UPDATE,
}
@@ -1125,6 +1128,8 @@ def _extract_input_data(
data["overrides"] = override_dict
return data
if task_type == PaperlessTask.TaskType.REPROCESS_DOCUMENT:
return {"document_id": task_kwargs["document_id"]}
if task_type == PaperlessTask.TaskType.MAIL_FETCH:
account_ids = task_kwargs.get("account_ids")
if account_ids is not None:
@@ -1212,6 +1217,19 @@ def before_task_publish_handler(
input_data = _extract_input_data(task_type, task_kwargs)
owner_id = _extract_owner_id(task_type, task_kwargs)
trigger_source = _determine_trigger_source(headers)
# Consumption can fan out again (e.g. barcode splitting). Keep those
# descendants attached so their caller cannot finish before them.
parent = None
if task_type == PaperlessTask.TaskType.CONSUME_FILE and headers.get(
"parent_id",
):
parent = PaperlessTask.objects.filter(
task_id=headers["parent_id"],
parent__isnull=False,
).first()
if parent is not None:
owner_id = parent.owner_id
trigger_source = parent.trigger_source
# A retried task is republished with the same task_id, so this fires
# again for it; get_or_create keeps the original PENDING record
@@ -1224,6 +1242,7 @@ def before_task_publish_handler(
"status": PaperlessTask.Status.PENDING,
"input_data": input_data,
"owner_id": owner_id,
"parent": parent,
},
)
except Exception: # pragma: no cover
@@ -1309,6 +1328,10 @@ def task_postrun_handler(
except PaperlessTask.DoesNotExist:
return
if task_instance.children.exists():
finish_dispatch(task_instance, retval if isinstance(retval, dict) else {})
return
task_instance.status = new_status
task_instance.date_done = now
changed_fields = ["status", "date_done"]
@@ -1331,7 +1354,21 @@ def task_postrun_handler(
task_instance.status = PaperlessTask.Status.FAILURE
changed_fields.append("status")
if (
task_instance.parent_id is not None
and task_instance.task_type == PaperlessTask.TaskType.CONSUME_FILE
and (not isinstance(retval, dict) or "document_id" not in retval)
and not (isinstance(retval, dict) and "duplicate_of" in retval)
):
task_instance.status = PaperlessTask.Status.FAILURE
task_instance.result_data = {
**(retval if isinstance(retval, dict) else {}),
"error_message": "Consumption stopped without creating a document.",
}
changed_fields.extend(["status", "result_data"])
task_instance.save(update_fields=changed_fields)
update_parent(task_instance)
if task and task.name == BULK_OPERATION_TASK_NAME:
_send_bulk_operation_status(task_instance)
except Exception: # pragma: no cover
@@ -1388,6 +1425,10 @@ def task_failure_handler(
}
task_qs = PaperlessTask.objects.filter(task_id=task_id)
parent = task_qs.first()
if parent is not None and parent.children.exists():
finish_dispatch(parent, result_data)
return
task_instance = task_qs.values("date_started", "date_created").first()
if task_instance:
date_started = task_instance["date_started"]
@@ -1399,6 +1440,7 @@ def task_failure_handler(
date_started - date_created
).total_seconds()
task_qs.update(**update_fields)
update_parent(task_qs.get())
if sender and sender.name == BULK_OPERATION_TASK_NAME:
_send_bulk_operation_status(task_qs.first())
except Exception: # pragma: no cover
@@ -1445,6 +1487,8 @@ def task_revoked_handler(
"reason": (reason + " Check worker logs for details."),
},
)
if task_instance := task_qs.first():
update_parent(task_instance)
if sender and sender.name == BULK_OPERATION_TASK_NAME:
_send_bulk_operation_status(task_qs.first())
except Exception: # pragma: no cover
+242
View File
@@ -0,0 +1,242 @@
"""Completion tracking for operations which dispatch document processing tasks."""
from __future__ import annotations
import uuid
from typing import TYPE_CHECKING
from celery import shared_task
from django.db import transaction
from django.utils import timezone
from documents.models import PaperlessTask
if TYPE_CHECKING:
from celery.canvas import Signature
from documents.data_models import ConsumableDocument
from documents.data_models import DocumentMetadataOverrides
def queue_consumption(
*,
input_doc: ConsumableDocument,
overrides: DocumentMetadataOverrides,
trigger_source: str,
parent_task_id: str | None,
) -> None:
from documents.tasks import consume_file
kwargs = {"input_doc": input_doc, "overrides": overrides}
if parent_task_id is None:
consume_file.apply_async(
kwargs=kwargs,
headers={"trigger_source": trigger_source},
)
else:
queue_processing_tasks(parent_task_id, [consume_file.s(**kwargs)])
def queue_reprocessing_tasks(
parent_task_id: str,
document_ids: list[int],
*,
remote_ocr: bool,
) -> None:
from documents.tasks import update_document_content_maybe_archive_file
queue_processing_tasks(
parent_task_id,
[
update_document_content_maybe_archive_file.s(
document_id=document_id,
remote_ocr=remote_ocr,
)
for document_id in document_ids
],
)
def queue_processing_tasks(
parent_task_id: str,
signatures: list[Signature],
*,
delete_ids: list[int] | None = None,
asn_backup: dict | None = None,
) -> None:
from documents.signals.handlers import TRACKED_TASKS
from documents.signals.handlers import _extract_input_data
parent = PaperlessTask.objects.get(task_id=parent_task_id)
children = [
PaperlessTask(
task_id=str(uuid.uuid4()),
task_type=TRACKED_TASKS[signature.task],
trigger_source=parent.trigger_source,
owner_id=parent.owner_id,
parent=parent,
input_data=_extract_input_data(
TRACKED_TASKS[signature.task],
signature.kwargs,
),
)
for signature in signatures
]
# Dependencies and their final step must be registered together.
with transaction.atomic():
PaperlessTask.objects.bulk_create(children)
if delete_ids:
PaperlessTask.objects.create(
task_id=str(uuid.uuid4()),
task_type=PaperlessTask.TaskType.BULK_DELETE,
owner_id=parent.owner_id,
trigger_source=parent.trigger_source,
parent=parent,
input_data={
"dependencies": [child.pk for child in children],
"delete_ids": delete_ids,
"asn_backup": asn_backup or {},
},
)
for index, (signature, child) in enumerate(zip(signatures, children, strict=True)):
try:
signature.apply_async(
task_id=child.task_id,
headers={"trigger_source": parent.trigger_source},
)
except Exception:
PaperlessTask.objects.filter(
pk__in=[task.pk for task in children[index:]],
).update(
status=PaperlessTask.Status.FAILURE,
date_done=timezone.now(),
result_data={"error_message": "Could not publish processing task."},
)
raise
@shared_task
def finish_file_operation(
dependencies: list[int],
delete_ids: list[int],
asn_backup: dict,
) -> dict[str, str]:
from documents.bulk_edit import delete
from documents.bulk_edit import restore_archive_serial_numbers
statuses = list(
PaperlessTask.objects.filter(pk__in=dependencies).values_list(
"status",
flat=True,
),
)
if len(statuses) != len(dependencies):
raise ValueError(
"Processing task records are missing; originals were preserved.",
)
if any(status != PaperlessTask.Status.SUCCESS for status in statuses):
restore_archive_serial_numbers(asn_backup)
return {"reason": "Originals preserved; archive serial numbers restored."}
delete(delete_ids)
return {"reason": "Originals moved to trash."}
def _publish_finalizer(task: PaperlessTask) -> None:
try:
finish_file_operation.apply_async(
task_id=task.task_id,
kwargs=task.input_data,
headers={"trigger_source": task.trigger_source},
)
except Exception as error:
from documents.signals.handlers import task_failure_handler
task_failure_handler(
sender=finish_file_operation,
task_id=task.task_id,
exception=error,
)
def _schedule_finalizers(parent: PaperlessTask) -> None:
for task in parent.children.filter(
task_type=PaperlessTask.TaskType.BULK_DELETE,
status=PaperlessTask.Status.PENDING,
):
dependencies = task.input_data.get("dependencies")
if dependencies is None or task.result_data:
continue
if (
PaperlessTask.objects.filter(pk__in=dependencies)
.exclude(
status__in=PaperlessTask.COMPLETE_STATUSES,
)
.exists()
):
continue
task.result_data = {"scheduled": True}
task.save(update_fields=["result_data"])
transaction.on_commit(lambda task=task: _publish_finalizer(task))
def finish_dispatch(task: PaperlessTask, result_data: dict) -> None:
"""Record the scheduling outcome without completing an active parent."""
with transaction.atomic():
parent = PaperlessTask.objects.select_for_update().get(pk=task.pk)
if parent.is_complete:
return
parent.dispatched = True
parent.result_data = result_data
parent.save(update_fields=["dispatched", "result_data"])
_finalize_parent(parent)
def update_parent(task: PaperlessTask) -> None:
if task.parent_id is None:
return
with transaction.atomic():
parent = PaperlessTask.objects.select_for_update().get(pk=task.parent_id)
_finalize_parent(parent)
def _finalize_parent(parent: PaperlessTask) -> None:
if parent.is_complete or not parent.dispatched:
return
_schedule_finalizers(parent)
statuses = list(parent.children.values_list("status", flat=True))
if any(status not in PaperlessTask.COMPLETE_STATUSES for status in statuses):
return
succeeded = statuses.count(PaperlessTask.Status.SUCCESS)
failed = len(statuses) - succeeded
result_data = parent.result_data or {}
if failed and not result_data.get("error_message"):
result_data["error_message"] = (
f"{succeeded} child task(s) succeeded; {failed} failed or were revoked. "
"See child tasks for details."
)
parent.status = (
PaperlessTask.Status.FAILURE
if result_data.get("error_message")
else PaperlessTask.Status.SUCCESS
)
parent.result_data = {
**parent.input_data,
**result_data,
"succeeded_count": succeeded,
"failed_count": failed,
}
parent.date_done = timezone.now()
if parent.date_started:
parent.duration_seconds = (
parent.date_done - parent.date_started
).total_seconds()
parent.wait_time_seconds = (
parent.date_started - parent.date_created
).total_seconds()
parent.save()
from documents.signals.handlers import _send_bulk_operation_status
if "operation" in parent.input_data:
transaction.on_commit(lambda: _send_bulk_operation_status(parent))
update_parent(parent)
+3 -3
View File
@@ -394,11 +394,10 @@ def update_document_content_maybe_archive_file(
)
if not parser_class:
logger.error(
raise ValueError(
f"No parser found for mime type {mime_type}, cannot "
f"archive document {document} (ID: {document_id})",
f"reprocess document {document} (ID: {document_id})",
)
return
with parser_class() as parser:
parser.configure(ParserContext())
@@ -512,6 +511,7 @@ def update_document_content_maybe_archive_file(
logger.exception(
f"Error while parsing document {document} (ID: {document_id})",
)
raise
@shared_task
@@ -225,21 +225,3 @@ class TestCorruptedIndex:
assert (current_index_missing_meta_json / "meta.json").exists()
tantivy.Index.open(str(current_index_missing_meta_json))
def test_missing_meta_json_flags_index_for_reindex(
self,
current_index_missing_meta_json: Path,
) -> None:
"""
GIVEN:
- An index directory with matching sentinels but a missing meta.json
WHEN:
- open_or_rebuild_index() recreates it as an empty index
THEN:
- needs_rebuild() is True, so the next
`document_index reindex --if-needed` repopulates the index
instead of reporting the empty one as up to date
"""
open_or_rebuild_index(current_index_missing_meta_json)
assert needs_rebuild(current_index_missing_meta_json)
+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"]
-32
View File
@@ -2089,38 +2089,6 @@ class TestDocumentApi(DirectoriesMixin, ConsumeTaskMixin, APITestCase):
self.assertIsNone(overrides.document_type_id)
self.assertIsNone(overrides.tag_ids)
def test_upload_type_is_detected_from_a_prefix(self) -> None:
"""
GIVEN:
- An upload larger than the prefix read to detect its type
WHEN:
- The document is posted
THEN:
- The type is detected from the prefix and the upload is accepted
- The file handed to the consumer holds the whole upload
"""
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
)
content = SIMPLE_DIGITAL_PDF.read_bytes()
with (
mock.patch("documents.serialisers._MIME_SNIFF_BYTES", 1024),
SimpleUploadedFile(
"simple.pdf",
content,
content_type="application/pdf",
) as f,
):
response = self.client.post(
"/api/documents/post_document/",
{"document": f},
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
input_doc, _ = self.assert_queue_consumption_task_call_args()
self.assertEqual(input_doc.original_file.read_bytes(), content)
def test_upload_with_path_traversal_filename_is_reduced_to_basename(self) -> None:
self.consume_file_mock.return_value = celery.result.AsyncResult(
id=str(uuid.uuid4()),
+2 -1
View File
@@ -69,7 +69,8 @@ class TestArchiver(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
doc.save()
shutil.copy(sample_file, doc.source_path)
update_document_content_maybe_archive_file(doc.pk)
with self.assertRaisesMessage(ValueError, "No parser found"):
update_document_content_maybe_archive_file(doc.pk)
doc = Document.objects.get(id=doc.id)
+543
View File
@@ -0,0 +1,543 @@
import shutil
import uuid
from unittest import mock
import pytest
from documents.bulk_operations import execute_bulk_operation
from documents.models import PaperlessTask
from documents.signals.handlers import task_failure_handler
from documents.signals.handlers import task_postrun_handler
from documents.signals.handlers import task_revoked_handler
from documents.tasks import update_document_content_maybe_archive_file
from paperless_testing.factories import DocumentFactory
from paperless_testing.factories import UserFactory
@pytest.fixture
def operation(paperless_dirs):
user = UserFactory(superuser=True)
documents = DocumentFactory.create_batch(3)
parent = PaperlessTask.objects.create(
task_id=str(uuid.uuid4()),
task_type=PaperlessTask.TaskType.BULK_UPDATE,
owner=user,
trigger_source=PaperlessTask.TriggerSource.WEB_UI,
input_data={"operation": "reprocess", "document_count": 3},
)
kwargs = {
"operation": "reprocess",
"document_ids": [document.pk for document in documents],
"parameters": {"remote_ocr": True},
"user_id": user.pk,
}
return parent, kwargs
@pytest.fixture
def pdf_documents(paperless_dirs, tmp_path):
from documents.models import Document
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
documents = DocumentFactory.create_batch(2, mime_type="application/pdf")
for document in documents:
source = tmp_path / f"{document.pk}.pdf"
shutil.copy(SIMPLE_DIGITAL_PDF, source)
Document.objects.filter(pk=document.pk).update(filename=str(source))
document.refresh_from_db()
return documents
def complete(child, status="SUCCESS"):
if status == "FAILURE":
task_failure_handler(
sender=update_document_content_maybe_archive_file,
task_id=child.task_id,
exception=RuntimeError("Parser failed"),
)
elif status == "REVOKED":
task_revoked_handler(
sender=update_document_content_maybe_archive_file,
request=mock.Mock(id=child.task_id),
)
else:
task_postrun_handler(
task=update_document_content_maybe_archive_file,
task_id=child.task_id,
state=status,
)
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("outcome", ["SUCCESS", "FAILURE", "REVOKED"])
def test_parent_waits_for_all_children(operation, outcome):
parent, kwargs = operation
with (
mock.patch(
"documents.tasks.update_document_content_maybe_archive_file.apply_async",
) as publish,
mock.patch("documents.signals.handlers._send_bulk_operation_status") as notify,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
assert parent.date_done is None
children = list(parent.children.order_by("pk"))
assert len(children) == 3
assert publish.call_count == 3
assert all(child.owner_id == parent.owner_id for child in children)
assert all(child.trigger_source == parent.trigger_source for child in children)
assert all(call.args[1]["remote_ocr"] for call in publish.call_args_list)
complete(children[0], outcome)
complete(children[1])
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
notify.assert_not_called()
complete(children[2])
parent.refresh_from_db()
assert parent.status == ("success" if outcome == "SUCCESS" else "failure")
assert parent.result_data["succeeded_count"] == (
3 if outcome == "SUCCESS" else 2
)
assert parent.result_data["failed_count"] == (0 if outcome == "SUCCESS" else 1)
assert parent.date_done is not None
assert parent.duration_seconds >= 0
notify.assert_called_once()
complete(children[2])
notify.assert_called_once()
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("outcome", ["SUCCESS", "FAILURE"])
def test_fast_children_wait_for_dispatch_to_finish(operation, outcome):
parent, kwargs = operation
def publish(*args, task_id, **kwargs):
# Every child is registered before the first publication.
assert parent.children.count() == 3
complete(PaperlessTask.objects.get(task_id=task_id), outcome)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
assert not parent.dispatched
with (
mock.patch(
"documents.tasks.update_document_content_maybe_archive_file.apply_async",
side_effect=publish,
),
mock.patch("documents.signals.handlers._send_bulk_operation_status") as notify,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
parent.refresh_from_db()
assert parent.status == ("success" if outcome == "SUCCESS" else "failure")
notify.assert_called_once()
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("published_count", [0, 1])
def test_publish_failure_waits_for_published_children(operation, published_count):
parent, kwargs = operation
with (
mock.patch(
"documents.tasks.update_document_content_maybe_archive_file.apply_async",
side_effect=[None] * published_count + [RuntimeError("Broker unavailable")],
),
mock.patch("documents.signals.handlers._send_bulk_operation_status") as notify,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=False)
parent.refresh_from_db()
if published_count:
assert parent.status == PaperlessTask.Status.STARTED
notify.assert_not_called()
complete(parent.children.get(status=PaperlessTask.Status.PENDING))
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.FAILURE
assert parent.result_data["error_message"] == "Broker unavailable"
assert parent.result_data["succeeded_count"] == published_count
assert parent.result_data["failed_count"] == 3 - published_count
notify.assert_called_once()
@pytest.mark.django_db(transaction=True)
def test_empty_selection_completes_without_children(operation):
parent, kwargs = operation
kwargs["document_ids"] = []
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.SUCCESS
assert not parent.children.exists()
@pytest.mark.django_db
def test_client_cannot_supply_parent_task_id(operation):
from rest_framework.test import APIClient
parent, kwargs = operation
client = APIClient()
client.force_authenticate(parent.owner)
with mock.patch("documents.views.execute_bulk_operation.apply_async") as publish:
response = client.post(
"/api/documents/bulk_edit/",
{
"documents": kwargs["document_ids"],
"method": "set_correspondent",
"parameters": {"correspondent": None, "parent_task_id": parent.task_id},
},
format="json",
)
assert response.status_code == 400
publish.assert_not_called()
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
"name,parameters",
[
("rotate", {"degrees": 90}),
("merge", {}),
("split", {"pages": [[1]]}),
("delete_pages", {"pages": [1]}),
("edit_pdf", {"operations": [{"page": 1}], "update_document": True}),
("edit_pdf", {"operations": [{"page": 1}]}),
("remove_password", {"password": "secret", "update_document": True}),
("remove_password", {"password": "secret"}),
],
)
def test_file_operations_wait_for_consumption(
operation,
pdf_documents,
name,
parameters,
):
from documents.tasks import consume_file
parent, kwargs = operation
documents = pdf_documents
kwargs.update(
operation=name,
document_ids=[doc.pk for doc in documents]
if name == "merge"
else [documents[0].pk],
parameters=parameters,
)
parent.input_data = {
"operation": name,
"document_count": len(kwargs["document_ids"]),
}
parent.save()
with (
mock.patch("documents.tasks.consume_file.apply_async") as publish,
mock.patch("documents.bulk_edit.pdf_ops.needs_decrypt", return_value=True),
mock.patch(
"documents.bulk_edit.pdf_ops.decrypt_pdf",
return_value=documents[0].source_path,
),
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
child = parent.children.get()
assert child.task_type == PaperlessTask.TaskType.CONSUME_FILE
publish.assert_called_once()
task_postrun_handler(
task=consume_file,
task_id=child.task_id,
state="SUCCESS",
retval={"document_id": 100},
)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.SUCCESS
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize(
"outcome",
["success", "failure", "duplicate", "stopped", "revoked"],
)
def test_replacement_waits_for_deletion_or_recovery(operation, pdf_documents, outcome):
from documents.models import Document
from documents.task_tracking import finish_file_operation
from documents.tasks import consume_file
parent, kwargs = operation
doc = pdf_documents[0]
doc.archive_serial_number = 123
Document.objects.filter(pk=doc.pk).update(archive_serial_number=123)
kwargs.update(
operation="edit_pdf",
document_ids=[doc.pk],
parameters={"operations": [{"page": 1}], "delete_original": True},
)
parent.input_data = {"operation": "edit_pdf", "document_count": 1}
parent.save()
with (
mock.patch("documents.tasks.consume_file.apply_async"),
mock.patch(
"documents.task_tracking.finish_file_operation.apply_async",
) as finalize,
mock.patch("documents.signals.handlers._send_bulk_operation_status") as notify,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
consume = parent.children.get(task_type=PaperlessTask.TaskType.CONSUME_FILE)
finalizer = parent.children.get(task_type=PaperlessTask.TaskType.BULK_DELETE)
finalize.assert_not_called()
if outcome == "failure":
complete(consume, "FAILURE")
elif outcome == "revoked":
complete(consume, "REVOKED")
else:
retval = (
{"document_id": 100}
if outcome == "success"
else (
{"duplicate_of": 100}
if outcome == "duplicate"
else {"reason": "Stopped"}
)
)
task_postrun_handler(
task=consume_file,
task_id=consume.task_id,
state="SUCCESS",
retval=retval,
)
finalize.assert_called_once()
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
assert Document.objects.filter(pk=doc.pk).exists()
notify.assert_not_called()
finish_file_operation.apply(
kwargs=finalizer.input_data,
task_id=finalizer.task_id,
throw=True,
)
parent.refresh_from_db()
assert parent.status == ("success" if outcome == "success" else "failure")
notify.assert_called_once()
if outcome == "success":
assert not Document.objects.filter(pk=doc.pk).exists()
else:
doc.refresh_from_db()
assert not doc.is_deleted
assert doc.archive_serial_number == 123
@pytest.mark.django_db(transaction=True)
def test_consumption_descendants_keep_operation_active(operation):
from documents.data_models import ConsumableDocument
from documents.data_models import DocumentSource
from documents.signals.handlers import before_task_publish_handler
from documents.task_tracking import finish_dispatch
from documents.task_tracking import queue_processing_tasks
from documents.tasks import consume_file
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
parent, _ = operation
parent.status = PaperlessTask.Status.STARTED
parent.save()
input_doc = ConsumableDocument(
source=DocumentSource.ConsumeFolder,
original_file=SIMPLE_DIGITAL_PDF,
)
with mock.patch("documents.tasks.consume_file.apply_async"):
queue_processing_tasks(parent.task_id, [consume_file.s(input_doc=input_doc)])
child = parent.children.get()
finish_dispatch(parent, {})
descendant_id = str(uuid.uuid4())
before_task_publish_handler(
headers={
"task": consume_file.name,
"id": descendant_id,
"parent_id": child.task_id,
},
body=((), {"input_doc": input_doc}, {}),
)
descendant = PaperlessTask.objects.get(task_id=descendant_id)
assert descendant.parent_id == child.pk
assert descendant.owner_id == parent.owner_id
task_postrun_handler(
task=consume_file,
task_id=child.task_id,
state="SUCCESS",
retval={"reason": "Barcode splitting complete"},
)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
task_postrun_handler(
task=consume_file,
task_id=descendant_id,
state="SUCCESS",
retval={"document_id": 100},
)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.SUCCESS
@pytest.mark.django_db(transaction=True)
@pytest.mark.parametrize("failure", ["delete", "restore", "publish"])
def test_final_step_failures_reach_parent(operation, pdf_documents, failure):
from documents.task_tracking import finish_file_operation
from documents.tasks import consume_file
parent, kwargs = operation
doc = pdf_documents[0]
kwargs.update(
operation="edit_pdf",
document_ids=[doc.pk],
parameters={"operations": [{"page": 1}], "delete_original": True},
)
with (
mock.patch("documents.tasks.consume_file.apply_async"),
mock.patch(
"documents.task_tracking.finish_file_operation.apply_async",
side_effect=RuntimeError("Publish failed")
if failure == "publish"
else None,
),
mock.patch("documents.signals.handlers._send_bulk_operation_status") as notify,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
child = parent.children.get(task_type=PaperlessTask.TaskType.CONSUME_FILE)
if failure == "restore":
complete(child, "FAILURE")
else:
task_postrun_handler(
task=consume_file,
task_id=child.task_id,
state="SUCCESS",
retval={"document_id": 100},
)
finalizer = parent.children.get(task_type=PaperlessTask.TaskType.BULK_DELETE)
if failure != "publish":
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
notify.assert_not_called()
target = (
"documents.bulk_edit.delete"
if failure == "delete"
else "documents.bulk_edit.restore_archive_serial_numbers"
)
with mock.patch(target, side_effect=RuntimeError("Final step failed")):
finish_file_operation.apply(
kwargs=finalizer.input_data,
task_id=finalizer.task_id,
throw=False,
)
parent.refresh_from_db()
finalizer.refresh_from_db()
assert finalizer.status == PaperlessTask.Status.FAILURE
assert parent.status == PaperlessTask.Status.FAILURE
notify.assert_called_once()
doc.refresh_from_db()
assert not doc.is_deleted
@pytest.mark.django_db(transaction=True)
def test_partial_merge_preserves_skipped_original_and_reports_it(
operation,
pdf_documents,
):
from documents.models import Document
from documents.task_tracking import finish_file_operation
from documents.tasks import consume_file
parent, kwargs = operation
included, excluded = pdf_documents
excluded.source_path.unlink()
kwargs.update(
operation="merge",
document_ids=[included.pk, excluded.pk],
parameters={"delete_originals": True},
)
parent.input_data = {"operation": "merge", "document_count": 2}
parent.save()
with (
mock.patch("documents.tasks.consume_file.apply_async") as consume,
mock.patch("documents.task_tracking.finish_file_operation.apply_async"),
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
consume.assert_called_once()
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
assert parent.result_data["failed_document_ids"] == [excluded.pk]
child = parent.children.get(task_type=PaperlessTask.TaskType.CONSUME_FILE)
task_postrun_handler(
task=consume_file,
task_id=child.task_id,
state="SUCCESS",
retval={"document_id": 100},
)
finalizer = parent.children.get(task_type=PaperlessTask.TaskType.BULK_DELETE)
assert finalizer.input_data["delete_ids"] == [included.pk]
finish_file_operation.apply(
kwargs=finalizer.input_data,
task_id=finalizer.task_id,
throw=True,
)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.FAILURE
assert parent.result_data["failed_document_ids"] == [excluded.pk]
assert not Document.objects.filter(pk=included.pk).exists()
assert Document.objects.filter(pk=excluded.pk).exists()
@pytest.mark.django_db(transaction=True)
def test_merge_with_no_valid_inputs_fails(operation, pdf_documents):
parent, kwargs = operation
for doc in pdf_documents:
doc.source_path.unlink()
kwargs.update(
operation="merge",
document_ids=[doc.pk for doc in pdf_documents],
parameters={},
)
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=False)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.FAILURE
assert not parent.children.exists()
@pytest.mark.django_db(transaction=True)
def test_split_waits_for_every_output_before_recovery(operation, pdf_documents):
from documents.task_tracking import finish_file_operation
from documents.tasks import consume_file
parent, kwargs = operation
doc = pdf_documents[0]
kwargs.update(
operation="split",
document_ids=[doc.pk],
parameters={"pages": [[1], [1]], "delete_originals": True},
)
with (
mock.patch("documents.tasks.consume_file.apply_async"),
mock.patch(
"documents.task_tracking.finish_file_operation.apply_async",
) as finalize,
):
execute_bulk_operation.apply(kwargs=kwargs, task_id=parent.task_id, throw=True)
children = list(
parent.children.filter(task_type=PaperlessTask.TaskType.CONSUME_FILE),
)
assert len(children) == 2
complete(children[0], "FAILURE")
finalize.assert_not_called()
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.STARTED
task_postrun_handler(
task=consume_file,
task_id=children[1].task_id,
state="SUCCESS",
retval={"document_id": 100},
)
finalize.assert_called_once()
finalizer = parent.children.get(task_type=PaperlessTask.TaskType.BULK_DELETE)
finish_file_operation.apply(
kwargs=finalizer.input_data,
task_id=finalizer.task_id,
throw=True,
)
parent.refresh_from_db()
assert parent.status == PaperlessTask.Status.FAILURE
doc.refresh_from_db()
assert not doc.is_deleted
+58 -1
View File
@@ -1,4 +1,5 @@
import shutil
import uuid
from datetime import timedelta
from pathlib import Path
from unittest import mock
@@ -16,6 +17,7 @@ from documents import tasks
from documents.models import Correspondent
from documents.models import Document
from documents.models import DocumentType
from documents.models import PaperlessTask
from documents.models import Tag
from documents.models import WorkflowAction
from documents.sanity_checker import SanityCheckFailedException
@@ -280,6 +282,60 @@ class TestUpdateContent(DirectoriesMixin, TestCase):
tasks.update_document_content_maybe_archive_file(doc.pk)
self.assertNotEqual(Document.objects.get(pk=doc.pk).content, "test")
@mock.patch("documents.tasks.get_parser_registry")
def test_missing_parser_records_failure(self, registry) -> None:
doc = DocumentFactory(content="Original content", mime_type="application/pdf")
registry.return_value.get_parser_for_file.return_value = None
task = PaperlessTask.objects.create(
task_id=str(uuid.uuid4()),
task_type=PaperlessTask.TaskType.REPROCESS_DOCUMENT,
)
result = tasks.update_document_content_maybe_archive_file.apply(
args=[doc.pk],
task_id=task.task_id,
throw=False,
)
self.assertTrue(result.failed())
task.refresh_from_db()
self.assertEqual(task.status, PaperlessTask.Status.FAILURE)
self.assertIn("No parser found", task.result_data["error_message"])
doc.refresh_from_db()
self.assertEqual(doc.content, "Original content")
@mock.patch("documents.tasks.should_produce_archive", return_value=False)
@mock.patch("documents.tasks.get_parser_registry")
def test_parser_failure_records_failure(self, registry, _produce_archive) -> None:
for method in ("parse", "get_thumbnail"):
with self.subTest(method=method):
doc = DocumentFactory(
content="Original content",
mime_type="application/pdf",
)
parser = mock.MagicMock()
getattr(parser, method).side_effect = RuntimeError("Processing failed")
parser_class = mock.MagicMock()
parser_class.return_value.__enter__.return_value = parser
registry.return_value.get_parser_for_file.return_value = parser_class
task = PaperlessTask.objects.create(
task_id=str(uuid.uuid4()),
task_type=PaperlessTask.TaskType.REPROCESS_DOCUMENT,
)
result = tasks.update_document_content_maybe_archive_file.apply(
args=[doc.pk],
task_id=task.task_id,
throw=False,
)
self.assertTrue(result.failed())
task.refresh_from_db()
self.assertEqual(task.status, PaperlessTask.Status.FAILURE)
self.assertEqual(task.result_data["error_message"], "Processing failed")
doc.refresh_from_db()
self.assertEqual(doc.content, "Original content")
def _create_root_with_version(self) -> tuple[Document, Document]:
sample1 = self.dirs.scratch_dir / "sample.pdf"
shutil.copy(SIMPLE_DIGITAL_PDF, sample1)
@@ -370,7 +426,8 @@ class TestUpdateContentRemoteOCR(DirectoriesMixin, TestCase):
)
def _allow_remote(self, **kwargs) -> bool:
tasks.update_document_content_maybe_archive_file(self.doc.pk, **kwargs)
with self.assertRaisesMessage(ValueError, "No parser found"):
tasks.update_document_content_maybe_archive_file(self.doc.pk, **kwargs)
_, call_kwargs = self.mock_registry.return_value.get_parser_for_file.call_args
return call_kwargs["allow_remote"]
+35 -15
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
@@ -2189,7 +2192,7 @@ class DocumentViewSet(
raise Http404
try:
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
version_label = serializer.validated_data.get("version_label")
t = int(mktime(datetime.now().timetuple()))
@@ -2200,9 +2203,7 @@ class DocumentViewSet(
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
@@ -2418,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)
@@ -2477,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",
)
@@ -2977,8 +2998,9 @@ class DocumentOperationPermissionMixin(PassUserMixin, DocumentSelectionMixin):
parser_classes = (parsers.JSONParser,)
def _queue_bulk_operation(self, method, documents, parameters, from_webui):
if "update_callback" in parameters:
raise ValueError("Unsupported bulk operation parameter: update_callback")
for parameter in ("update_callback", "parent_task_id"):
if parameter in parameters:
raise ValueError(f"Unsupported bulk operation parameter: {parameter}")
trigger_source = (
PaperlessTask.TriggerSource.WEB_UI
if from_webui
@@ -3340,7 +3362,7 @@ class PostDocumentView(GenericAPIView[Any]):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
doc_name, doc_file = serializer.validated_data.get("document")
doc_name, doc_data = serializer.validated_data.get("document")
doc_name = normalize("NFC", doc_name)
correspondent_id = serializer.validated_data.get("correspondent")
document_type_id = serializer.validated_data.get("document_type")
@@ -3360,9 +3382,7 @@ class PostDocumentView(GenericAPIView[Any]):
pathvalidate.sanitize_filename(doc_name),
)
with temp_file_path.open("wb") as scratch_file:
for chunk in doc_file.chunks():
scratch_file.write(chunk)
temp_file_path.write_bytes(doc_data)
os.utime(temp_file_path, times=(t, t))
+50 -50
View File
@@ -2,7 +2,7 @@ msgid ""
msgstr ""
"Project-Id-Version: paperless-ngx\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2026-11-25 23:54+0000\n"
"POT-Creation-Date: 2026-11-23 19:47+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:356 documents/views.py:622
#: documents/views.py:2760 paperless_mail/serialisers.py:145
#: documents/serialisers.py:2856 documents/views.py:359 documents/views.py:625
#: documents/views.py:2783 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:4841
#: documents/serialisers.py:2942 documents/views.py:4864
#, python-format
msgid "Documents not found: %(ids)s"
msgstr ""
@@ -1961,40 +1961,40 @@ msgstr ""
msgid ", "
msgstr ""
#: documents/views.py:311
#: documents/views.py:314
msgid "Specify only one of text, title_search, query, or more_like_id."
msgstr ""
#: documents/views.py:349 documents/views.py:2757
#: documents/views.py:352 documents/views.py:2780
msgid "Invalid more_like_id"
msgstr ""
#: documents/views.py:1681
#: documents/views.py:1684
msgid "Invalid AI configuration."
msgstr ""
#: documents/views.py:1692
#: documents/views.py:1695
msgid "AI backend request timed out."
msgstr ""
#: documents/views.py:1704
#: documents/views.py:1707
msgid "AI backend rejected the request. Check logs for details."
msgstr ""
#: documents/views.py:4857
#: documents/views.py:4880
#, python-format
msgid "Insufficient permissions to share document %(id)s."
msgstr ""
#: documents/views.py:4904
#: documents/views.py:4927
msgid "Bundle is already being processed."
msgstr ""
#: documents/views.py:4970
#: documents/views.py:4993
msgid "The share link bundle is still being prepared. Please try again later."
msgstr ""
#: documents/views.py:4984
#: documents/views.py:5007
msgid "The share link bundle is unavailable."
msgstr ""
@@ -2286,151 +2286,151 @@ msgstr ""
msgid "paperless application settings"
msgstr ""
#: paperless/settings/__init__.py:587
#: paperless/settings/__init__.py:582
msgid "English (US)"
msgstr ""
#: paperless/settings/__init__.py:588
#: paperless/settings/__init__.py:583
msgid "Arabic"
msgstr ""
#: paperless/settings/__init__.py:589
#: paperless/settings/__init__.py:584
msgid "Afrikaans"
msgstr ""
#: paperless/settings/__init__.py:590
#: paperless/settings/__init__.py:585
msgid "Belarusian"
msgstr ""
#: paperless/settings/__init__.py:591
#: paperless/settings/__init__.py:586
msgid "Bulgarian"
msgstr ""
#: paperless/settings/__init__.py:592
#: paperless/settings/__init__.py:587
msgid "Catalan"
msgstr ""
#: paperless/settings/__init__.py:593
#: paperless/settings/__init__.py:588
msgid "Czech"
msgstr ""
#: paperless/settings/__init__.py:594
#: paperless/settings/__init__.py:589
msgid "Danish"
msgstr ""
#: paperless/settings/__init__.py:595
#: paperless/settings/__init__.py:590
msgid "German"
msgstr ""
#: paperless/settings/__init__.py:596
#: paperless/settings/__init__.py:591
msgid "Greek"
msgstr ""
#: paperless/settings/__init__.py:597
#: paperless/settings/__init__.py:592
msgid "English (GB)"
msgstr ""
#: paperless/settings/__init__.py:598
#: paperless/settings/__init__.py:593
msgid "Spanish"
msgstr ""
#: paperless/settings/__init__.py:599
#: paperless/settings/__init__.py:594
msgid "Persian"
msgstr ""
#: paperless/settings/__init__.py:600
#: paperless/settings/__init__.py:595
msgid "Finnish"
msgstr ""
#: paperless/settings/__init__.py:601
#: paperless/settings/__init__.py:596
msgid "French"
msgstr ""
#: paperless/settings/__init__.py:602
#: paperless/settings/__init__.py:597
msgid "Hungarian"
msgstr ""
#: paperless/settings/__init__.py:603
#: paperless/settings/__init__.py:598
msgid "Indonesian"
msgstr ""
#: paperless/settings/__init__.py:604
#: paperless/settings/__init__.py:599
msgid "Italian"
msgstr ""
#: paperless/settings/__init__.py:605
#: paperless/settings/__init__.py:600
msgid "Japanese"
msgstr ""
#: paperless/settings/__init__.py:606
#: paperless/settings/__init__.py:601
msgid "Korean"
msgstr ""
#: paperless/settings/__init__.py:607
#: paperless/settings/__init__.py:602
msgid "Luxembourgish"
msgstr ""
#: paperless/settings/__init__.py:608
#: paperless/settings/__init__.py:603
msgid "Norwegian"
msgstr ""
#: paperless/settings/__init__.py:609
#: paperless/settings/__init__.py:604
msgid "Dutch"
msgstr ""
#: paperless/settings/__init__.py:610
#: paperless/settings/__init__.py:605
msgid "Polish"
msgstr ""
#: paperless/settings/__init__.py:611
#: paperless/settings/__init__.py:606
msgid "Portuguese (Brazil)"
msgstr ""
#: paperless/settings/__init__.py:612
#: paperless/settings/__init__.py:607
msgid "Portuguese"
msgstr ""
#: paperless/settings/__init__.py:613
#: paperless/settings/__init__.py:608
msgid "Romanian"
msgstr ""
#: paperless/settings/__init__.py:614
#: paperless/settings/__init__.py:609
msgid "Russian"
msgstr ""
#: paperless/settings/__init__.py:615
#: paperless/settings/__init__.py:610
msgid "Slovak"
msgstr ""
#: paperless/settings/__init__.py:616
#: paperless/settings/__init__.py:611
msgid "Slovenian"
msgstr ""
#: paperless/settings/__init__.py:617
#: paperless/settings/__init__.py:612
msgid "Serbian"
msgstr ""
#: paperless/settings/__init__.py:618
#: paperless/settings/__init__.py:613
msgid "Swedish"
msgstr ""
#: paperless/settings/__init__.py:619
#: paperless/settings/__init__.py:614
msgid "Turkish"
msgstr ""
#: paperless/settings/__init__.py:620
#: paperless/settings/__init__.py:615
msgid "Ukrainian"
msgstr ""
#: paperless/settings/__init__.py:621
#: paperless/settings/__init__.py:616
msgid "Vietnamese"
msgstr ""
#: paperless/settings/__init__.py:622
#: paperless/settings/__init__.py:617
msgid "Chinese Simplified"
msgstr ""
#: paperless/settings/__init__.py:623
#: paperless/settings/__init__.py:618
msgid "Chinese Traditional"
msgstr ""
+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,
)
-5
View File
@@ -505,11 +505,6 @@ 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")
@@ -90,15 +90,6 @@ 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:
-60
View File
@@ -1,74 +1,14 @@
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"))
-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",
[
+40 -150
View File
@@ -1,12 +1,7 @@
import json
import logging
from collections.abc import AsyncIterator
from contextlib import aclosing
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
@@ -22,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__"
@@ -113,146 +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 with aclosing(
_stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
),
) as chunks:
async for chunk in chunks:
yield chunk
yield from _stream_chat_with_documents(
query_str,
documents,
unrestricted=unrestricted,
output_language=output_language,
)
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, 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()
@@ -268,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)
@@ -295,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 -61
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,32 +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
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)
@@ -199,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,
)
@@ -265,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,
)
@@ -294,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."]
@@ -316,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])),
)
@@ -347,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])),
)
@@ -397,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),
@@ -420,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),
@@ -449,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),
@@ -485,7 +455,7 @@ class TestStreamChatRetrieval:
deleted_at=timezone.now(),
)
collect(
list(
chat.stream_chat_with_documents(
"question?",
Document.objects.filter(pk=kept.pk),
@@ -517,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
@@ -550,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(
@@ -647,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")
@@ -660,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,51 +0,0 @@
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)
@@ -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
Generated
+7 -42
View File
@@ -2562,9 +2562,7 @@ dependencies = [
{ name = "scikit-learn" },
{ name = "sentence-transformers" },
{ name = "setproctitle" },
{ 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 = "sqlite-vec" },
{ 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'" },
@@ -2723,10 +2721,7 @@ 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", 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 = "sqlite-vec", specifier = "==0.1.9" },
{ 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" },
@@ -4113,42 +4108,12 @@ asyncio = [
[[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-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'",
]
version = "0.1.9"
source = { registry = "https://pypi.org/simple" }
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-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" },
{ 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" },
]
[[package]]