Skip to content

fix(utils): synchronize BufferMap total updates across threads (fixes #11152) - #11159

Open
ghanashyam03 wants to merge 2 commits into
celery:mainfrom
ghanashyam03:fix/buffermap-thread-safety-11152
Open

ghanashyam03 wants to merge 2 commits into
celery:mainfrom
ghanashyam03:fix/buffermap-thread-safety-11152

Conversation

@ghanashyam03

Copy link
Copy Markdown

Description

Fixes #11152.

BufferMap tracks aggregate buffered items across all sub-buffers in self.total. In multi-threaded consumer/producer workloads (such as RPC and Redis result backends with _pending_messages), concurrent put(), extend(), take(), and _pop_to_evict() mutate self.total via non-atomic operations (+=, -=) without synchronization.

This leads to drift between BufferMap.total and the true item count under concurrency, which causes premature eviction or eviction starvation. In addition, BufferMap.clear() did not reset total to 0.

Changes

  1. Added an internal reentrant lock (self.mutex = threading.RLock()) to BufferMap guarding put, extend, take, _LRUpop, _pop_to_evict, and clear.
  2. Added context manager support (__enter__ / __exit__) to BufferMap so external callers can synchronize multi-step operations on the mapping.
  3. Updated BufferMap.clear() to reset self.total = 0.
  4. Protected pop() and total -= len(buf) in RPCBackend.forget() and ResultConsumer.on_wait_for_pending() using the buffer map mutex.

Testing

Added unit and concurrency regression tests in t/unit/utils/test_collections.py:

  • test_clear_resets_total
  • test_context_manager_locks_mutex
  • test_concurrent_puts_preserve_total
  • test_concurrent_puts_and_takes_preserve_total

Verified locally:

  • pytest -p no:remotedata t/unit/utils/test_collections.py (76 passed)
  • pytest -o markers=celery -p no:remotedata t/unit/utils/test_collections.py t/unit/backends/test_rpc.py t/unit/backends/test_redis.py (318 passed)
  • flake8 celery/utils/collections.py celery/backends/redis.py celery/backends/rpc.py t/unit/utils/test_collections.py (clean)

@auvipy
auvipy self-requested a review November 24, 2026 08:36

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BufferMap.total races: unguarded +=/-= drifts eviction accounting across threads

1 participant