Skip to content

fix(filesystem backend): write result files atomically - #10703

Open
simpleqt wants to merge 6 commits into
celery:mainfrom
simpleqt:fix/filesystem-backend-atomic-set
Open

simpleqt wants to merge 6 commits into
celery:mainfrom
simpleqt:fix/filesystem-backend-atomic-set

Conversation

@simpleqt

@simpleqt simpleqt commented Sep 24, 2026 •

Copy link
Copy Markdown

Problem

FilesystemBackend.set writes results non-atomically:

def set(self, key, value):
    with self.open(self._filename(key), 'wb') as outfile:
        outfile.write(ensure_bytes(value))

open(..., 'wb') truncates the file before writing, with no temp-file/rename and no locking. Concurrent readers — AsyncResult.get polling, get_many/join_native, and _store_result's own pre-write read (base.py: current_meta = self._get_task_meta_for(task_id)) — can land in the truncated-but-not-yet-complete window and get a torn payload, which then fails decode_result:

payload bytes: 512143
reads: 302 errors: 262
DecodeError: Unterminated string starting at: line 1 column 33 (char 32)

(writer thread looping set(key, 512KB meta), reader thread looping get(key) + decode — 262 of 302 reads saw a torn file). get only swallows FileNotFoundError, not partial writes. So a task can succeed while consumers of its result intermittently blow up on deserialization.

Fix

Write to a temporary file in the same directory (created through the injectable self.open() with a uuid() name and a celery-result- prefix, type-matched because result paths may be bytes), then os.replace() it into place — readers now see either the old or the new complete file, never a partial one. os.replace is atomic on POSIX and Windows; the temp file is removed if the write fails. On Windows, os.replace() is retried briefly on PermissionError, since a reader holding the destination open (CPython opens files without FILE_SHARE_DELETE) would otherwise turn a harmless concurrent read into a failed store_result.

Notes on semantics:

  • New files get the umask-derived default mode; overwrites preserve the existing file's mode (stat + chmod).
  • The rename replaces the destination rather than writing through it: a symlink (or different ownership/ACLs) on the result path is not followed, and the link target is left untouched.
  • cleanup() now also removes celery-result-*.tmp files older than expires, so temp files orphaned by a killed process don't accumulate forever, and its stat()/unlink() pairs tolerate files vanishing in a concurrent forget()/cleanup() pass.

Test plan

t/unit/backends/test_filesystem.py:

  • test_concurrent_readers_never_see_torn_payload: reader thread decodes while 50 sequential 100KB writes happen. Fails on main (torn DecodeError), passes with the fix (red/green verified).
  • test_set_is_atomic_no_tempfile_left_behind: set/get roundtrip plus no celery-result-* temp residue.
  • test_cleanup_removes_stale_temp_files: a stale orphaned .tmp is removed by cleanup(), a fresh one survives.
  • test_set_retries_replace_on_permission_error / test_set_raises_after_replace_retries_exhausted: the Windows retry path succeeds after transient PermissionErrors and still raises (with temp cleanup) once retries are exhausted.

Existing 22 tests unchanged and passing; flake8 (repo config) clean.

Copilot AI lite review requested due to automatic review settings September 24, 2026 15:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codecov

codecov Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.92683% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.97%. Comparing base (e1dba84) to head (6327a8f).
⚠️ Report is 46 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/filesystem.py 82.92% 5 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10703      +/-   ##
==========================================
+ Coverage   89.52%   89.97%   +0.44%     
==========================================
  Files         153      153              
  Lines       20419    20973     +554     
  Branches     2434     2521      +87     
