Repository navigation
Combine fixes for the filesystem backend, canvas stamping, LimitedSet, truncate, event heartbeats and beat - #11184
Open
MehrazRumman wants to merge 23 commits into
Open
MehrazRumman wants to merge 23 commits into
MehrazRumman wants to merge 23 commits into
Conversation
…g result delete() unconditionally unlinks the result file, so forget() blows up with FileNotFoundError when the result was expired, already forgotten, or never stored. Other KV backends tolerate deleting an absent key; make the filesystem backend match by ignoring FileNotFoundError in delete().
A concurrent forget() or a cleanup() run by another worker or beat sharing the result directory can remove a file between listdir() and stat()/unlink(); the race made cleanup() raise FileNotFoundError and abandon the rest of the directory. Skip vanished entries and keep processing, mirroring the forget() hardening in this series. Signed-off-by: simpleqt <[email protected]>
auvipy asked about the 77.78% patch coverage: the uncovered lines were cleanup()'s unlink-side race (the file vanishing between stat() and unlink()) - the existing racy test only exercised the stat side. The new test ages one file past expires, makes unlink lose the race on it (real unlink of the victim followed by FileNotFoundError), and pins that cleanup keeps going: the victim is gone, fresh files survive. Signed-off-by: simpleqt <[email protected]>
_Chord.stamp() guarded the body stamping behind visitor is not None, so a plain chord(header, body).stamp(custom=x) stamped every header task but silently dropped the stamps from the body. Stamping without a visitor is a documented, supported mode (Signature.stamp falls back to set(**headers)), and the header/body asymmetry meant callers could not rely on custom headers reaching the callback. Stamp the body whenever it exists; the visitor's on_chord_body hook is only consulted when a visitor was passed, preserving the visitor flow covered by the existing stamping tests. Signed-off-by: simpleqt <[email protected]>
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]>
…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]>
LimitedSet documents maxlen as enforced at all times, but assigning a smaller value kept the excess items in place until enough new items were added to trigger eviction one by one. Make maxlen a property that purges down to the new limit on assignment and keeps the maxlen >= minlen invariant for direct assignments too.
- purge() on assignment only when the set is over the new limit: growing maxlen must not purge, since purge() also drops time-expired items (with expires set, growing used to empty the set as a side effect). - __init__ sets _maxlen directly, which removes both getattr guards from the setter (it no longer runs during construction). - the new tests move into test_LimitedSet (carries @t.skip.if_win32), the redundant local pickle import is gone, and a new test pins that growing maxlen keeps expired items in place. - the shrink test comment now says 'until the next add()', matching the actual main-branch behaviour. Signed-off-by: simpleqt <[email protected]>
The comparison used >= instead of >, so a string exactly at maxlen was
'truncated' and came back longer than the input with the suffix
appended: truncate('hello', maxlen=5) returned 'hello...'. Only
truncate strings that actually exceed the limit.
The cluster-state dispatcher updated a worker's heartbeat for a task event
with the event's timestamp instead of the local receive time, because the
arguments to Worker.event() were passed in the wrong order:
worker.event(None, local_received, timestamp)
Worker.event() stores its third argument (local_received) in the heartbeat
list, which Worker.alive compares against the local clock, and every other
caller passes (timestamp, local_received). So a worker whose clock lags by
more than the heartbeat expiry window was reported OFFLINE right after it
sent an event, and a worker whose clock is ahead stored a future entry that
never leaves the list, keeping it ONLINE after it stopped sending events.
Pass the arguments in the documented order instead, and cover it with a
regression test that fails when the heartbeat is the remote timestamp.
Scheduler.tick() recovers the delay until the top entry's next check by subtracting two absolute timestamps built by _when(). At today's epoch magnitude a float only resolves to about 0.24 microseconds, so that difference came back up to 0.12 microseconds longer than the delay the entry had asked for -- a delay the scheduler, having no better value, then slept past. Cut the recovered delay back to the microsecond resolution of the datetimes the timestamps are built from. The invariant is covered by test_beat's pending/ticks tests and by a new one that pins it with a fixed clock. Signed-off-by: simpleqt <[email protected]>
…recv in the drift warning
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #11184 +/- ##
==========================================
+ Coverage 91.82% 91.85% +0.02%
==========================================
Files 153 153
Lines 22314 22367 +53
Branches 2798 2805 +7
==========================================
+ Hits 20490 20545 +55
Misses 1529 1529
+ Partials 295 293 -2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
…y so no branch is unreachable
…ts before raising
…d files and str paths
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR combines eight open PRs by @simpleqt into one, so maintainers can review and merge them together. This follows @auvipy's request on #10702 to combine the filesystem backend PRs. Each original commit is cherry-picked and keeps its original author, and the merge-from-
maincommits are left out. Wheremainhad moved on, conflicts were resolved as described below. Two small follow-up fixes from the reviews are added at the end.Combined PRs
Filesystem result backend
forget()on a missing result no longer raisesFileNotFoundError.FilesystemBackend.delete()now ignores a file that is already gone.cleanup()now skips files that another worker or beat removes betweenlistdir()andstat()/unlink(), instead of aborting the pass.delete()idempotent for missing keys. This is the same fix as fix(backends/filesystem): forget() raises FileNotFoundError on missing result #10678, so only fix(filesystem backend): make delete idempotent for missing keys #10702's comment and itsdelete()-level test (test_delete_missing_key_is_idempotent) are kept. Itsforget()test duplicatedtest_forget_missing_task_is_noopfrom fix(backends/filesystem): forget() raises FileNotFoundError on missing result #10678 and was dropped.set()writes to acelery-result-<uuid>.tmpfile in the same directory and moves it into place withos.replace(), so readers never see a partly written file.os.replace()is retried a few times onPermissionError.cleanup()also removes orphaned temp files older thanexpires.Other fixes
chord.stamp()without a visitor now also stamps the chord body, asSignature,chainandgroupalready do.LimitedSet.maxlenevicts the oldest items immediately.maxlenbelowminlenraisesValueError.maxlenafter construction, so this is API hardening rather than a fix for a live bug.truncate()no longer cuts strings that already fit. Before, a string exactlymaxlenlong was given the suffix, and a fitting string with a space lost its last word.Conflict resolution against current
maincelery/backends/filesystem.py:mainnow computes thecleanup()cutoff withapp.now().timestamp(), so thedatetimeimport from the older fix(filesystem backend): write result files atomically #10703 base is not needed. The temp file is now created withself.open(), sotempfileis not needed either.cleanup(), fix(filesystem backend): write result files atomically #10703's loop is kept, with fix(backends/filesystem): forget() raises FileNotFoundError on missing result #10678's comment explaining whyFileNotFoundErroris ignored.t/unit/backends/test_filesystem.py,t/unit/utils/test_collections.pyandt/unit/utils/test_text.py: the tests added onmainand in the PRs are independent, so all of them are kept. fix(collections): enforce a shrunken LimitedSet.maxlen immediately #10796's tests already usemain's new(inserted, seq, item)entry layout.Follow-ups from review
truncate()docstring (fix(text): stop truncate from cutting strings that already fit #10797 review): the docstring said the result never exceedsmaxlen, but the suffix is added on top. It now uses the wording suggested in the review. A test case was also added for a fitting string with a space (truncate("hello world", 11))._warn_drift()passed the local receive time asorigand the sender's timestamp asrecv. They are now in the right order, and a test checks them. The test fails without the fix.Coverage follow-ups
The Codecov patch check failed on the first push, which showed that some of the new code was never run by the tests:
cleanup()race tests did not trigger the race.test_cleanup_skips_files_vanishing_before_unlinkpatchedos.unlink, but the backend keeps its own reference (self.unlink), so the patch was never called. It now patchestb.unlinkand checks that it was called.test_cleanup_skips_files_removed_concurrentlydeleted the file insidestat()without raising. Now thatmaincomputes the cutoff correctly, a fresh file is not stale andunlinkis never reached. It now removes the file before calling the realstat(), which raisesFileNotFoundError.os.replace()retry loop is rewritten asfor/else. It still makes five attempts and raises the lastPermissionError, but it no longer has an unreachable branch. The retries-exhausted test now checks that there are exactly five attempts.cleanup()cleanup()with group keys and unrelated files in the directoryset()with astrresult pathTesting
pytest t/unit: 5831 passed, 32 skipped, 1 xfailed.celery/backends/filesystem.pyis 99%. The only uncovered line is the Windows-only path handling in__init__, which this PR does not change.flake8andisort --check-onlypass on all changed files.t/integration/test_canvas.py) needs a broker and was not run locally. It is left to CI.If this PR is merged, #10678, #10698, #10702, #10703, #10796, #10797, #10904 and #10908 can be closed.