Fix: defer unscoped file moves to commit inside a transaction

This commit is contained in:
Trenton H committed 2026-12-01 08:08:03 -08:00
1 parent 79d1b84306
commit 4231cdc63e
2 files changed
+56 -3

No files matched your search

+12 -3
View File
@@ -432,14 +432,23 @@ def request_file_move(document: Document) -> None:
Ask for the document's files to follow its committed state.
Inside an open scope the request is recorded and performed when the scope
ends. Otherwise the move happens now and only the final filename columns
are copied onto the caller's instance, so source_path is current after
save() while other in-memory fields are left alone.
ends. Inside a user transaction with no scope it runs on commit. Otherwise
the move happens now and only the final filename columns are copied onto
the caller's instance, so source_path is current after save() while other
in-memory fields are left alone.
"""
collector = _active_collector.get()
if collector is not None and collector.add(document.pk):
return
if in_user_transaction():
# An enclosing transaction can still roll back the filename columns,
# and the move would take media.lock while it holds document rows.
# Wait for the commit, so the caller's instance keeps its old paths.
pk = document.pk
transaction.on_commit(lambda: _flush([pk]))
return
moved = move_files_for_document(document.pk)
if moved is not None:
document.filename = moved.filename
+44
View File
@@ -667,6 +667,50 @@ class TestRequestFileMoveWithoutScope:
assert document.correspondent == unsaved
assert document.title == "original"
def test_inside_atomic_waits_for_commit(
self,
document: Document,
paperless_dirs: PaperlessDirs,
django_capture_on_commit_callbacks: OnCommitCapture,
) -> None:
"""
GIVEN:
- No file move scope is open, but a transaction is
WHEN:
- A save inside the transaction requests a move
THEN:
- Nothing moves until the transaction commits
"""
with django_capture_on_commit_callbacks(execute=True):
with transaction.atomic():
document.title = "renamed"
document.save()
assert (paperless_dirs.originals_dir / "original.pdf").is_file()
assert (paperless_dirs.originals_dir / "renamed.pdf").is_file()
def test_inside_rolled_back_atomic_moves_nothing(
self,
document: Document,
paperless_dirs: PaperlessDirs,
django_capture_on_commit_callbacks: OnCommitCapture,
) -> None:
"""
GIVEN:
- No file move scope is open, but a transaction is
WHEN:
- The transaction rolls back after a save requested a move
THEN:
- The file stays at its original path
"""
with django_capture_on_commit_callbacks(execute=True):
with pytest.raises(RuntimeError), transaction.atomic():
document.title = "renamed"
document.save()
raise RuntimeError
assert (paperless_dirs.originals_dir / "original.pdf").is_file()
@pytest.mark.django_db
class TestReceiver: