Skip to content

fix(collections): enforce a shrunken LimitedSet.maxlen immediately - #10796

Open
simpleqt wants to merge 2 commits into
celery:mainfrom
simpleqt:sq/limited-set-maxlen-shrink
Open

simpleqt wants to merge 2 commits into
celery:mainfrom
simpleqt:sq/limited-set-maxlen-shrink

Conversation

@simpleqt

@simpleqt simpleqt commented Oct 4, 2026 •

Copy link
Copy Markdown

Summary

LimitedSet stores maxlen as a plain attribute. The class docstring promises "maxlen is enforced at all times", but assigning a smaller maxlen after construction leaves the set over the limit until the next add() (each add() triggers at most one eviction via purge()). Nothing in Celery assigns maxlen after construction today (celery/worker/state.py builds both sets once), so this is API hardening: it makes the property setter uphold the documented invariant, with tests to pin it.

s = LimitedSet(maxlen=5)
for i in range(5):
    s.add(f"k{i}")
s.maxlen = 2
sorted(s)             # -> ['k3', 'k4']  (was ['k0'..'k4'] until the next add())

Fix

maxlen becomes a property whose setter validates against minlen and evicts down to the new limit immediately — but only when the set is actually over the new limit, because purge() also drops time-expired items and growing the limit must not have that side effect:

@maxlen.setter
def maxlen(self, value):
    value = 0 if value is None else value
    if value < self.minlen:
        raise ValueError('minlen must be a positive number, less or equal to maxlen.')
    self._maxlen = value
    if value and len(self._data) > value:
        self.purge()

__init__ sets _maxlen directly, so the setter no longer runs during construction and needs no attribute guards.

Behaviour changes worth noting

  • s.maxlen = 0 (no limit) on a set with minlen > 0 now raises ValueError — the constructor already rejects that combination, so assignment is now consistent with it.
  • s.maxlen = None is stored as 0 (same as in the constructor).
  • minlen remains unvalidated on assignment (out of scope; only maxlen is guarded, consistent with the constructor's validation order).

Test plan

t/unit/utils/test_collections.py, inside the existing test_LimitedSet class (carries @t.skip.if_win32):

  • test_shrinking_maxlen_evicts_oldest_immediately: shrink evicts the oldest items at once (on main the excess would survive until the next add()).
  • test_growing_maxlen_is_untouched: growing the limit neither evicts nor reorders.
  • test_growing_maxlen_keeps_expired_items: with expired items present, growing maxlen must not purge them away (pins the conditional-purge behaviour).
  • test_shrink_below_minlen_raises: assignment below minlen raises.
  • test_pickle_roundtrip_uses_maxlen: pickling preserves maxlen.

All LimitedSet tests (94) and the worker state tests that use it (revoked, successful_requests, 30) pass; flake8 (repo config) clean.

LimitedSet documents maxlen as enforced at all times, but assigning a
smaller value kept the excess items in place until enough new items
were added to trigger eviction one by one. Make maxlen a property that
purges down to the new limit on assignment and keeps the
maxlen >= minlen invariant for direct assignments too.
Copilot AI lite review requested due to automatic review settings October 4, 2026 15:40
@auvipy auvipy added this to the 5.7.x milestone Oct 4, 2026

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.

Copilot review overview

🟡 Changes recommended

Address the unresolved purge behavior and Windows test-skip review comments.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

Updates LimitedSet.maxlen to validate changes and immediately enforce reduced limits.

Changes:

  • Adds validated maxlen property handling.
  • Adds regression tests for shrinking, growth, validation, and pickling.
File Summary
t/​unit/​utils/​test_collections.py Adds coverage for updated LimitedSet behavior.
celery/​utils/​collections.py Implements validated, immediate maxlen enforcement.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread t/unit/utils/test_collections.py Outdated
assert cm['bar'] == 3


class test_LimitedSet_maxlen_shrink:
@codecov

codecov Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 90.23%. Comparing base (775652a) to head (d3255e3).
⚠️ Report is 14 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #10796      +/-   ##
==========================================
+ Coverage   89.98%   90.23%   +0.24%     
==========================================
  Files         153      153              
  Lines       20937    21069     +132     
  Branches     2516     2544      +28     
==========================================
+ Hits        18841    19011     +170     
+ Misses       1796     1751      -45     
- Partials      300      307       +7     
Flag Coverage Δ
unittests 90.21% <100.00%> (+0.24%) ⬆️

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.

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

Thanks for the PR. I checked it out and ran it against main.

What works

Case main this PR
5 items, then s.maxlen = 2 len(s) stays 5 until the next add() len(s) == 2 immediately, oldest items evicted
s.maxlen = 1 with minlen=2 accepted ValueError
pickle, copy, deepcopy, repr work work, unchanged

The unit tests for LimitedSet and for the worker state that uses it (revoked, successful_requests) pass unchanged.

Scope of the problem

  • Nothing in Celery assigns maxlen after construction; celery/worker/state.py builds both sets once. This is API hardening, which is fine, but the description should not read as a live bug.
  • On main the excess is removed at the very next add(), because add() calls purge() once the set is at maxlen. The test comment says the items stay "until several more items were added"; it is one add.

Suggestions

  1. The setter calls purge() on every assignment, not only when shrinking. purge() also runs time-based expiry, so growing the limit removes expired items as a side effect: with expires=10 and 4 expired items, s.maxlen = 50 leaves the set empty (4 items on main). The comment says "shrinking maxlen must evict", so I would purge only when the set is over the new limit:
   if value and len(self._data) > value:
       self.purge()
  1. getattr(self, 'minlen', 0) and getattr(self, '_data', None) are only needed because __init__ goes through the setter before the other attributes exist. Setting self._maxlen directly in __init__ (it is validated a few lines later anyway) removes both guards and keeps the setter simple.

  2. Behaviour changes worth a line in the description:

    • s.maxlen = 0 (no limit) on a set with minlen > 0 now raises. The constructor already rejects that combination, so this is consistent, but it was accepted on assignment before.
    • s.maxlen = None is now stored as 0.
    • minlen is still not validated on assignment: s.minlen = 9 with maxlen=5 is accepted. Fine to leave out of scope, but then only one of the two is guarded.
  3. Tests:

    • Please move the new tests into the existing test_LimitedSet class instead of a new class after test_ChainMap. That class carries @t.skip.if_win32, and keeping them together avoids deciding the Windows question separately.
    • import pickle inside test_pickle_roundtrip_uses_maxlen is redundant; the module already imports it.
    • A test for growing maxlen on a set with expired items would pin down whichever behaviour you choose in point 1.

None of these is a blocker. With points 1 and 4 addressed this looks good to me.

- purge() on assignment only when the set is over the new limit:
  growing maxlen must not purge, since purge() also drops
  time-expired items (with expires set, growing used to empty the
  set as a side effect).
- __init__ sets _maxlen directly, which removes both getattr guards
  from the setter (it no longer runs during construction).
- the new tests move into test_LimitedSet (carries @t.skip.if_win32),
  the redundant local pickle import is gone, and a new test pins that
  growing maxlen keeps expired items in place.
- the shrink test comment now says 'until the next add()', matching
  the actual main-branch behaviour.

Signed-off-by: simpleqt <[email protected]>
@simpleqt

This comment was marked as spam.

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.

4 participants