Fix: Don't let database locks and file system locks deadlock (#14765)

* Fix: stop full document saves from writing file path columns

A full save() of a Document instance loaded before another process moved its file wrote the old filename back. The DB then pointed at a path that no longer existed, and recovery only worked when the recomputed path happened to match the file's real location.

Document.save() now leaves filename and archive_filename out of full saves on existing rows. Writers that own those columns opt in with write_file_paths=True or an explicit update_fields. A full save of a row deleted elsewhere now raises instead of re-inserting it.

* Fix: make the global media lock reentrant within a thread

Every caller built its own FileLock on media.lock, so code already holding it could not call into code that takes it again without blocking itself. That made it impossible to take media.lock before opening a transaction in paths that also attach files or move files inside that transaction.

media_lock() hands out one FileLock instance per path with per-thread hold counts, so a thread re-enters while other threads and processes stay excluded. All media.lock call sites now use it.

* Fix: extract document file moves out of the signal receiver

The file move receiver refreshed the caller's own instance from the database, which wiped unsaved in-memory changes. It ran on every m2m_changed action including pre_add and pre_remove, wrote modified even when nothing moved, and its no-move branch skipped trashed documents.

The move body now lives in documents.file_moves.move_files_for_document. It skips documents without a filename before taking media.lock, then takes the lock with a 300 second timeout, loads a fresh instance by pk, writes only when a filename column changes, and returns the instance. The receiver ignores reverse and pre_* m2m actions and copies just the final filename columns back onto the caller's instance.

* Fix: collect document file moves per scope and move once on exit

Each save of a document moved its files on the spot, so one logical change could move them several times, and moves could run inside another open transaction.

defer_file_moves() opens a ContextVar-backed scope. Inside it, move requests are recorded and the outermost scope moves each document once on exit, or on commit if a transaction is still open. A failing move is logged and does not stop the others. Outside any scope moves stay immediate.

* Fix: move document files once per request, after its writes commit

A tag PATCH moved files from inside the tags.set() transaction while holding the document row lock. A concurrent save holding media.lock and waiting on that row deadlocked with it, and every later save on the instance queued behind media.lock until the webserver restarted.

FileMoveMiddleware opens a file move scope around every request, in sync or async mode, so each changed document is moved once after the view returns and never while a transaction holds row locks.

* Fix: move document files once per Celery task

Tasks such as bulk_update_documents moved a document's files once for its manual post_save and again for every save its workflows made, each time taking the global media lock.

All tasks now run through FileMoveScopedTask, which opens a file move scope around the task body, including when the task raises. bulk_update_documents flushes after each document so long bulk edits still make steady progress.

* Fix: take media.lock before the archiver's transaction

The archiver updated the document row inside a transaction and then waited on media.lock. A concurrent file move holding media.lock and updating the same row could deadlock with it, and the unique archive filename was generated outside the lock from an instance loaded before the parse.

The archiver now acquires media.lock before opening its transaction, refreshes the document under the lock, and moves the archive and thumbnail inside that block, so it never waits on media.lock while holding the row.

* Fix: take media.lock before emptying the trash

Emptying the trash deleted documents inside Django's delete transaction, and the post_delete file cleanup waited on media.lock while the deleted rows were locked. A concurrent file move holding media.lock and updating one of those rows could deadlock with it.

empty_trash now holds media.lock around the delete, so the cleanup handler re-enters the lock instead of waiting while rows are locked.

* Fix: take media.lock before the consumer's storage transaction

Consuming a new version locked the root document row with select_for_update and then waited on media.lock to place the file, the same lock ordering that let concurrent saves deadlock. On MariaDB even the version row's foreign key check holds a shared lock on the root.

The consumer's storage phase now takes media.lock before opening its transaction and runs inside its own file move scope. File placement and workflow email actions inside the transaction re-enter the lock instead of waiting, and filename follow-ups run once after commit.

* Fix: keep Celery's Django task base for file move scoped tasks

Passing task_cls to Celery replaces the Django fixup's default DjangoTask, so FileMoveScopedTask, built on the plain Task, left every task without delay_on_commit. The workflow AI suggestions trigger failed with an AttributeError.

FileMoveScopedTask now subclasses DjangoTask, which only needs django.db.transaction and is safe to import before apps load. The task scope test also asserts tasks are DjangoTask instances.

* Fix: rename and retag documents one file move at a time

document_renamer sent a fake post_save per document to trigger the move, and document_retagger moved a document once for each field it assigned.

The renamer calls move_files_for_document directly for each document, so progress reflects real work. The retagger opens a file move scope per document, so each document is moved once after all of its assignments.

* Fix: move files per document during scheduled workflow runs

check_scheduled_workflows runs the workflow once per matched document inside the task-wide file move scope, so every rename it triggered was deferred to the end of the task. A long run killed by the Celery time limit would then discard all of the renames.

The task now flushes the pending file moves after each document's workflow run and websocket notification, the same way bulk_update_documents does, so renames land document by document while the scope stays open.

* Fix: place consumed files before running the post-consume script