==========================================
+ Hits        18281    18870     +589     
+ Misses       1837     1801      -36     
- Partials      301      302       +1     
Flag Coverage Δ
unittests 89.95% <82.92%> (+0.44%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@auvipy
auvipy self-requested a review September 24, 2026 15:47
@auvipy auvipy added this to the 5.7.0 milestone Sep 24, 2026

@auvipy auvipy left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

the code coverage might be improved @MehrazRumman what do you think?

@ege-arhan ege-arhan left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Atomic write is the right fix for torn reads, but the new path changes result-file permissions: tempfile.mkstemp creates the temp file with mode 0o600, and os.replace(tmp_name, filename) keeps that mode. The old code (self.open(filename, 'wb')) preserved an existing file's mode and gave new files the umask-based default (typically 0o644).

Repro sketch:

import os, stat
tb.set(key, b'{"ok": true}')
print(oct(stat.S_IMODE(os.stat(tb._filename(key)).st_mode)))
# before: 0o644 (or the pre-existing file's mode, preserved across overwrites)
# after this PR: 0o600 on every write, even overwrites of a 0644 file

If locked-down result files are intended, it deserves a changelog note since existing deployments may serve/share these files under the old mode. Otherwise, consider copying the previous file's mode (when it exists) onto the temp file before replace, e.g. via os.chmod(tmp_name, ...) from os.stat(filename), falling back to the umask default for new files.

Two smaller notes on the same hunk:

  • set() now bypasses the injectable self.open (uses os.fdopen/os.replace directly), so backends/tests overriding open no longer intercept writes.
  • In the except BaseException handler, os.unlink(tmp_name) can itself raise FileNotFoundError (e.g. replace succeeded but a later line failed — not the case today, but any future statement added after os.replace inside the try would mask the original error). A guarded cleanup would be more robust.

tempfile.mkstemp creates the temp file with mode 0o600, and os.replace
keeps it, so every result file ended up 0o600 regardless of umask or a
pre-existing file's mode. Write the temp file through the injectable
self.open (umask-derived default mode like plain open('wb')), copy the
previous file's mode onto it before replace for overwrites, and guard
the error-path unlink against FileNotFoundError.

Signed-off-by: simpleqt <[email protected]>
@simpleqt

This comment was marked as spam.

@auvipy

auvipy commented Sep 27, 2026

Copy link
Copy Markdown
Member

@MehrazRumman

@MehrazRumman MehrazRumman left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @simpleqt, and thanks @ege-arhan for the earlier review. The permission and injectable-open points look properly addressed now.

The fix works

I ran a reader thread doing get() + decode() in a loop while the main thread called set() 300 times on the same key with a ~100 KB payload:

torn/undecodable reads leftover .tmp files
main 748 none
this PR 0 none

So the torn-read race is real, and write-to-temp + os.replace() fixes it. Other things that look right:

  • The temp file is in the same directory, so os.replace() stays a same-filesystem, atomic rename.
  • str and bytes paths are both handled.
  • New files get the umask default because they go through self.open, and an existing file's mode is kept via stat + chmod, covered by test_set_preserves_file_mode_and_umask_default.
  • The temp file is removed on any failure, including BaseException, and a missing temp file during that cleanup is tolerated.

Worth addressing

  1. cleanup() never removes an orphaned temp file. If the process is killed (SIGKILL, OOM, power loss) between the write and os.replace(), a celery-result-<uuid>.tmp is left behind. cleanup() only considers names starting with the task/group/chord key prefixes, so these files stay forever. Since cleanup() already walks the directory, it could also delete celery-result-*.tmp files older than expires. That's small, and it keeps a long-running shared result directory clean.

  2. Windows (and possibly SMB mounts): os.replace() can fail while a reader has the file open. CPython on Windows opens files without FILE_SHARE_DELETE, so replacing a result file that another process is reading at that moment raises PermissionError. With the old open(..., 'wb') the write went through, and the reader got torn data instead. The new behaviour is arguably better (a clear error instead of corrupt data), but a short retry loop around os.replace() on PermissionError (a few attempts, a few ms apart) would avoid turning a harmless concurrent read into a failed store_result. At minimum, please mention it in the comment.

Minor / edge cases

  • Symlinked result files are replaced rather than written through. On main, if a result file is a symlink, the write goes to the target. With os.replace() the symlink itself is replaced by a regular file and the target stays unchanged (I checked this). It's the same for a changed owner or ACLs when another user owns the existing file. These are unusual setups, so I don't think they block the PR, but a sentence in the docstring would help.
  • No fsync before os.replace(). After a crash, some filesystems can leave the renamed file empty. For a result store that's probably acceptable, but an optional os.fsync() on the temp file before the rename would make the write durable as well as atomic. I'm fine leaving it out.
  • The PR description is out of date. It still says tempfile.mkstemp(), but the code now uses self.open() with a uuid() name. Please update it so the history matches the implementation.
  • In test_set_preserves_file_mode_and_umask_default, os.umask() changes process-wide state. It's restored in finally, which is fine, but it could affect other tests running in parallel threads. pytest-xdist uses processes, so this is only a note.

LGTM once (1) and (2) are handled (or explicitly deferred).

…try replace on Windows

Address MehrazRumman's review on celery#10703:

- cleanup() now also removes 'celery-result-*.tmp' files older than
  expires, so temp files orphaned by a SIGKILL/OOM between the write
  and the os.replace() in set() no longer accumulate forever in a
  shared result directory. The stat()/unlink() pairs in cleanup() are
  guarded against the FileNotFoundError from a concurrent forget()
  or cleanup() pass, completing the idempotency contract.

- os.replace() is retried briefly on PermissionError (5 attempts,
  10ms apart): on Windows, CPython opens files without
  FILE_SHARE_DELETE, so a reader holding the destination open can
  turn a harmless concurrent read into a failed store_result. The
  failure is still raised once retries are exhausted.

- set() docstring/comment now documents that the rename replaces the
  destination rather than writing through a symlink or preserving a
  foreign owner/ACL, and the PR description is updated to match the
  implementation (self.open() with a uuid name, not mkstemp).

Tests: test_cleanup_removes_stale_temp_files,
test_set_retries_replace_on_permission_error,
test_set_raises_after_replace_retries_exhausted
(t/unit/backends/test_filesystem.py, 25 passed).

Signed-off-by: simpleqt <[email protected]>
@simpleqt

This comment was marked as spam.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants