Skip to content

Return 0 from MemcachedCache._increment when the result is 0 - #1082

Open
uttam12331 wants to merge 1 commit into
aio-libs:masterfrom
uttam12331:fix-memcached-increment-zero
Open

Return 0 from MemcachedCache._increment when the result is 0#1082
uttam12331 wants to merge 1 commit into
aio-libs:masterfrom
uttam12331:fix-memcached-increment-zero

Conversation

@uttam12331

Copy link
Copy Markdown

Problem

MemcachedCache.increment reports the wrong value when a counter is decremented to exactly 0:

await cache.set("counter", 5)
await cache.increment("counter", -5)   # returns -5, but the stored value is 0

aiomcache's incr/decr return the new value, or None if the key is missing. _increment ends with:

return incremented or delta

The or delta fallback is there to handle the missing-key case (incremented is None). But 0 is also falsy, so when the counter reaches exactly 0, 0 or delta returns delta instead of 0.

Impact

A decrement (or increment) whose true result is 0 returns the delta instead — increment("counter", -5) on a counter of 5 returns -5 while a subsequent get returns 0. The memory and valkey backends both return the true post-increment value (and BaseCache.increment documents the return as "Value of the key once incremented"), so only the memcached backend diverges.

Fix

return incremented if incremented is not None else delta

This keeps the missing-key behavior (return delta when the client returned None) while correctly returning a real 0.

Tests

Added test_increment_result_zero to tests/ut/backends/test_memcached.py, asserting that when the client's decr returns 0, _increment returns 0. It fails on master (returns -5) and passes with the fix.

_increment returned `incremented or delta`, where the `or delta` fallback
is meant to cover the missing-key case (aiomcache incr/decr return None).
But 0 is also falsy, so decrementing a counter to exactly 0 returned the
delta instead of 0 -- e.g. decrementing a counter of 5 by 5 returned -5.

Return delta only when the client returned None (missing key), so a real
result of 0 is preserved. This matches the memory and valkey backends,
which return the true post-increment value.
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.

1 participant