Repository navigation
fix(backends/couchbase): missing document raises instead of returning None - #10680
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
This comment was marked as spam.
This comment was marked as spam.
MehrazRumman
left a comment
There was a problem hiding this comment.
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 = NoneTwo problems with this shape:
- Coupling. Adding the exception to the same
trymeans that if that one name ever fails to import — an SDK release that moves or renames it —ClusterbecomesNonetoo, 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 supportedcouchbase>=3range the name exists, so this is about robustness rather than a current bug, but it's cheap to avoid. except None:is aTypeErrorif it's ever evaluated. It's unreachable today because__init__raises whenCluster 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
couchbaseextra, so the whole module isimportorskip-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 patchingClusterso 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).statereadsPENDINGandforget()doesn't raise. One test going throughbackend.get_task_meta(...)with the mockedgetraising — assertingstatus == PENDING— pins the actual behaviour the PR is about, and would catch a future change in_get_task_meta_forthat stops treatingNoneas 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 theexceptand silently turning outages intoPENDING.
4. Worth mentioning in the description and changelog
The fix reaches further than state and forget():
GroupResult.restore()on an expired group goes throughget()via_restore_group, so it now returnsNoneinstead of raising.- If the key-value implementation of
task_result_exists()goes throughget(), this also fixesAsyncResult.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
KeyValueStoreBackendcontract; the Mongo backend isn't a key-value backend, though it does report missing results asPENDING. The behavioural point stands; the wording would just be off in a changelog. test_get_missing_document_returns_Nonecould also assertget.assert_called_once_with('1f3fab'), matchingtest_getright 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.
1d021bd to
66a7a13
Compare
This comment was marked as spam.
This comment was marked as spam.
|
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
This comment was marked as spam.
This comment was marked as spam.
|
thats really great! |
…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]>
Description
The
KeyValueStoreBackendcontract across celery is:get()returnsNonefor an absent key, anddelete()/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 aKeyValueStoreBackend), and it's whatget_task_meta()/AsyncResultrely on to render an expired or unknown task id as a state rather than crashing.CouchbaseBackendviolates both halves:get()doesself.connection.get(key).contentwith no guard. When the document has expired (auto-expiry is on:supports_autoexpire = True) or was never stored, the SDK raisesDocumentNotFoundException, which propagates out ofget_task_meta()— soAsyncResult(id).stateon a purged id raisesDocumentNotFoundExceptioninstead of reading as unknown/PENDING.delete()doesself.connection.remove(key)with no guard, soAsyncResult.forget()on an already-expired or already-forgotten result raisesDocumentNotFoundException.Reproduce (against a reachable Couchbase with an empty/default collection):
What does this fix
Bug fix —
get()now catchesDocumentNotFoundExceptionand returnsNone;delete()catches it and returns. TheDocumentNotFoundExceptionimport lives in its owntrywith a stand-in exception class when the SDK is absent (mirroringmongodb.py), so a future SDK rename can't takeClusterdown with it and noexcept Nonecan arise.Because
KeyValueStoreBackendroutes more thanget_task_meta()throughget(), 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()isbool(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-visiblePENDINGcontract throughget_task_meta()), andtest_get_unrelated_sdk_errors_propagate(pins the catch width: a timeout still propagates).Type of Change
Verification
pytest t/unit/backends/test_couchbase.py→ 24 passed (couchbase SDK 4.6.3).DocumentNotFoundExceptionpropagates throughget()/get_task_meta()), the other tests pass — they fail for exactly this behavior, not incidentally.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'sMultiGetResulthas neither.items()nor iteration and by default raises on the first failed key, soget_many()/GroupResult.restore()died withTypeError. Now translated viaGetMultiOptions(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.requirements/test-ci-default.txt), sot/unit/backends/test_couchbase.pyactually runs; markers exclude exactly the matrix cells where the SDK publishes no wheels (PyPy, CPython 3.15, Windows/3.14).also fix #10694