Skip to content

fix(backends/filesystem): forget() raises FileNotFoundError on missing result - #10678

Open
simpleqt wants to merge 5 commits into
celery:mainfrom
simpleqt:fix/fs-forget-missing
Open

simpleqt wants to merge 5 commits into
celery:mainfrom
simpleqt:fix/fs-forget-missing

Conversation

@simpleqt

Copy link
Copy Markdown

Description

FilesystemBackend.delete() unconditionally os.unlink()s the result file. AsyncResult.forget() calls it, so forgetting a task whose result file is not on disk — because it was expired by cleanup(), already forgotten, or never stored — raises FileNotFoundError instead of being a no-op:

>>> ar.forget()
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/results/<task-id>'

Every other KV-style backend (redis, memcached, mongodb, …) silently ignores deleting an absent key, and forget() semantics across celery treat "already gone" as success. This makes the filesystem backend match: delete() now catches FileNotFoundError and returns.

What does this fix

forget() (and any direct delete()) on a missing result file raised FileNotFoundError. Reproduce:

from celery import Celery, uuid
app = Celery('t', backend='file:///tmp/celery-fs-repro')
app.AsyncResult(uuid()).forget()  # FileNotFoundError on current main

Type of Change

  • Bug fix (non-breaking change that fixes an issue)

Commits

Single commit ffbf7d8: the 4-line guard in celery/backends/filesystem.py plus two regression tests (test_forget_missing_task_is_noop, test_forget_twice_is_noop).

Verification

Tests were written against the fix and confirmed to fail without it:

  • With the fix: pytest t/unit/backends/test_filesystem.py → 21 passed
  • Fix reverted (tests kept): → the 2 new tests fail with FileNotFoundError, the other 19 pass

Repo-pinned pre-commit run --files celery/backends/filesystem.py t/unit/backends/test_filesystem.py (flake8, isort, mypy, codespell, pyupgrade, …): all hooks pass.

…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().
Copilot AI lite review requested due to automatic review settings September 21, 2026 12:27

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 21, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.77778% with 2 lines in your changes missing coverage. Please review.
✅ Project coverage is 89.98%. Comparing base (88c70c4) to head (a4001c8).
⚠️ Report is 48 commits behind head on main.

Files with missing lines Patch % Lines
celery/backends/filesystem.py 77.77% 2 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10678      +/-   ##
==========================================
+ Coverage   89.44%   89.98%   +0.53%     
==========================================
  Files         153      153              
  Lines       20414    20943     +529     
  Branches     2434     2516      +82     
==========================================
+ Hits        18260    18845     +585     
+ Misses       1851     1798      -53     
+ Partials      303      300       -3     
Flag Coverage Δ
unittests 89.96% <77.77%> (+0.53%) ⬆️

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 added a commit that referenced this pull request Sep 27, 2026
…10697)

* fix(backends): keep forget() idempotent on elasticsearch and couchdb

Result.forget() on ElasticsearchBackend raises elasticsearch.NotFoundError
and on CouchBackend raises pycouchdb.exceptions.NotFound when the result is
absent (expired, cleaned up, already forgotten, or never stored), while the
other KV result backends treat deleting an absent key as a no-op.

Catch the backend-specific NotFound inside each delete(), mirroring the
filesystem (#10678) and couchbase (#10680) fixes, so forget() stays
idempotent. get()/mget() paths are unchanged.

Regression tests per backend: forgetting a missing task and forgetting
twice. Red before the fix (4 failed, exception propagated), green after
(58 passed). pre-commit hooks pass on pinned versions.

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

* docs(backends): clarify ES NotFoundError scope, fix forget-twice test

- note that Elasticsearch NotFoundError also covers a missing index
  (index_not_found_exception); the forget() outcome is the same either way
- test_forget_twice_is_noop generated two different task ids, making it
  identical to the missing-task test; use the same id so it really
  exercises the second forget on an already-forgotten result

---------

Signed-off-by: simpleqt <[email protected]>
Co-authored-by: Asif Saif Uddin {"Auvi":"অভি"} <[email protected]>

@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, this is a small, correct fix, and it's in line with the rest of this forget() series (#10697 for Elasticsearch/CouchDB, #10701 for ArangoDB, #10714 for Azure Block Blob/CosmosDB).

The fix

  • Catching only FileNotFoundError around self.unlink(...) is the right scope. It handles the missing-file case and still surfaces PermissionError, IsADirectoryError and other OSErrors, which point to a real misconfiguration.
  • unlink is injectable (FilesystemBackend(unlink=...)), and the except works for the default os.unlink and for any custom function that follows the same convention.

Tests

Both tests exercise the real code path through forget(), including get_key_for_task() and _filename(), against a real temporary directory. test_forget_twice_is_noop uses the same task id for both calls, so it tests exactly what its name says.

Related gap in cleanup() (possible follow-up)

cleanup() has the same missing-file race:

for filename in os.listdir(self.path):
    ...
    if os.stat(path).st_mtime < cutoff_ts:
        self.unlink(path)

If a forget(), or a second cleanup() from another worker or beat instance sharing the directory, removes a file between listdir() and stat()/unlink(), cleanup() raises FileNotFoundError and stops processing the rest of the directory. Wrapping the stat()/unlink() in the same try/except FileNotFoundError: pass (or continue) would fix it. It fits this PR's theme, so it could be added here, or it could be a follow-up if you'd rather keep this PR minimal.

Nit

with contextlib.suppress(FileNotFoundError): would be a bit more compact than try/except/pass, but the other backends in this series use try/except, so keeping it consistent is fine too.

LGTM. Approving; the cleanup() point is non-blocking.

@auvipy

auvipy commented Sep 27, 2026

Copy link
Copy Markdown
Member

i think the cleanup part should be done here

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]>
@simpleqt

This comment was marked as spam.

@auvipy

auvipy commented Sep 27, 2026

Copy link
Copy Markdown
Member

the patch cov is showing only 77%, is it right? can you cross check? if true it would be great to improve test coverage

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]>
@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.

4 participants