Skip to content

fix(agentset): implement _from_iterable to preserve random and avoid strong ref leaks in set operations - #4105

Merged
quaquel merged 2 commits into
mesa:mainfrom
Dilraj07:fix-agentset-set-operations-from-iterable
Nov 20, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
Dilraj07:fix-agentset-set-operations-from-iterable

Conversation

@Dilraj07

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

Implements _from_iterable on AbstractAgentSet so binary set operations (&, |, -, ^):

  1. Preserve self.random and suppress spurious non-reproducibility warnings when operations produce an empty set.
  2. Return standard weak-reference AgentSet instances instead of leaking strong-reference _HardKeyAgentSet instances from model.agents.

Bug / Issue

Fixes #4104

In Python's collections.abc.Set, binary set operators (&, |, -, ^) construct results via self._from_iterable(...). Without _from_iterable:

  • Operations yielding empty sets fell back to cls(it) with random=None, triggering a spurious UserWarning and assigning an unseeded stdlib Random() that broke simulation reproducibility.
  • Set operations on model.agents returned a _HardKeyAgentSet holding strong references to agents, violating Mesa's architecture where operations on model.agents must return weak AgentSet instances to avoid memory leaks.

Implementation

Implemented _from_iterable(self, it) on AbstractAgentSet in mesa/agentset.py to construct AgentSet(it, random=self.random).

Testing

  • Added unit tests in tests/test_agentset.py:
    • test_agentset_set_operations_preserve_random_and_suppress_empty_warning
    • test_model_agents_set_operations_return_weak_agentset
    • test_agentset_set_operations_with_python_set
  • Verified all 60 tests in test_agentset.py pass cleanly.
  • Verified all 280 tests across core modules pass with zero regressions.
  • Verified with ruff check and ruff format --check.

Additional Notes

No breaking changes. This ensures consistent memory management and random generator propagation across all set operations.

@github-actions github-actions Bot added the testing Release notes label label Nov 15, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +1.1% [-0.1%, +2.3%] 🔵 +1.4% [+0.5%, +2.3%]
BoltzmannWealth large 🔵 -0.7% [-1.1%, -0.2%] 🔵 -1.0% [-1.8%, -0.2%]
Schelling small 🔵 -0.3% [-0.9%, +0.4%] 🔵 -0.2% [-1.1%, +0.7%]
Schelling large 🔵 -0.1% [-1.4%, +1.2%] 🔵 +0.4% [-0.4%, +1.5%]
WolfSheep small 🔵 +1.0% [+0.4%, +1.5%] 🔵 +3.6% [-0.9%, +8.2%]
WolfSheep large 🔵 +1.6% [+0.8%, +2.5%] 🔵 +1.4% [+0.4%, +2.3%]
SugarscapeG1mt small 🔵 -0.1% [-0.6%, +0.4%] 🔵 +0.1% [-1.6%, +1.8%]
SugarscapeG1mt large 🔵 +1.1% [+0.2%, +2.3%] 🔵 +1.9% [-0.1%, +4.2%]
BoidFlockers small 🔵 +1.7% [+0.4%, +2.9%] 🔵 +1.8% [+0.9%, +2.7%]
BoidFlockers large 🔵 +0.8% [-0.8%, +2.3%] 🔵 +2.3% [+0.5%, +3.9%]
MultiLevelAllianceModel small 🔵 -1.2% [-4.5%, +2.5%] 🔵 +3.7% [+2.3%, +5.4%]
MultiLevelAllianceModel large 🔵 -1.2% [-2.8%, +0.4%] 🔵 +3.6% [+3.0%, +4.4%]

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

Reproduced on main: set operators on model.agents return a _HardKeyAgentSet that keeps removed agents alive, and empty results warn and get an unseeded Random. With this PR all four operators, the reflected forms like {a} - model.agents, and in-place ops come back as weak AgentSets on model.random. Full suite passes.

One issue, see the inline comment: hard-coding AgentSet breaks subclasses.

Small thing: test_agentset_set_operations_with_python_set passes on main too. A remove + gc.collect() check on model.agents - subset would test the leak directly.

Comment thread mesa/agentset.py Outdated
Comment on lines +199 to +205
def _from_iterable(self, it: Iterable[A]) -> AgentSet[A]:
"""Construct an AgentSet from an iterable, preserving the random generator.

This hook is called by collections.abc.Set binary operators (&, |, -, ^).
It ensures returned sets hold weak references and preserve self.random.
"""
return AgentSet(it, random=self.random)

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.

With class MySet(AgentSet), s - {a} returned MySet on main and a plain AgentSet here, while select() still returns MySet. The rest of the file uses type(self)(...) and lets _HardKeyAgentSet downgrade, so:

Suggested change
def _from_iterable(self, it: Iterable[A]) -> AgentSet[A]:
"""Construct an AgentSet from an iterable, preserving the random generator.
This hook is called by collections.abc.Set binary operators (&, |, -, ^).
It ensures returned sets hold weak references and preserve self.random.
"""
return AgentSet(it, random=self.random)
def _from_iterable(self, it: Iterable[A]) -> AbstractAgentSet[A]:
"""Build the result of a set operator (&, |, -, ^), keeping self.random."""
return type(self)(it, self.random)

plus in _HardKeyAgentSet, next to copy():

    def _from_iterable(self, it: Iterable[A]) -> AgentSet[A]:
        return AgentSet(it, self.random)

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.

Thanks for the review @AshNicolus .

@quaquel
quaquel merged commit 71f239a into mesa:main Nov 20, 2026
17 checks passed
EwoutH pushed a commit to EwoutH/mesa that referenced this pull request Nov 22, 2026
…strong ref leaks in set operations (mesa#4105)

* fix(agentset): implement _from_iterable to preserve random and avoid strong ref leaks in set operations

* fix(agentset): preserve subclass type in _from_iterable and test leak prevention

Adapted for 3.5.x: the conflict is only in tests/test_agentset.py, where main's tests follow 4.0-only weighted select_random tests. Only the tests added by mesa#4105 are taken, with their gc, warnings and weakref imports.

(cherry picked from commit 71f239a)

Assisted-by: Claude Opus 5.5
EwoutH added a commit to EwoutH/mesa that referenced this pull request Nov 22, 2026
Add mesa#3913, mesa#4061, mesa#4072, mesa#4105, mesa#4126, mesa#4136, mesa#4141, mesa#4157, mesa#4161 and the Starlette 1.x support backported from mesa#4007, and move the release date to 2026-11-22.

Assisted-by: Claude Opus 5.5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AgentSet binary set operations (&, |, -, ^) raise spurious warning on empty results, drop seeded RNG, and leak strong references from model.agents

3 participants