The consumer's storage phase opens its own file move scope, which nests under the consume task's scope. Moves requested while storing the document therefore stayed pending until the task ended, and the post-consume script could be handed a path from before the move.

The consumer now flushes the pending file moves once after the storage block, outside the media lock and the transaction, and before the post-consume script runs.

* Fix: skip the thread hop for async file move scopes with nothing to move

adefer_file_moves hopped to a worker thread on every exit, even when no file move had been requested, which costs an executor round trip for most async requests.

The collector is now closed on the event loop, which touches no database, and the flush only runs through sync_to_async when something was collected. The transaction check still happens inside the flush in the sync thread. The comment above the lock-free filename precheck in move_files_for_document now gives the real reason it uses values_list(): it keeps the check off Document.global_objects.filter(), which tests patch to inject database errors and observe the mover's writes.

* Fix: return the post-move modified time from document updates

Editing a document in a way that renames its file returned a response carrying the modified time from before the move. The deferred file move runs after the response is built and bumps modified, so the stored value was newer than the one the client received. The frontend then saw a newer server modified time and showed a spurious "document was updated" prompt whose reload discarded local edits.

DocumentViewSet.update now flushes pending file moves right after saving and before reading the document back, so the response reflects the final filename and modified time.

* Trimming and simpliciation

* Fix: refresh the document after placing files, before the post-consume script

* Fix: move documents when tags change through the reverse relation

* Fix: move versions of trashed documents

* Fix: rename only root documents in document_renamer

* Improves test coverage even for the exception cases

* Fix: move documents when a tag is cleared through the reverse relation

* Fix: flush file moves before the scheduled workflow websocket notification

* Fix: move files before the bulk update websocket notification

* Fix: bump modified for documents changed by a bulk edit

* Fix: defer unscoped file moves to commit inside a transaction

* Fix: allow deferred file move callback in zone OCR reindex test

* 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.

* Fix: remove the superseded archive file when a reprocess changes its path

Reprocessing a document writes the new archive to the path its current
metadata generates and updates archive_filename, but never removed the file
the old archive_filename pointed at. Normally both are the same path. They
differ when a committed edit has not had its file move applied yet, which
deferred file moves make a real window: the new archive lands at the new path
and the old one stays on disk with no document referencing it. The deferred
move then finds the archive already at its target and only moves the original.

Delete the replaced archive, and its directory if that leaves it empty, once
the new one is in place and only when the two paths differ.

* Fix: keep the trash cleanup handler connected while any empty_trash call runs

empty_trash connects cleanup_document_deletion to post_delete before deleting
and disconnects it in a finally block. The signal is process wide and the
trash endpoint calls empty_trash directly in the web process, so overlapping
calls interfere. One caller finishing disconnects the handler while another is
still waiting for media.lock; the waiter then hard deletes its documents with no
handler attached and their files stay on disk, unreferenced.

