Skip to content

Combine fixes for the filesystem backend, canvas stamping, LimitedSet, truncate, event heartbeats and beat - #11184

Open
MehrazRumman wants to merge 23 commits into
celery:mainfrom
MehrazRumman:fix/simpleqt-combined
Open

MehrazRumman wants to merge 23 commits into
celery:mainfrom
MehrazRumman:fix/simpleqt-combined

Conversation

@MehrazRumman

@MehrazRumman MehrazRumman commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

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-main commits are left out. Where main had 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

Other fixes

Conflict resolution against current main

Follow-ups from review

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:

  • The two cleanup() race tests did not trigger the race. test_cleanup_skips_files_vanishing_before_unlink patched os.unlink, but the backend keeps its own reference (self.unlink), so the patch was never called. It now patches tb.unlink and checks that it was called. test_cleanup_skips_files_removed_concurrently deleted the file inside stat() without raising. Now that main computes the cutoff correctly, a fresh file is not stale and unlink is never reached. It now removes the file before calling the real stat(), which raises FileNotFoundError.
  • The os.replace() retry loop is rewritten as for/else. It still makes five attempts and raises the last PermissionError, but it no longer has an unreachable branch. The retries-exhausted test now checks that there are exactly five attempts.
  • New tests:
    • a temp file that another worker removes during cleanup()
    • cleanup() with group keys and unrelated files in the directory
    • set() with a str result path
    • stamping a chord that has no body

Testing

  • pytest t/unit: 5831 passed, 32 skipped, 1 xfailed.
  • Coverage of celery/backends/filesystem.py is 99%. The only uncovered line is the Windows-only path handling in __init__, which this PR does not change.
  • flake8 and isort --check-only pass on all changed files.
  • The integration test added in fix(canvas): stamp the chord body without a visitor #10698 (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.

simpleqt and others added 18 commits November 29, 2026 23:53
…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]>
@codecov

codecov Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.85%. Comparing base (ce68a20) to head (c85b6ee).
✅ All tests successful. No failed tests found.

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     
Flag Coverage Δ
unittests 91.83% <100.00%> (+0.02%) ⬆️

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.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants