Skip to content

fix(backends): keep forget() idempotent on elasticsearch and couchdb - #10697

Merged
auvipy merged 4 commits into
celery:mainfrom
simpleqt:forget-kv-backends
Sep 27, 2026
Merged

auvipy merged 4 commits into
celery:mainfrom
simpleqt:forget-kv-backends

Conversation

@simpleqt

Copy link
Copy Markdown

Problem

AsyncResult(task_id).forget() raises on two KV result backends when the result is absent — expired, cleaned up, already forgotten, or never stored:

res = app.AsyncResult("8bed31f4-...")   # never stored, or already forgotten
res.forget()
# ElasticsearchBackend -> elasticsearch.exceptions.NotFoundError
# CouchBackend         -> pycouchdb.exceptions.NotFound

forget() is documented as removing the result and is expected to be idempotent ("forget about it"), and every other KV backend already tolerates an absent key: filesystem was fixed in #10678, couchbase in #10680, and redis's delete is a no-op for missing keys.

Root cause

KeyValueStoreBackend._forget (celery/backends/base.py:1257) calls self.delete(self.get_key_for_task(task_id)), and both backends let their client's missing-document exception propagate out of delete():

  • celery/backends/elasticsearch.py:260 — self.server.delete(...) raises elasticsearch.exceptions.NotFoundError (404) for an absent doc (the get() path at lines 112/184 already handles this exception, only delete() leaks it)
  • celery/backends/couchdb.py:98 — self.connection.delete(key) raises pycouchdb.exceptions.NotFound

Fix

Catch the backend-specific NotFound inside each delete() and return, so forget() is idempotent — same shape as the filesystem and couchbase fixes. get()/mget() and every other path are unchanged.

     def delete(self, key):
+        try:
+            if self.doc_type:
+                self.server.delete(index=self.index, id=key, doc_type=self.doc_type)
+            else:
+                self.server.delete(index=self.index, id=key)
+        except elasticsearch.exceptions.NotFoundError:
+            # deleting an already-expired, already-forgotten or never-stored
+            # result must keep forget() idempotent, like the other KV backends
+            pass

(analogous for couchdb.py with pycouchdb.exceptions.NotFound)

Tests

Two regression tests per backend in t/unit/backends/test_elasticsearch.py / test_couchdb.py:

  • test_forget_missing_task_is_noop — forget a task whose document does not exist
  • test_forget_twice_is_noop — forget the same stored task twice

Red/green verified: with the fix reverted all 4 new tests fail with the exception propagating out of forget(); with the fix all 58 tests in both files pass. pre-commit run --files (pinned hooks: flake8, isort, mypy, pyupgrade, codespell) passes on all changed files.

Note on CI: the elasticsearch/couchdb extras are not part of the default CI requirements, so these tests are importorskip'd there (same situation as couchbase before #10680) — they were run locally against elasticsearch 8.19.3 / pycouchdb 1.17.1 (extras' pinned range).

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 (celery#10678) and couchbase (celery#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]>
Copilot AI lite review requested due to automatic review settings September 23, 2026 15:38

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.52%. Comparing base (31b6167) to head (f8fe942).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #10697   +/-   ##
=======================================
  Coverage   89.51%   89.52%           
=======================================
  Files         153      153           
  Lines       20414    20420    +6     
  Branches     2434     2434           
=======================================
+ Hits        18274    18280    +6     
  Misses       1838     1838           
  Partials      302      302           
Flag Coverage Δ
unittests 89.50% <100.00%> (+<0.01%) ⬆️

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 23, 2026 17:22
@auvipy auvipy added this to the 5.7.0 milestone Sep 23, 2026
@auvipy

auvipy commented Sep 26, 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, this is a clean fix. The approach looks right to me.

The fix

  • Elasticsearch: catching elasticsearch.exceptions.NotFoundError around both delete() branches (with and without doc_type) is correct. Note that ES also raises NotFoundError when the index itself doesn't exist (index_not_found_exception), so this change also hides that case. For forget() that's reasonable (nothing to forget either way), but it would be worth mentioning in the comment so nobody later thinks it only covers a missing document.
  • CouchDB: pycouchdb's Database.delete(id) first fetches the document to get its _rev, and that fetch is what raises NotFound, so catching it there is the right place. A concurrent update between the fetch and the delete can still raise Conflict. That's a different situation, and I think it's correct to leave it unhandled.
  • This matches the existing DocumentNotFoundException handling in couchbase.py and the no-op behaviour of Redis, cache, DynamoDB and ArangoDB, so forget() now behaves consistently on these backends.

Backends that still raise

For completeness, I checked the other KeyValueStoreBackend.delete() implementations. Two still let a missing-key error through:

  • azureblockblob.py: blob_client.delete_blob() raises azure.core.exceptions.ResourceNotFoundError for a missing blob.
  • cosmosdbsql.py: DeleteDocument() raises an HTTPFailure with status 404 for a missing document.

(gcs.py checks blob.exists() first, and S3 delete_object doesn't raise for a missing key.)

These don't need to be in this PR, but since the description says "like the other KV backends", it would be good to either fix them here or open a follow-up issue so forget() behaves the same everywhere.

Tests

  • test_forget_twice_is_noop calls forget(uuid()) twice, which generates two different task ids. Because side_effect is a list, the second call raises regardless, so this is effectively the same test as test_forget_missing_task_is_noop. To test what the name says, please use the same id for both calls:
  tid = uuid()
  x.forget(tid)
  x.forget(tid)
  assert x._connection.delete.call_count == 2
  • None of the new tests check which key delete() was called with. Adding delete.assert_called_with(x.get_key_for_task(tid)) (converted with bytes_to_str for CouchDB) would make sure the exception is being suppressed for the right call.
  • In test_elasticsearch.py, the NotFoundError(..., ApiResponseMeta(404, ...), None) construction is now repeated three times, including the existing test just above. A small helper such as _not_found_error() would keep this readable and give one place to update if the elasticsearch client's constructor changes again.

Summary

The code change is correct and small, and I'd approve it once the "twice" tests use the same task id. Handling Azure Block Blob and CosmosDB can be a follow-up.

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

This comment was marked as spam.

@auvipy
auvipy merged commit 0a24c06 into celery:main Sep 27, 2026
411 checks passed
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