Repository navigation
fix(utils): prevent LimitedSet.purge()/pop() from evicting a refreshe… - #10508
Namraa310806 wants to merge 19 commits into
Conversation
…d item via a stale heap entry
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #10508 +/- ##
==========================================
+ Coverage 89.12% 89.14% +0.02%
==========================================
Files 153 153
Lines 20236 20247 +11
Branches 2387 2390 +3
==========================================
+ Hits 18036 18050 +14
+ Misses 1897 1895 -2
+ Partials 303 302 -1
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. |
There was a problem hiding this comment.
Pull request overview
Fixes a LimitedSet eviction bug where stale heap entries (left behind after refreshing an item) could cause purge() / pop() to remove the current refreshed entry prematurely. This preserves the existing lazy-heap cleanup approach while ensuring only the current _data entry can be evicted.
Changes:
- Update
LimitedSet.purge()to discard stale heap entries before using the heap head to decide expiry. - Update
LimitedSet.pop()to remove an item from_dataonly when the popped heap entry matches the current_dataentry. - Add regression tests to cover refreshed items surviving stale-entry expiry and expiring at the correct refreshed TTL.
Reviewed changes
Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.
| File | Description |
|---|---|
| celery/utils/collections.py | Prevents stale heap entries from driving expiry/eviction decisions in purge() and pop(). |
| t/unit/utils/test_collections.py | Adds regression coverage for refresh + stale-heap-entry scenarios and correct eventual expiration. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
|
you can also check this pr #10507 and see if anything can be incorporated from it |
|
Thanks for pointing me to #10507. I reviewed it and incorporated the relevant approach of validating stale heap entries in both I also kept the additional regression coverage for multiple stale entries and direct pop() handling, and added a test for the equal-timestamp refresh case to verify why identity comparison is required. I’ve rerun the relevant tests and lint checks, and everything passes. Please let me know if there’s anything else from #10507 you’d like me to incorporate. |
|
can you also explore the possibilities of adding smoke or integrations tests for this changes? |
|
@auvipy Thanks for pointing me to #10507. I reviewed it and incorporated the relevant stale-entry handling in both I also checked whether a smoke/integration test would be useful. The existing worker/revoke tests already cover the production path, and an additional test for this specific timing issue would be more fragile, so I kept the regression coverage focused on The relevant tests and lint checks are passing. |
|
@phanky1 can you review this please? |
| except KeyError: | ||
| pass |
There was a problem hiding this comment.
Even though this exception is rare it's still possible, so I think we should keep this.
There was a problem hiding this comment.
Agreed — you're right that this needed the try/except back given _data can be touched concurrently. I've implemented the fix: self._data.pop(item) is now wrapped in try/except KeyError, and if the race is lost, pop() treats it as a stale entry and continues to the next heap entry instead of raising. I've also added a regression test (test_pop_handles_concurrent_removal_race) that simulates the exact race by making _data.pop() raise KeyError on the specific key being popped, and verifies pop() skips it cleanly and returns the next valid item. All LimitedSet and worker/state tests pass.
phanky1
left a comment
There was a problem hiding this comment.
I have run the 6 new tests against the original codebase and only 2 of them failed, which makes me think something isn't right with the test setup. Can you check @Namraa310806?
mohithvardhan002
left a comment
There was a problem hiding this comment.
Reviewed the LimitedSet stale-entry handling in purge() and pop(), along with the regression tests. The implementation correctly skips stale heap entries and only evicts the current _data entry. The tests also cover refreshes, multiple stale entries, pop(), and equal-timestamp entries.
I think we should bring back the try/except in |
|
@MehrazRumman please have a round of review |
MehrazRumman
left a comment
There was a problem hiding this comment.
I verified this by extracting LimitedSet from both origin/main and c623aef into standalone modules and running them side by side.
The fix is correct. The reported bug reproduces on main and is gone here:
main: add('x',1.0); add('x',6.0); purge(11.0) -> 'x' in s = False # wrong
pr: add('x',1.0); add('x',6.0); purge(11.0) -> 'x' in s = True # right
The is check is sound because every path that writes _data keeps its values identical to the heap's objects — _refresh_heap() rebuilds from self._data.values(), update(LimitedSet) copies the same tuple objects then refreshes, and the dict/iterable branches go through add(). I fuzzed 8000 random op sequences (add/discard/pop/purge/update, random maxlen/minlen/expires) asserting after every operation that each _data value is present in _heap by identity: no violations, no exceptions, no hangs, on either version. purge() also stays amortized linear and leaves the heap cleaner than main, and a pickle round-trip preserves the invariant.
Two things worth noting in its favour: the while/else also removes a latent IndexError (on main, self._heap[0] with a non-empty _data and an empty _heap raises; here it exits cleanly), and the restored try/except in pop() addresses @phanky1's point.
The tests, though, mostly do not guard the fix. Running each added test body against both versions:
| test | on main | real regression test? |
|---|---|---|
test_stale_heap_entry_cannot_evict_refreshed_item |
fails | yes |
test_purge_with_only_stale_entries_in_heap |
fails | yes |
test_multiple_refreshes_with_stale_entries |
passes | no |
test_pop_skips_stale_heap_entries |
passes | no |
test_refresh_with_same_timestamp |
passes | no |
test_pop_returns_default_when_only_stale_entries_remain |
passes | no |
test_pop_handles_concurrent_removal_race |
passes | no |
Five of seven pass on unpatched main, so they would not have caught #10506 and will not catch a regression.
The cause is that add() calls discard(), which calls _maybe_refresh_heap(), and at small sizes the 15% overload threshold is always exceeded — so the heap is rebuilt and the stale entry the test intends to create is silently removed. Two comments are therefore factually wrong:
test_pop_skips_stale_heap_entriessays "Heap now contains: (1, task1) [stale], (2, task2), (5, task1) [current]". The actual heap is[(2.0,'task2'), (5.0,'task1')]with zero stale entries.test_multiple_refreshes_with_stale_entriespromises multiple stale entries; there is never more than one at a time.
test_refresh_with_same_timestamp can't discriminate either — with equal timestamps the stale and current entries expire together, so both versions agree. Its entry1 is not entry2 assertion is still worth keeping as documentation of why identity is required.
To get a pop() test that actually fails on main, use at least 8 items so _maybe_refresh_heap() stays under its threshold and the stale entry survives:
def test_pop_does_not_evict_refreshed_item_via_stale_entry(self):
s = LimitedSet(expires=100)
# >= 8 items so discard()'s 15% overload threshold does not rebuild the heap
for i in range(8):
s.add(f"other{i}", now=10.0 + i)
s.add("hot", now=1.0)
s.add("hot", now=100.0) # leaves a genuine stale (1.0, "hot")
assert s.pop() == "other0" # main returns "hot"
assert "hot" in sVerified: main returns 'hot' and drops it from the set; this branch returns 'other0' and keeps 'hot'. The same shape works for purge(now=102.0).
Last two are minor: test_pop_returns_default_when_only_stale_entries_remain reaches its state with s._data.pop(...), which discard() does through the public API, so calling s.discard("task-id") would be more faithful; and test_purge_with_only_stale_entries_in_heap manufactures a state my fuzzing suggests the public API cannot produce, so it is covering a defensive branch rather than a reachable one — worth saying so in the docstring.
On the smoke/integration question: agreed, skipping it is the right call. The behaviour is a pure data-structure timing property and a broker-level test would be far more fragile than these unit tests.
No objection to the production change — it is correct and I would merge it once the test gaps above are closed.
|
|
||
| Regression test for the check-then-act race in pop(). If another thread | ||
| removes an item from self._data after the identity check passes but before | ||
| self._data.pop(item) is called, pop() should treat it as a stale entry and |
There was a problem hiding this comment.
There still appears to be a check-then-act race here. After current_entry is entry passes, another thread could refresh the same item before _data.pop(item) executes. Since add() replaces _data[item] with a new entry, this pop could then remove the newly refreshed entry. The new regression test covers concurrent removal (KeyError), but not concurrent refresh/replacement. Could we also cover or synchronize this case?
auvipy
left a comment
There was a problem hiding this comment.
also merge conflict needs to be fixed
Description
Fixes #10506
LimitedSetkeeps expired entries in its heap for lazy cleanup. When an existing item is refreshed, its current entry in_datais replaced with a new entry, while the previous heap entry may remain in_heap.Previously,
purge()could use the stale heap entry's timestamp when checking expiration, andpop()could remove the current_dataentry based only on the item key. As a result, an old expired heap entry could remove a refreshed item before its actual expiration time.For example:
t=1withexpires=10.t=6.t=11.t=11could remove the item even though the refreshed entry should remain valid untilt=16.Changes
LimitedSet.purge()to skip stale heap entries before checking the expiration timestamp.LimitedSet.pop()to remove an item only when the popped heap entry matches the item's current entry in_data.The existing lazy heap design is preserved; stale entries are discarded during heap processing rather than requiring eager removal when an item is refreshed.
Verification
LimitedSettests pass.t/unit/utils/tests pass:412 passed, 94 skipped, 28 xfailed.