Repository navigation
Conversation
Codecov Report❌ Patch coverage is
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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
There was a problem hiding this comment.
the code coverage might be improved @MehrazRumman what do you think?
ege-arhan
left a comment
There was a problem hiding this comment.
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 fileIf 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 injectableself.open(usesos.fdopen/os.replacedirectly), so backends/tests overridingopenno longer intercept writes.- In the
except BaseExceptionhandler,os.unlink(tmp_name)can itself raiseFileNotFoundError(e.g. replace succeeded but a later line failed — not the case today, but any future statement added afteros.replaceinside thetrywould 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]>
This comment was marked as spam.
This comment was marked as spam.
MehrazRumman
left a comment
There was a problem hiding this comment.
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. strandbytespaths are both handled.- New files get the umask default because they go through
self.open, and an existing file's mode is kept viastat+chmod, covered bytest_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
-
cleanup()never removes an orphaned temp file. If the process is killed (SIGKILL, OOM, power loss) between the write andos.replace(), acelery-result-<uuid>.tmpis left behind.cleanup()only considers names starting with the task/group/chord key prefixes, so these files stay forever. Sincecleanup()already walks the directory, it could also deletecelery-result-*.tmpfiles older thanexpires. That's small, and it keeps a long-running shared result directory clean. -
Windows (and possibly SMB mounts):
os.replace()can fail while a reader has the file open. CPython on Windows opens files withoutFILE_SHARE_DELETE, so replacing a result file that another process is reading at that moment raisesPermissionError. With the oldopen(..., '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 aroundos.replace()onPermissionError(a few attempts, a few ms apart) would avoid turning a harmless concurrent read into a failedstore_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. Withos.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
fsyncbeforeos.replace(). After a crash, some filesystems can leave the renamed file empty. For a result store that's probably acceptable, but an optionalos.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 usesself.open()with auuid()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 infinally, which is fine, but it could affect other tests running in parallel threads.pytest-xdistuses 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]>
Problem
FilesystemBackend.setwrites results non-atomically:open(..., 'wb')truncates the file before writing, with no temp-file/rename and no locking. Concurrent readers —AsyncResult.getpolling,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 failsdecode_result:(writer thread looping
set(key, 512KB meta), reader thread loopingget(key)+ decode — 262 of 302 reads saw a torn file).getonly swallowsFileNotFoundError, 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 auuid()name and acelery-result-prefix, type-matched because result paths may bebytes), thenos.replace()it into place — readers now see either the old or the new complete file, never a partial one.os.replaceis atomic on POSIX and Windows; the temp file is removed if the write fails. On Windows,os.replace()is retried briefly onPermissionError, since a reader holding the destination open (CPython opens files withoutFILE_SHARE_DELETE) would otherwise turn a harmless concurrent read into a failedstore_result.Notes on semantics:
stat+chmod).cleanup()now also removescelery-result-*.tmpfiles older thanexpires, so temp files orphaned by a killed process don't accumulate forever, and itsstat()/unlink()pairs tolerate files vanishing in a concurrentforget()/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 onmain(tornDecodeError), passes with the fix (red/green verified).test_set_is_atomic_no_tempfile_left_behind: set/get roundtrip plus nocelery-result-*temp residue.test_cleanup_removes_stale_temp_files: a stale orphaned.tmpis removed bycleanup(), a fresh one survives.test_set_retries_replace_on_permission_error/test_set_raises_after_replace_retries_exhausted: the Windows retry path succeeds after transientPermissionErrors and still raises (with temp cleanup) once retries are exhausted.Existing 22 tests unchanged and passing; flake8 (repo config) clean.