Skip to content

fix(utils): prevent LimitedSet.purge()/pop() from evicting a refreshe… - #10508

Open
Namraa310806 wants to merge 19 commits into
celery:mainfrom
Namraa310806:fix/limited-set-stale-heap-eviction
Open

Namraa310806 wants to merge 19 commits into
celery:mainfrom
Namraa310806:fix/limited-set-stale-heap-eviction

Conversation

@Namraa310806

Copy link
Copy Markdown
Contributor

Description

Fixes #10506

LimitedSet keeps expired entries in its heap for lazy cleanup. When an existing item is refreshed, its current entry in _data is 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, and pop() could remove the current _data entry 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:

  • An item is added at t=1 with expires=10.
  • The same item is refreshed at t=6.
  • The old heap entry expires at t=11.
  • Previously, purging at t=11 could remove the item even though the refreshed entry should remain valid until t=16.

Changes

  • Update LimitedSet.purge() to skip stale heap entries before checking the expiration timestamp.
  • Update LimitedSet.pop() to remove an item only when the popped heap entry matches the item's current entry in _data.
  • Add regression tests covering:
    • A refreshed item surviving expiration of its stale heap entry.
    • Multiple refreshes creating multiple stale entries without causing premature eviction.
    • The refreshed entry still expiring at its correct expiration time.

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

  • Regression tests pass.
  • Existing LimitedSet tests pass.
  • Relevant worker/state tests pass.
  • Broader t/unit/utils/ tests pass: 412 passed, 94 skipped, 28 xfailed.

@codecov

codecov Bot commented Aug 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.14%. Comparing base (b6fa6b3) to head (6d23f35).
⚠️ Report is 22 commits behind head on main.

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     
Flag Coverage Δ
unittests 89.12% <100.00%> (+0.02%) ⬆️

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.

@auvipy
auvipy requested a lite review from Copilot August 22, 2026 14:30

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.

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 _data only when the popped heap entry matches the current _data entry.
  • 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.

@auvipy

auvipy commented Aug 22, 2026

Copy link
Copy Markdown
Member

you can also check this pr #10507 and see if anything can be incorporated from it

@auvipy
auvipy self-requested a review August 22, 2026 14:56
@Namraa310806

Copy link
Copy Markdown
Contributor Author

Thanks for pointing me to #10507. I reviewed it and incorporated the relevant approach of validating stale heap entries in both purge() and pop() using entry identity.

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.

@auvipy

auvipy commented Aug 31, 2026

Copy link
Copy Markdown
Member

can you also explore the possibilities of adding smoke or integrations tests for this changes?

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.

Pull request overview

Copilot reviewed 2 out of 2 changed files in this pull request and generated no new comments.

@Namraa310806

Copy link
Copy Markdown
Contributor Author

@auvipy Thanks for pointing me to #10507. I reviewed it and incorporated the relevant stale-entry handling in both purge() and pop().

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

The relevant tests and lint checks are passing.

@auvipy auvipy added this to the 5.7.0 milestone Sep 2, 2026
@auvipy

auvipy commented Sep 5, 2026

Copy link
Copy Markdown
Member

@phanky1 can you review this please?

Comment on lines -604 to -605
except KeyError:
pass

@phanky1 phanky1 Sep 5, 2026 •

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.

Even though this exception is rare it's still possible, so I think we should keep this.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

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?

@auvipy auvipy modified the milestones: 5.7.0, 5.8.0 Sep 5, 2026
@auvipy auvipy modified the milestones: 5.8.0, 5.7.x Sep 12, 2026

@mohithvardhan002 mohithvardhan002 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@phanky1

phanky1 commented Sep 13, 2026

Copy link
Copy Markdown
Contributor

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 pop() since multiple threads can access the same LimitedSet.

@auvipy

auvipy commented Sep 14, 2026

Copy link
Copy Markdown
Member

@MehrazRumman please have a round of review

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

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_entries says "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_entries promises 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 s

Verified: 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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 auvipy left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also merge conflict needs to be fixed

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.

LimitedSet can prematurely evict refreshed items due to stale heap entries

6 participants