Hold the connection with a lock protected reference count, connecting for the
first active caller and disconnecting after the last one finishes.
This commit is contained in:
Trenton H authored and GitHub committed 2026-12-01 22:30:15 +00:00
1 parent 28f6e8e58a
commit cd41640312
31 files changed
+3329 -370

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"
+3 -3
View File
@@ -743,7 +743,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
mime_type="application/pdf",
)
self.doc1.archive_filename = sample1_archive
self.doc1.save()
self.doc1.save(write_file_paths=True)
self.doc2 = Document.objects.create(
checksum="B",
title="B",
@@ -753,7 +753,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
created=date(2023, 1, 2),
)
self.doc2.archive_filename = sample2_archive
self.doc2.save()
self.doc2.save(write_file_paths=True)
self.doc3 = Document.objects.create(
checksum="C",
title="C",
@@ -778,7 +778,7 @@ class TestPDFActions(DirectoriesMixin, TestCase):
created=date(2023, 1, 3),
)
self.img_doc.archive_filename = img_doc_archive
self.img_doc.save()
self.img_doc.save(write_file_paths=True)
@staticmethod
def fake_decrypt(
+160 -1
View File
@@ -27,6 +27,10 @@ from documents.models import Document
from documents.models import DocumentType
from documents.models import StoragePath
from documents.models import Tag
from documents.models import Workflow
from documents.models import WorkflowAction
from documents.models import WorkflowActionEmail
from documents.models import WorkflowTrigger
from documents.parsers import ParseError
from documents.plugins.helpers import ProgressStatusOptions
from documents.tasks import sanity_check
@@ -38,6 +42,7 @@ from paperless_testing.factories import DocumentFactory
from paperless_testing.factories import TagFactory
from paperless_testing.factories import UserFactory
from paperless_testing.fakes.progress import FakeProgressManager
from paperless_testing.locks import record_media_lock_acquisitions
from paperless_testing.permissions import grant_object
from paperless_testing.samples import MULTI_PAGE_DIGITAL_PDF
from paperless_testing.samples import MULTI_PAGE_IMAGES_PDF
@@ -221,6 +226,160 @@ class TestConsumer(
shutil.copy(src, dst)
return dst
@mock.patch("documents.consumer.load_classifier")
def test_consume_takes_media_lock_outside_transaction(self, m) -> None:
"""
GIVEN:
- A new document to consume
WHEN:
- It is consumed
THEN:
- media.lock is acquired
- media.lock is never first acquired inside a transaction
- The document's file is in place
"""
m.return_value = MagicMock()
with record_media_lock_acquisitions() as acquisitions:
with self.get_consumer(self.get_test_file()) as consumer:
consumer.run()
self.assertTrue(acquisitions)
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
document = Document.objects.first()
assert document is not None
self.assertIsFile(document.source_path)
@mock.patch("documents.consumer.load_classifier")
def test_consume_places_file_before_post_consume_script(self, m) -> None:
"""
GIVEN:
- A new document to consume
WHEN:
- It is consumed
THEN:
- Pending file moves are flushed before the post-consume script runs
"""
m.return_value = MagicMock()
order = MagicMock()
with (
mock.patch(
"documents.consumer.flush_pending_file_moves",
order.flush,
),
mock.patch.object(
ConsumerPlugin,
"run_post_consume_script",
order.script,
),
):
with self.get_consumer(self.get_test_file()) as consumer:
consumer.run()
self.assertEqual(
[c[0] for c in order.mock_calls],
["flush", "script"],
)
@mock.patch("documents.consumer.load_classifier")
def test_consume_version_takes_media_lock_outside_transaction(self, m) -> None:
"""
GIVEN:
- An existing root document
WHEN:
- A new version of it is consumed (the root row is locked with
select_for_update inside the consumer's transaction)
THEN:
- media.lock is never first acquired inside a transaction
- The root's modified is bumped
"""
m.return_value = MagicMock()
with self.get_consumer(self.get_test_file()) as consumer:
consumer.run()
root_doc = Document.objects.first()
assert root_doc is not None
original_modified = timezone.now() - datetime.timedelta(days=1)
Document.objects.filter(pk=root_doc.pk).update(modified=original_modified)
version_file = self.get_test_file2()
status = FakeProgressManager(version_file.name, None)
overrides = DocumentMetadataOverrides(version_label="v2")
doc = ConsumableDocument(
DocumentSource.ApiUpload,
original_file=version_file,
root_document_id=root_doc.pk,
)
preflight = ConsumerPreflightPlugin(
doc,
overrides,
status, # type: ignore[arg-type]
self.dirs.scratch_dir,
"task-id",
)
preflight.setup()
preflight.run()
consumer = ConsumerPlugin(
doc,
overrides,
status, # type: ignore[arg-type]
self.dirs.scratch_dir,
"task-id",
)
consumer.setup()
try:
with record_media_lock_acquisitions() as acquisitions:
consumer.run()
finally:
consumer.cleanup()
self.assertTrue(acquisitions)
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
root_doc.refresh_from_db()
self.assertGreater(root_doc.modified, original_modified)
@override_settings(
PAPERLESS_EMAIL_HOST="localhost",
EMAIL_ENABLED=True,
PAPERLESS_URL="http://localhost:8000",
)
@mock.patch("documents.consumer.load_classifier")
@mock.patch("django.core.mail.message.EmailMessage.send", return_value=1)
def test_consumption_workflow_email_runs_under_held_lock(self, send, m) -> None:
"""
GIVEN:
- A document added workflow with an email action
WHEN:
- A document is consumed (the consumer holds media.lock while
workflows run)
THEN:
- The email action re-enters media.lock and sends without blocking
"""
m.return_value = MagicMock()
trigger = WorkflowTrigger.objects.create(
type=WorkflowTrigger.WorkflowTriggerType.DOCUMENT_ADDED,
)
email = WorkflowActionEmail.objects.create(
subject="added",
body="body",
to="someone@example.com",
include_document=True,
)
action = WorkflowAction.objects.create(
type=WorkflowAction.WorkflowActionType.EMAIL,
email=email,
)
workflow = Workflow.objects.create(name="email on add")
workflow.triggers.add(trigger)
workflow.actions.add(action)
with self.get_consumer(self.get_test_file()) as consumer:
consumer.run()
send.assert_called_once()
@override_settings(
FILENAME_FORMAT=None,
TIME_ZONE="America/Chicago",
@@ -750,7 +909,7 @@ class TestConsumer(
FILENAME_FORMAT="{correspondent}/{title}",
ARCHIVE_FILE_GENERATION="always",
)
@mock.patch("documents.signals.handlers.generate_unique_filename")
@mock.patch("documents.file_moves.generate_unique_filename")
def testFilenameHandlingUnstableFormat(self, m) -> None:
filenames = ["this", "that", "now this", "i cannot decide"]
@@ -0,0 +1,73 @@
import shutil
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
from unittest import mock
import pytest
from pytest_django.fixtures import Settings
from documents import tasks
from documents.media_lock import media_lock
from documents.models import Document
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.factories import DocumentFactory
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
def _trashed_document(dirs: PaperlessDirs, title: str) -> tuple[Document, Path]:
# The title-only filename format keeps the generated filename equal to the
# stored one, so creating the document does not move the file.
doc = DocumentFactory(
title=title,
filename=f"{title}.pdf",
mime_type="application/pdf",
)
original = dirs.originals_dir / f"{title}.pdf"
shutil.copy(SIMPLE_DIGITAL_PDF, original)
doc.delete()
return doc, original
@pytest.mark.django_db
class TestEmptyTrashOverlappingCalls:
def test_call_that_waits_for_the_lock_still_removes_its_files(
self,
paperless_dirs: PaperlessDirs,
settings: Settings,
) -> None:
"""
GIVEN:
- Two trashed documents with files on disk
- A second empty_trash call that runs to completion while the first
is waiting for media.lock, as happens with two overlapping
requests in one process
WHEN:
- The first call gets the lock and deletes its document
THEN:
- Both documents are gone from the database
- Both documents' files are gone from disk, not just the files of
the call that finished first
"""
settings.FILENAME_FORMAT = "{{ title }}"
first, first_original = _trashed_document(paperless_dirs, "first")
second, second_original = _trashed_document(paperless_dirs, "second")
assert first_original.is_file()
assert second_original.is_file()
interleaved = False
@contextmanager
def lock_after_other_call(*args, **kwargs) -> Iterator[None]:
nonlocal interleaved
if not interleaved:
interleaved = True
tasks.empty_trash(doc_ids=[second.pk])
with media_lock(*args, **kwargs):
yield
with mock.patch("documents.tasks.media_lock", lock_after_other_call):
tasks.empty_trash(doc_ids=[first.pk])
assert not Document.global_objects.filter(pk__in=[first.pk, second.pk]).exists()
assert not second_original.exists()
assert not first_original.exists()
+23 -25
View File
@@ -92,7 +92,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated
self.assertEqual(document.filename, Path("none/none.pdf"))
document.save()
document.save(write_file_paths=True)
# test that creating dirs for the source_path creates the correct directory
create_source_path_directory(document.source_path)
@@ -190,7 +190,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Set a correspondent and save the document
document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
document.save()
document.save(write_file_paths=True)
# Check proper handling of files
self.assertIsFile(
@@ -232,7 +232,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
disable_auditlog(),
):
m.side_effect = DatabaseError()
document.save()
document.save(write_file_paths=True)
# Check proper handling of files
self.assertIsFile(document.source_path)
@@ -336,7 +336,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated
document.filename = generate_filename(document)
document.save()
document.save(write_file_paths=True)
self.assertEqual(document.filename, "none/none.pdf")
create_source_path_directory(document.source_path)
@@ -362,7 +362,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated
document.filename = generate_filename(document)
document.save()
document.save(write_file_paths=True)
self.assertEqual(document.filename, "none/none.pdf")
create_source_path_directory(document.source_path)
@@ -385,7 +385,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
document.save()
document.filename = generate_filename(document)
document.save()
document.save(write_file_paths=True)
create_source_path_directory(document.source_path)
Path(document.source_path).touch()
document.delete()
@@ -421,7 +421,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Set a correspondent and save the document
document.correspondent = Correspondent.objects.get_or_create(name="test")[0]
document.save()
document.save(write_file_paths=True)
# Check proper handling of files
self.assertIsDir(settings.ORIGINALS_DIR / "test")
@@ -476,7 +476,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
def test_filename_relative(self) -> None:
doc = Document.objects.create(title="doc1", mime_type="application/pdf")
doc.filename = generate_filename(doc)
doc.save()
doc.save(write_file_paths=True)
self.assertEqual(
doc.source_path,
@@ -532,7 +532,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
# Ensure that filename is properly generated
document.filename = generate_filename(document)
document.save()
document.save(write_file_paths=True)
self.assertEqual(document.filename, "none/none/none.pdf")
create_source_path_directory(document.source_path)
Path(document.source_path).touch()
@@ -620,13 +620,13 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
Path(document.source_path).touch()
Path(document2.source_path).touch()
document.filename = "0000001.pdf"
document.save()
document.save(write_file_paths=True)
self.assertIsFile(document.source_path)
self.assertEqual(document.filename, "qwe.pdf")
document2.filename = "0000002.pdf"
document2.save()
document2.save(write_file_paths=True)
self.assertIsFile(document.source_path)
self.assertEqual(document2.filename, "qwe_01.pdf")
@@ -656,19 +656,17 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
self.assertEqual(document2.filename, "qwe.pdf")
@override_settings(FILENAME_FORMAT="{title}")
@mock.patch("documents.signals.handlers.Document.objects.filter")
@mock.patch("documents.signals.handlers.shutil.move")
@mock.patch("documents.file_moves.Document.global_objects.filter")
@mock.patch("documents.file_moves.shutil.move")
def test_no_move_only_save(self, mock_move, mock_filter) -> None:
"""
GIVEN:
- A document with a filename
- The document is saved
- The filename is not changed
WHEN:
- The document is saved
- The document is saved without a change that affects its path
THEN:
- The document modified date is updated
- The document is not moved
- The document modified date is updated by the save itself
- The file is not moved and the mover writes nothing
"""
with disable_auditlog():
doc = Document.objects.create(
@@ -686,7 +684,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
doc.save()
doc.refresh_from_db()
mock_filter.assert_called()
mock_filter.assert_not_called()
self.assertNotEqual(original_modified, doc.modified)
mock_move.assert_not_called()
@@ -694,7 +692,7 @@ class TestFileHandling(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
FILENAME_FORMAT="{{title}}_{{custom_fields|get_cf_value('test')}}",
CELERY_TASK_ALWAYS_EAGER=True,
)
@mock.patch("documents.signals.handlers.update_filename_and_move_files")
@mock.patch("documents.signals.handlers.move_files_for_document")
def test_select_cf_updated(self, m) -> None:
"""
GIVEN:
@@ -2045,7 +2043,7 @@ class TestCustomFieldFilenameUpdates(
Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True)
Path(self.doc.source_path).touch()
with mock.patch("documents.signals.handlers.generate_unique_filename") as m:
with mock.patch("documents.file_moves.generate_unique_filename") as m:
m.side_effect = generate_unique_filename
self.cfi.value_text = "updated"
self.cfi.save()
@@ -2067,7 +2065,7 @@ class TestCustomFieldFilenameUpdates(
Path(self.doc.source_path).parent.mkdir(parents=True, exist_ok=True)
Path(self.doc.source_path).touch()
with mock.patch("documents.signals.handlers.generate_unique_filename") as m:
with mock.patch("documents.file_moves.generate_unique_filename") as m:
m.side_effect = generate_unique_filename
self.cfi.value_text = "updated"
self.cfi.save()
@@ -2145,7 +2143,7 @@ def test_refresh_failure_surfaces_database_error(
GIVEN:
- A document with a stored filename
WHEN:
- Saving it triggers a filename update and refreshing it from the database fails
- Saving it triggers a filename update and loading it from the database fails
THEN:
- The database error is raised, not an unbound variable error from the rollback
"""
@@ -2153,8 +2151,8 @@ def test_refresh_failure_surfaces_database_error(
with (
mock.patch.object(
Document,
"refresh_from_db",
Document.global_objects,
"get",
side_effect=DatabaseError("database is locked"),
),
pytest.raises(DatabaseError, match="database is locked"),
File diff suppressed because it is too large. Load diff
+61 -1
View File
@@ -18,11 +18,13 @@ if TYPE_CHECKING:
from pytest_mock import MockerFixture
from documents.file_handling import generate_filename
from documents.file_moves import move_files_for_document
from documents.models import Document
from documents.tasks import update_document_content_maybe_archive_file
from paperless_testing.assertions import FileSystemAssertsMixin
from paperless_testing.dirs import DirectoriesMixin
from paperless_testing.factories import DocumentFactory
from paperless_testing.locks import record_media_lock_acquisitions
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
sample_file: Path = SIMPLE_DIGITAL_PDF
@@ -63,6 +65,28 @@ class TestArchiver(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
self.assertTrue(filecmp.cmp(sample_file, doc.source_path))
self.assertEqual(doc.archive_filename, "none/A.pdf")
def test_handle_document_takes_media_lock_outside_transaction(self) -> None:
"""
GIVEN:
- A document whose archive version is being generated
WHEN:
- update_document_content_maybe_archive_file runs
THEN:
- media.lock is acquired
- media.lock is never first acquired while a transaction holds the
document row
"""
doc = self.make_models()
shutil.copy(sample_file, Path(self.dirs.originals_dir) / f"{doc.id:07}.pdf")
with record_media_lock_acquisitions() as acquisitions:
update_document_content_maybe_archive_file(doc.pk)
self.assertTrue(acquisitions)
self.assertFalse(any(a.in_user_transaction for a in acquisitions))
doc.refresh_from_db()
self.assertIsFile(doc.archive_path)
def test_unknown_mime_type(self) -> None:
doc = self.make_models()
doc.mime_type = "sdgfh"
@@ -236,7 +260,7 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
doc = Document.objects.create(title="test", mime_type="image/jpeg")
doc.filename = generate_filename(doc)
doc.archive_filename = generate_filename(doc, archive_filename=True)
doc.save()
doc.save(write_file_paths=True)
Path(doc.source_path).touch()
Path(doc.archive_path).touch()
@@ -253,6 +277,42 @@ class TestRenamer(DirectoriesMixin, FileSystemAssertsMixin, TestCase):
self.assertIsFile(doc2.source_path)
self.assertIsFile(doc2.archive_path)
@override_settings(FILENAME_FORMAT="")
def test_rename_moves_each_document_by_direct_call(self) -> None:
"""
GIVEN:
- Two documents whose filename format changed
WHEN:
- document_renamer runs
THEN:
- move_files_for_document is called once per document
- Both files are at their new paths
"""
docs = []
for title in ("first", "second"):
doc = Document.objects.create(title=title, mime_type="image/jpeg")
doc.filename = generate_filename(doc)
doc.save(write_file_paths=True)
Path(doc.source_path).touch()
docs.append(doc)
with (
override_settings(FILENAME_FORMAT="{title}"),
mock.patch(
"documents.management.commands.document_renamer.move_files_for_document",
wraps=move_files_for_document,
) as mover,
):
call_command("document_renamer", skip_checks=True)
self.assertCountEqual(
[c.args[0] for c in mover.call_args_list],
[d.pk for d in docs],
)
for doc in docs:
doc.refresh_from_db()
self.assertIsFile(doc.source_path)
@pytest.mark.management
class TestCreateClassifier:
@@ -4,10 +4,13 @@ Tests for the document_retagger management command.
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
from django.core.management import call_command
from django.core.management.base import CommandError
from documents.file_moves import _active_collector
from documents.models import Correspondent
from documents.models import Document
from documents.models import DocumentType
@@ -21,6 +24,12 @@ from paperless_testing.factories import DocumentTypeFactory
from paperless_testing.factories import StoragePathFactory
from paperless_testing.factories import TagFactory
if TYPE_CHECKING:
from pytest_django.fixtures import Settings
from pytest_mock import MockerFixture
from paperless_testing.dirs import PaperlessDirs
# ---------------------------------------------------------------------------
# Module-level type aliases
# ---------------------------------------------------------------------------
@@ -484,3 +493,69 @@ class TestRetaggerEdgeCases(DirectoriesMixin):
assert d_first.tags.count() == 0
assert d_unrelated.tags.count() == 2
@pytest.mark.management
@pytest.mark.django_db
class TestRetaggerFileMoves:
def test_each_document_is_processed_in_its_own_scope(
self,
paperless_dirs: PaperlessDirs,
settings: Settings,
mocker: MockerFixture,
) -> None:
"""
GIVEN:
- Two documents and a filename format using the correspondent
- A classifier suggestion assigning a correspondent to each
WHEN:
- document_retagger runs with --correspondent
THEN:
- Each document is processed inside an open file move scope
- When the second document is processed, the first one's file has
already moved
- Both files end at their final paths
"""
settings.FILENAME_FORMAT = "{correspondent}/{title}"
(paperless_dirs.originals_dir / "none").mkdir(exist_ok=True)
for title in ("first", "second"):
(paperless_dirs.originals_dir / "none" / f"{title}.pdf").write_bytes(b"x")
DocumentFactory(
title=title,
filename=f"none/{title}.pdf",
mime_type="application/pdf",
)
correspondent = CorrespondentFactory(name="acme")
processed: list[Document] = []
scope_open: list[bool] = []
seen_first_moved: list[bool] = []
def fake_set_correspondent(sender, document, **kwargs):
scope_open.append(_active_collector.get() is not None)
# Order-agnostic: on the second call, check the first one's file.
if processed:
first = processed[0]
seen_first_moved.append(
(
paperless_dirs.originals_dir / "acme" / f"{first.title}.pdf"
).is_file(),
)
processed.append(document)
document.correspondent = correspondent
document.save(update_fields=("correspondent",))
return correspondent
mocker.patch(
"documents.management.commands.document_retagger.load_classifier",
)
mocker.patch(
"documents.management.commands.document_retagger.set_correspondent",
side_effect=fake_set_correspondent,
)
call_command("document_retagger", "--correspondent", skip_checks=True)
assert scope_open == [True, True]
assert seen_first_moved == [True]
for title in ("first", "second"):
assert (paperless_dirs.originals_dir / "acme" / f"{title}.pdf").is_file()
+121
View File
@@ -0,0 +1,121 @@
from __future__ import annotations
import threading
from typing import TYPE_CHECKING
import pytest
from django.db import transaction
from filelock import Timeout
from documents.file_moves import in_user_transaction
from documents.media_lock import media_lock
from paperless_testing.locks import record_media_lock_acquisitions
if TYPE_CHECKING:
from paperless_testing.dirs import PaperlessDirs
@pytest.mark.usefixtures("paperless_dirs")
class TestMediaLock:
def test_same_thread_reenters_without_blocking(self) -> None:
"""
GIVEN:
- media.lock held by the current thread
WHEN:
- The same thread acquires it again with a zero timeout
THEN:
- The nested acquisition succeeds immediately
"""
with media_lock(), media_lock(timeout=0):
pass
def test_other_thread_is_excluded(self) -> None:
"""
GIVEN:
- media.lock held by the current thread
WHEN:
- Another thread tries to acquire it with a short timeout
THEN:
- The other thread times out
- After release, the other thread can acquire it
"""
outcomes: list[str] = []
def try_acquire() -> None:
try:
with media_lock(timeout=0.2):
outcomes.append("acquired")
except Timeout:
outcomes.append("timeout")
with media_lock():
worker = threading.Thread(target=try_acquire)
worker.start()
worker.join()
worker = threading.Thread(target=try_acquire)
worker.start()
worker.join()
assert outcomes == ["timeout", "acquired"]
def test_lock_file_is_the_configured_path(
self,
paperless_dirs: PaperlessDirs,
) -> None:
"""
GIVEN:
- The test's media directory layout
WHEN:
- media.lock is acquired
THEN:
- The lock file is created at settings.MEDIA_LOCK
"""
with media_lock():
assert paperless_dirs.media_lock.exists()
@pytest.mark.django_db
class TestInUserTransaction:
def test_false_inside_test_case_wrapper(self) -> None:
"""
GIVEN:
- The transaction pytest-django wraps around the test
WHEN:
- in_user_transaction is called
THEN:
- It returns False
"""
assert in_user_transaction() is False
def test_true_inside_atomic(self) -> None:
"""
GIVEN:
- An atomic block opened by code under test
WHEN:
- in_user_transaction is called inside it
THEN:
- It returns True
"""
with transaction.atomic():
assert in_user_transaction() is True
@pytest.mark.django_db
@pytest.mark.usefixtures("paperless_dirs")
class TestRecordMediaLockAcquisitions:
def test_records_only_first_acquisitions(self) -> None:
"""
GIVEN:
- Nested media.lock acquisitions, the outer one inside a transaction
WHEN:
- They are recorded
THEN:
- Only the outer, first acquisition is recorded, flagged as inside
a transaction
"""
with record_media_lock_acquisitions() as acquisitions:
with transaction.atomic(), media_lock(), media_lock():
pass
assert [a.in_user_transaction for a in acquisitions] == [True]
+101
View File
@@ -1,4 +1,7 @@
import pytest
from django.db import DatabaseError
from django.db import models
from django.db import transaction
from documents.models import Correspondent
from documents.models import Document
@@ -22,3 +25,101 @@ class TestDocument:
assert Correspondent.objects.count() == 0
assert Document.objects.count() == 1
assert Document.objects.first().correspondent is None
@pytest.mark.django_db
@pytest.mark.usefixtures("paperless_dirs")
class TestDocumentFilePathWrites:
def test_full_save_does_not_write_file_paths(self) -> None:
"""
GIVEN:
- A document whose filename columns were changed in the DB after
an instance was loaded
WHEN:
- The stale instance is saved without update_fields
THEN:
- The DB filename columns keep the newer values
- Other fields from the stale instance are written
"""
doc = DocumentFactory(filename="old.pdf", archive_filename="old.pdf")
stale = Document.objects.get(pk=doc.pk)
Document.objects.filter(pk=doc.pk).update(
filename="new.pdf",
archive_filename="new-archive.pdf",
)
stale.title = "changed"
stale.save()
doc.refresh_from_db()
assert doc.filename == "new.pdf"
assert doc.archive_filename == "new-archive.pdf"
assert doc.title == "changed"
@pytest.mark.parametrize(
"save_kwargs",
[
pytest.param({"write_file_paths": True}, id="write-file-paths"),
pytest.param(
{"update_fields": ["filename", "archive_filename"]},
id="explicit-update-fields",
),
],
)
def test_opt_in_writes_file_paths(self, save_kwargs: dict[str, object]) -> None:
"""
GIVEN:
- An existing document
WHEN:
- Its filename columns are changed in memory and saved with an
explicit opt in
THEN:
- The DB filename columns are updated
"""
doc = DocumentFactory(filename="old.pdf", archive_filename="old.pdf")
doc.filename = "new.pdf"
doc.archive_filename = "new.pdf"
doc.save(**save_kwargs)
doc.refresh_from_db()
assert doc.filename == "new.pdf"
assert doc.archive_filename == "new.pdf"
def test_creation_writes_file_paths(self) -> None:
"""
GIVEN:
- A new, unsaved document with filename columns set
WHEN:
- It is saved
THEN:
- The filename columns are written
"""
doc = DocumentFactory.build(filename="a.pdf", archive_filename="b.pdf")
doc.save()
doc.refresh_from_db()
assert doc.filename == "a.pdf"
assert doc.archive_filename == "b.pdf"
def test_full_save_of_deleted_row_raises(self) -> None:
"""
GIVEN:
- An instance whose row was hard-deleted elsewhere
WHEN:
- The instance is saved without update_fields
THEN:
- A DatabaseError is raised instead of re-inserting the row
"""
doc = DocumentFactory()
stale = Document.objects.get(pk=doc.pk)
# A plain QuerySet bypasses the soft-delete manager, so the row is
# really gone (as after emptying the trash).
models.QuerySet(model=Document).filter(pk=doc.pk).delete()
# The savepoint keeps the failed UPDATE from poisoning the test transaction.
with pytest.raises(DatabaseError), transaction.atomic():
stale.save()
assert not Document.global_objects.filter(pk=doc.pk).exists()
@@ -0,0 +1,107 @@
import shutil
from pathlib import Path
import pytest
from pytest_django.fixtures import Settings
from documents import tasks
from documents.models import Correspondent
from documents.models import Document
from documents.utils import compute_checksum
from paperless_testing.dirs import PaperlessDirs
from paperless_testing.samples import SIMPLE_DIGITAL_PDF
@pytest.mark.django_db
class TestReprocessArchiveCleanup:
def test_reprocess_with_pending_rename_leaves_one_archive(
self,
paperless_dirs: PaperlessDirs,
settings: Settings,
) -> None:
"""
GIVEN:
- A document whose committed metadata already generates a different
filename than the one its files still have, because its file move
has not run yet
WHEN:
- The document is reprocessed and a new archive file is produced
THEN:
- Exactly one archive file remains, the one the document points at
- The superseded archive file is not left behind
"""
settings.FILENAME_FORMAT = "{{ correspondent }}/{{ title }}"
settings.ARCHIVE_FILE_GENERATION = "always"
old_correspondent = Correspondent.objects.create(name="old")
new_correspondent = Correspondent.objects.create(name="new")
original = paperless_dirs.originals_dir / "old" / "t.pdf"
archive = paperless_dirs.archive_dir / "old" / "t.pdf"
for path in (original, archive):
path.parent.mkdir(parents=True)
shutil.copy(SIMPLE_DIGITAL_PDF, path)
doc = Document.objects.create(
title="t",
content="my document",
checksum=compute_checksum(original),
archive_checksum="stale",
filename="old/t.pdf",
archive_filename="old/t.pdf",
mime_type="application/pdf",
correspondent=old_correspondent,
)
# A queryset update sends no signals, so no file move is requested, as
# with a committed edit whose deferred move has not run yet.
Document.objects.filter(pk=doc.pk).update(correspondent=new_correspondent)
tasks.update_document_content_maybe_archive_file(doc.pk)
refreshed = Document.objects.get(pk=doc.pk)
archives = sorted(
p.relative_to(paperless_dirs.archive_dir).as_posix()
for p in Path(paperless_dirs.archive_dir).rglob("*.pdf")
)
assert archives == [refreshed.archive_filename]
assert refreshed.archive_filename == "new/t.pdf"
assert (paperless_dirs.originals_dir / refreshed.filename).is_file()
def test_reprocess_without_pending_rename_keeps_archive_in_place(
self,
paperless_dirs: PaperlessDirs,
settings: Settings,
) -> None:
"""
GIVEN:
- A document whose files already match its generated filename
WHEN:
- The document is reprocessed and a new archive file is produced
THEN:
- The new archive replaces the old one at the same path and is not
deleted as a superseded file
"""
settings.FILENAME_FORMAT = "{{ correspondent }}/{{ title }}"
settings.ARCHIVE_FILE_GENERATION = "always"
correspondent = Correspondent.objects.create(name="same")
original = paperless_dirs.originals_dir / "same" / "t.pdf"
archive = paperless_dirs.archive_dir / "same" / "t.pdf"
for path in (original, archive):
path.parent.mkdir(parents=True)
shutil.copy(SIMPLE_DIGITAL_PDF, path)
doc = Document.objects.create(
title="t",
content="my document",
checksum=compute_checksum(original),
archive_checksum="stale",
filename="same/t.pdf",
archive_filename="same/t.pdf",
mime_type="application/pdf",
correspondent=correspondent,
)
tasks.update_document_content_maybe_archive_file(doc.pk)
refreshed = Document.objects.get(pk=doc.pk)
assert refreshed.archive_filename == "same/t.pdf"
assert archive.is_file()
assert compute_checksum(archive) == refreshed.archive_checksum
+2 -2
View File
@@ -129,7 +129,7 @@ class TestCheckSanityOriginal:
class TestCheckSanityArchive:
def test_checksum_without_filename(self, sample_doc: Document) -> None:
sample_doc.archive_filename = None
sample_doc.save()
sample_doc.save(write_file_paths=True)
messages = check_sanity()
assert messages.has_error
assert any(
@@ -182,7 +182,7 @@ class TestCheckSanityArchive:
Path(sample_doc.archive_path).unlink()
sample_doc.archive_checksum = None
sample_doc.archive_filename = None
sample_doc.save()
sample_doc.save(write_file_paths=True)
messages = check_sanity()
assert not messages.has_error
@@ -366,7 +366,7 @@ class ShareLinkBundleBuildTaskTests(DirectoriesMixin, APITestCase):
def _write_document_file(self, *, archive: bool, content: bytes) -> Path:
if archive:
self.document.archive_filename = f"{self.document.pk:07}.pdf"
self.document.save()
self.document.save(write_file_paths=True)
path = self.document.archive_path
assert path is not None
else:
+6 -3
View File
@@ -887,8 +887,8 @@ class TestSavedZoneExtraction:
WHEN:
- Zone extraction runs
THEN:
- No on-commit callbacks are registered; finishing is left to the
caller
- The only on-commit callback is the deferred file move; reindexing
and other finishing is left to the caller
"""
make_zone(template, "Title")
mock_zone_ocr_run.return_value = subprocess.CompletedProcess(
@@ -900,7 +900,10 @@ class TestSavedZoneExtraction:
with django_capture_on_commit_callbacks() as callbacks:
run_zone_extraction(document, templates=[template])
assert callbacks == []
assert all(
callback.__qualname__.startswith("request_file_move")
for callback in callbacks
)
def test_document_run_renders_each_page_once_across_templates(
self,