mesa icon indicating copy to clipboard operation
mesa copied to clipboard

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

Open Dilraj07 opened this issue 2 weeks ago • 0 comments

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:

  1. Spurious warning and loss of seeded RNG on empty results: When an operation produces an empty set (e.g., aset1 - aset2 where all agents match, or aset1 & aset2 when disjoint), Python calls cls(it) with random=None. In AgentSet.__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 unseeded Random() instance to the result, breaking simulation reproducibility (empty_set.random is model.random is False).

  2. Strong reference memory leak from model.agents: When a user performs a set operation on model.agents (e.g. model.agents & subset or model.agents - subset), Python calls _HardKeyAgentSet(it). This returns a _HardKeyAgentSet holding strong references to the agents, violating Mesa's core design invariant that operations on model.agents must always return weak-reference AgentSet instances to prevent memory leaks (as is done in select(), 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

  1. Binary set operations resulting in an empty set should preserve self.random and not trigger non-reproducibility warnings.
  2. Set operations on model.agents should return standard weak-reference AgentSet instances.

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)

Dilraj07 avatar Nov 15 '26 07:11 Dilraj07