Fix: return 404 instead of 500 when a document is trashed during its own update

DocumentViewSet.update saves the change and then re-reads the document through
the default manager, which excludes soft deleted rows. A concurrent request
that moved the document to the trash in between made that read raise
DoesNotExist, so the client got a 500 for a document that no longer exists.

Raise Http404 instead, the same answer get_object() gives when the document
is already trashed at the start of the request. The committed change is kept.

Found while hammering the API with concurrent PATCH and delete requests.
This commit is contained in:
stumpylog committed 2026-11-30 21:14:22 -08:00
1 parent 8d866bbf32
commit c8ce651111
2 files changed
+49 -1

No files matched your search

@@ -0,0 +1,44 @@
from unittest import mock
import pytest
from rest_framework import status
from rest_framework.test import APIClient
from documents.models import Document
from paperless_testing.factories import DocumentFactory
@pytest.mark.django_db
class TestDocumentUpdateConcurrentDelete:
def test_patch_of_document_trashed_mid_request_returns_404(
self,
admin_client: APIClient,
) -> None:
"""
GIVEN:
- A document that another request moves to the trash after this
request has saved its changes, but before it re-reads the document
WHEN:
- The document is updated through the API
THEN:
- The response is a 404, not a server error
- The committed change is not lost
"""
doc = DocumentFactory(title="before")
def trash_concurrently() -> None:
Document.objects.get(pk=doc.pk).delete()
with mock.patch(
"documents.views.flush_pending_file_moves",
side_effect=trash_concurrently,
):
response = admin_client.patch(
f"/api/documents/{doc.pk}/",
{"title": "after"},
format="json",
)
assert response.status_code == status.HTTP_404_NOT_FOUND
assert Document.deleted_objects.filter(pk=doc.pk).exists()
assert Document.global_objects.get(pk=doc.pk).title == "after"
+5 -1
View File
@@ -1327,7 +1327,11 @@ class DocumentViewSet(
)
content_doc.save(update_fields=["content", "modified"])
refreshed_doc = self.get_queryset().get(pk=root_doc.pk)
try:
refreshed_doc = self.get_queryset().get(pk=root_doc.pk)
except Document.DoesNotExist:
# Trashed by a concurrent request after our write committed
raise Http404
response_data = self.get_serializer(refreshed_doc).data
if "version" in request.query_params and "content" in response_data:
response_data["content"] = content_doc.content