`AgentSet` binary set operations (`&`, `|`, `-`, `^`) raise spurious warning on empty results, drop seeded RNG, and leak strong references from `model.agents`
Describe the bug
AgentSet and _HardKeyAgentSet inherit from collections.abc.MutableSet. In Python, all set operations (__and__, __or__, __sub__, __xor__) construct their return value by calling self._from_iterable(...).
Because neither AbstractAgentSet nor AgentSet implements _from_iterable:
-
Spurious warning and loss of seeded RNG on empty results: When an operation produces an empty set (e.g.,
aset1 - aset2where all agents match, oraset1 & aset2when disjoint), Python callscls(it)withrandom=None. InAgentSet.__init__:if (len(self._agents) == 0) and random is None: warnings.warn( "No Agents specified in creation of AgentSet and no random number generator specified. " "This can make models non-reproducible. Please pass a random number generator explicitly", UserWarning, stacklevel=2, ) random = Random()This triggers a spurious
UserWarning, and attaches a brand new unseededRandom()instance to the result, breaking simulation reproducibility (empty_set.random is model.randomisFalse). -
Strong reference memory leak from
model.agents: When a user performs a set operation onmodel.agents(e.g.model.agents & subsetormodel.agents - subset), Python calls_HardKeyAgentSet(it). This returns a_HardKeyAgentSetholding strong references to the agents, violating Mesa's core design invariant that operations onmodel.agentsmust always return weak-referenceAgentSetinstances to prevent memory leaks (as is done inselect(),groupby(),shuffle(), etc.).
Reproduction
import warnings
from mesa import Agent, Model
from mesa.agentset import AgentSet, _HardKeyAgentSet
model = Model(rng=42)
Agent(model)
Agent(model)
aset = model.agents.copy()
# 1. Spurious warning & loss of model RNG on empty results
with warnings.catch_warnings(record=True) as w:
warnings.simplefilter("always")
diff = aset - aset
print("Warning raised:", len(w) > 0) # True (spurious!)
print("RNG preserved:", diff.random is model.random) # False (broken reproducibility!)
# 2. Strong reference leak from model.agents
inter = model.agents & aset
print("Is strong _HardKeyAgentSet:", isinstance(inter, _HardKeyAgentSet)) # True (leaks strong refs!)
Expected Behavior
- Binary set operations resulting in an empty set should preserve
self.randomand not trigger non-reproducibility warnings. - Set operations on
model.agentsshould return standard weak-referenceAgentSetinstances.
Proposed Solution
Implement _from_iterable on AbstractAgentSet in mesa/agentset.py:
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)