Skip to content

fix(backends/couchbase): missing document raises instead of returning None - #10680

Merged
auvipy merged 5 commits into
celery:mainfrom
simpleqt:fix/couchbase-missing-doc
Sep 22, 2026
Merged

auvipy merged 5 commits into
celery:mainfrom
simpleqt:fix/couchbase-missing-doc

Conversation

@simpleqt

@simpleqt simpleqt commented Sep 21, 2026 •

Copy link
Copy Markdown

Description

The KeyValueStoreBackend contract across celery is: get() returns None for an absent key, and delete()/forgetting an absent key is a no-op — that's how redis, memcached, filesystem, etc. behave (mongodb reaches the same observable behaviour at the result layer even though it isn't a KeyValueStoreBackend), and it's what get_task_meta()/AsyncResult rely on to render an expired or unknown task id as a state rather than crashing.

CouchbaseBackend violates both halves:

  • get() does self.connection.get(key).content with no guard. When the document has expired (auto-expiry is on: supports_autoexpire = True) or was never stored, the SDK raises DocumentNotFoundException, which propagates out of get_task_meta() — so AsyncResult(id).state on a purged id raises DocumentNotFoundException instead of reading as unknown/PENDING.
  • delete() does self.connection.remove(key) with no guard, so AsyncResult.forget() on an already-expired or already-forgotten result raises DocumentNotFoundException.

Reproduce (against a reachable Couchbase with an empty/default collection):

from celery import Celery, uuid
app = Celery('t', backend='couchbase://localhost/default')
app.AsyncResult(uuid()).state          # DocumentNotFoundException, not 'PENDING'
app.AsyncResult(uuid()).forget()       # DocumentNotFoundException

What does this fix

Bug fix — get() now catches DocumentNotFoundException and returns None; delete() catches it and returns. The DocumentNotFoundException import lives in its own try with a stand-in exception class when the SDK is absent (mirroring mongodb.py), so a future SDK rename can't take Cluster down with it and no except None can arise.

Because KeyValueStoreBackend routes more than get_task_meta() through get(), this also fixes on this backend:

  • GroupResult.restore() on a missing/expired group (_restore_group() → get()),
  • AsyncResult.exists() (added in 5.7.0; task_result_exists() is bool(self.get(...))), which currently raises for never-stored ids.

Four mock-based regression tests added to t/unit/backends/test_couchbase.py, following the file's existing mock-the-connection pattern: test_get_missing_document_returns_None, test_delete_missing_document_is_noop, test_get_task_meta_pending_for_missing_document (asserts the user-visible PENDING contract through get_task_meta()), and test_get_unrelated_sdk_errors_propagate (pins the catch width: a timeout still propagates).

Type of Change

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

Verification

  • With the fix: pytest t/unit/backends/test_couchbase.py → 24 passed (couchbase SDK 4.6.3).
  • Fix reverted, tests kept: the missing-document tests fail (DocumentNotFoundException propagates through get()/get_task_meta()), the other tests pass — they fail for exactly this behavior, not incidentally.
  • Repo-pinned pre-commit run --files celery/backends/couchbase.py t/unit/backends/test_couchbase.py (flake8, isort, mypy, yesqa, codespell, pyupgrade): all pass.

Follow-up commits (requested in review):

  • mget() fixed for the 4.x SDK: get_multi's MultiGetResult has neither .items() nor iteration and by default raises on the first failed key, so get_many()/GroupResult.restore() died with TypeError. Now translated via GetMultiOptions(return_exceptions=True) into the plain dict the KV contract expects (missing document → None, other per-key errors re-raised). Five regression tests added, Fixes #10694.
  • The unit-test CI job now installs the couchbase SDK (requirements/test-ci-default.txt), so t/unit/backends/test_couchbase.py actually runs; markers exclude exactly the matrix cells where the SDK publishes no wheels (PyPy, CPython 3.15, Windows/3.14).

also fix #10694

Copilot AI lite review requested due to automatic review settings September 21, 2026 12:32

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

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.42%. Comparing base (35e6ac2) to head (400ab59).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10680      +/-   ##
==========================================
+ Coverage   89.28%   89.42%   +0.14%     
==========================================
  Files         153      153              
  Lines       20397    20414      +17     
  Branches     2431     2434       +3     
==========================================
+ Hits        18212    18256      +44     
+ Misses       1881     1852      -29     
- Partials      304      306       +2     
Flag Coverage Δ
unittests 89.40% <100.00%> (+0.14%) ⬆️

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.

@simpleqt

This comment was marked as spam.

@auvipy
auvipy self-requested a review September 21, 2026 13:12
@auvipy auvipy added this to the 5.7.x milestone Sep 21, 2026

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

Review

Correct fix, narrowly scoped, and the verification is exactly what I'd want to see — in particular running the new tests with the fix reverted to show they fail for this reason and not incidentally. The contract claim checks out: KeyValueStoreBackend._get_task_meta_for treats a falsy get() as PENDING, so returning None is what makes AsyncResult(id).state read correctly, and catching only DocumentNotFoundException (rather than a broad SDK error) is the right width.

A few things before merge, one of them code.


1. The import fallback should be a placeholder class, in its own try

try:
    from couchbase.auth import PasswordAuthenticator
    from couchbase.cluster import Cluster
    from couchbase.exceptions import DocumentNotFoundException
except ImportError:
    Cluster = PasswordAuthenticator = None
    DocumentNotFoundException = None

