mesa icon indicating copy to clipboard operation
mesa copied to clipboard

`_HardKeyAgentSet.select_random()` returns strong references, causing memory leak on removed agents

Open Dilraj07 opened this issue 1 month ago • 0 comments

Bug Description

In _HardKeyAgentSet (which backs model.agents and model.agents_by_type[...]), views returned to the user must be downgraded to standard AgentSet (which uses weak references via WeakKeyDictionary) when inplace=False to prevent memory leaks and allow dead agents to be garbage collected:

https://github.com/mesa/mesa/blob/b1db02ad/mesa/agentset.py#L923-L942

While methods like select(), copy(), shuffle(), sort(), and groupby() correctly downgrade their return value to standard AgentSet, select_random() is missing an override in _HardKeyAgentSet.

Because select_random() is not overridden, calling model.agents.select_random(...) inherits the default implementation from AbstractAgentSet:

return self._update(chosen) if inplace else type(self)(chosen, self.random)

Where type(self) is _HardKeyAgentSet. Consequently, the returned subset holds strong references to the selected agents. When agents are subsequently removed via agent.remove(), they cannot be garbage collected as long as the random sample exists, creating an unbounded memory leak in simulations.

Reproduction Steps

import gc
import weakref
from mesa import Model, Agent
from mesa.agentset import AgentSet, _HardKeyAgentSet

model = Model()
agent = Agent(model)
agent_ref = weakref.ref(agent)

# Sample agents using select_random
sample = model.agents.select_random(1)
print("Sample type:", type(sample))

# Remove agent from the model
agent.remove()
del agent
gc.collect()

# Check if agent was garbage collected
print("Is agent alive after GC?", agent_ref() is not None)

Expected Behavior

  • type(model.agents.select_random(1)) should be AgentSet (using weak references, matching select(), copy(), shuffle(), etc.).
  • Removed agents should be freed by Python's garbage collector.

Actual Behavior

  • type(model.agents.select_random(1)) is _HardKeyAgentSet.
  • Agents remain pinned in memory by hard keys even after removal:
Sample type: <class 'mesa.agentset._HardKeyAgentSet'>
Is agent alive after GC? True

Proposed Fix

Override select_random() in _HardKeyAgentSet (mesa/agentset.py) to downgrade the returned view to a standard AgentSet (weak references) when inplace=False, matching the existing behavior of select(), shuffle(), and sort().

Dilraj07 avatar Oct 26 '26 08:10 Dilraj07