Two problems with this shape:

  • Coupling. Adding the exception to the same try means that if that one name ever fails to import — an SDK release that moves or renames it — Cluster becomes None too, and the backend refuses to start with "You need to install the couchbase library", which is untrue and sends users looking in the wrong place. Within the supported couchbase>=3 range the name exists, so this is about robustness rather than a current bug, but it's cheap to avoid.
  • except None: is a TypeError if it's ever evaluated. It's unreachable today because __init__ raises when Cluster is None, but that's an invariant in a different method keeping this one safe.

The MongoDB backend already has the pattern for this — a stand-in exception class when the driver isn't importable:

try:
    from couchbase.exceptions import DocumentNotFoundException
except ImportError:  # pragma: no cover
    class DocumentNotFoundException(Exception):
        """Stand-in so ``except`` clauses stay valid without the SDK."""

Every except DocumentNotFoundException: is then always valid, and a missing name can't disable the whole backend.

2. mget() is the third leg of the same contract

The description says the backend violates "both halves" of the contract, but mget() is part of it too — it's what get_many() and native group joins go through, and it has to cope with absent keys as well:

def mget(self, keys):
    return self.connection.get_multi(keys)

On the 4.x SDK, get_multi returns a MultiGetResult rather than a list of values, with per-key failures collected on the result object instead of raised. I'd be surprised if _mget_to_results handles that shape correctly for missing keys — or for present ones. Out of scope for this PR, but worth checking, and worth an issue if it's broken, since GroupResult.get() on this backend would go through it.

3. Tests

The two new tests are fine and follow the file's existing pattern. Three suggestions:

  • They never run in CI. As you noted, the unit job doesn't install the couchbase extra, so the whole module is importorskip-ed and the backend sits at 0% CI coverage — before and after this PR. That's not something to fix here, but it's worth maintainers knowing: it's how a contract violation this basic survived, and nothing stops it regressing. Either installing the extra in the unit job or patching Cluster so the module runs without the SDK would do; the second is a bigger restructure than this PR should carry.
  • Test the contract, not just the method. The user-visible claim is that AsyncResult(id).state reads PENDING and forget() doesn't raise. One test going through backend.get_task_meta(...) with the mocked get raising — asserting status == PENDING — pins the actual behaviour the PR is about, and would catch a future change in _get_task_meta_for that stops treating None as pending.
  • Pin the width of the catch. A test that a different SDK error (a timeout, say) still propagates from get() stops a future "while I'm here" change from widening the except and silently turning outages into PENDING.

4. Worth mentioning in the description and changelog

The fix reaches further than state and forget():

  • GroupResult.restore() on an expired group goes through get() via _restore_group, so it now returns None instead of raising.
  • If the key-value implementation of task_result_exists() goes through get(), this also fixes AsyncResult.exists() — new in 5.7.0, and whose entire purpose is reporting the never-stored case that currently raises on this backend. If so, that's the strongest argument for getting this into 5.7.x.

Nits

  • The description lists MongoDB among the backends following the KeyValueStoreBackend contract; the Mongo backend isn't a key-value backend, though it does report missing results as PENDING. The behavioural point stands; the wording would just be off in a changelog.
  • test_get_missing_document_returns_None could also assert get.assert_called_once_with('1f3fab'), matching test_get right above it.

Verdict: approve after point 1. Points 2–4 are follow-ups or description changes, not blockers — though the contract-level test in point 3 is cheap and I'd add it here.

… None

The KV backend contract is that get() returns None for an absent key and
delete() is a no-op, so an expired or never-stored result surfaces as a
PENDING/none state rather than an exception. CouchbaseBackend violated
both: get() let DocumentNotFoundException escape through get_task_meta(),
so AsyncResult on a purged task id crashed instead of reading as
unknown, and delete()/forget() raised the same exception when the
document had already expired or been removed.

Catch DocumentNotFoundException in both methods and honour the
contract.
@simpleqt

This comment was marked as spam.

@auvipy auvipy modified the milestones: 5.7.x, 5.7.0 Sep 22, 2026
@auvipy

auvipy commented Sep 22, 2026

Copy link
Copy Markdown
Member

i think we should fix the test skip of couchbase in this pr as well...

The couchbase unit tests pytest.importorskip the SDK, so they have never
run in CI (the line was commented out in test-ci-default.txt). Re-enable
the install with markers for the platforms where the SDK publishes no
wheels: PyPy, CPython 3.15, and the Windows job (which only runs 3.14).
get_multi() returns a MultiGetResult, which _mget_to_results cannot
consume: it has no .items() and is not iterable, so get_many()/
GroupResult.restore() raised TypeError on every call. It also raises on
the first failed key by default, so a single missing/expired document
took down the whole batch.

Ask the SDK to keep per-key results (GetMultiOptions
(return_exceptions=True)), then translate into the plain dict the KV
contract expects: a missing document means no result (None), any other
per-key failure is a real error and is re-raised.

Fixes celery#10694
@simpleqt

This comment was marked as spam.

@auvipy

auvipy commented Sep 22, 2026

Copy link
Copy Markdown
Member

thats really great!

@auvipy
auvipy merged commit 1700781 into celery:main Sep 22, 2026
21 of 23 checks passed
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]>
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.

[Bug] CouchbaseBackend.mget() is incompatible with couchbase SDK >= 4 (get_multi returns MultiGetResult)

4 participants