mesa icon indicating copy to clipboard operation
mesa copied to clipboard

`ContinuousSpaceAgent.remove()` raises `AttributeError` on repeated removal instead of safe no-op

Open Dilraj07 opened this issue 2 weeks ago • 1 comments

Describe the bug

In Mesa, agent.remove() is expected to be idempotent across agent classes: calling remove() once deletes the agent from the model and space, while subsequent calls safely no-op (for instance, Agent.remove() catches KeyError via contextlib.suppress, and CellAgent.remove() safely exits when self.cell is None).

However, calling agent.remove() more than once on a ContinuousSpaceAgent crashes with an unhandled AttributeError:

AttributeError: 'NoneType' object has no attribute '_remove_agent'

Root Cause

In mesa/experimental/continuous_space/continuous_space_agents.py:

def remove(self) -> None:
    """Remove and delete the agent from the model and continuous space."""
    super().remove()
    self.space._remove_agent(self)
    self._mesa_index = None
    self.space = None

On the first call, self.space is set to None. On any subsequent call, self.space._remove_agent(self) attempts to access _remove_agent on None.

Reproduction

import numpy as np
from mesa import Model
from mesa.experimental.continuous_space import ContinuousSpace, ContinuousSpaceAgent

model = Model(rng=42)
dimensions = np.asarray([[0, 10], [0, 10]])
space = ContinuousSpace(dimensions, torus=False, random=model.random)

agent = ContinuousSpaceAgent(space, model)
agent.position = np.array([5.0, 5.0])

agent.remove()  # First call succeeds
agent.remove()  # Second call crashes: AttributeError: 'NoneType' object has no attribute '_remove_agent'

Expected Behavior

Calling agent.remove() on an already-removed ContinuousSpaceAgent should safely no-op, preserving lifecycle consistency with base Agent and CellAgent.

Proposed Solution

Guard the space deregistration with if self.space is not None::

def remove(self) -> None:
    """Remove and delete the agent from the model and continuous space."""
    super().remove()
    if self.space is not None:
        self.space._remove_agent(self)
        self._mesa_index = None
        self.space = None

Dilraj07 avatar Nov 15 '26 07:11 Dilraj07

Practical ABM Workflows Leading to Repeated Removal

In agent-based modeling in continuous space, repeated removal occurs in several common simulation patterns:

1. Multi-Agent Interactions within the Same Step (Predation, Combat, Disease)

In continuous space, agents query proximity via get_neighbors_in_radius(). When multiple agents interact concurrently in a single tick:

  • Predator-Prey: Two predators (or a predator and an environmental hazard) may simultaneously target the same prey agent within their interaction radii during the same step. The first predator executes prey.remove(). When the second predator processes its caught targets and calls prey.remove(), the simulation crashes with an unhandled AttributeError.
  • Concurrent Death Events: A prey agent's energy reaches 0 during its own step (calling self.remove()), while a predator hunting in the same sub-step also eliminates it.

Without idempotency, model developers are forced to write defensive, fragile checks before every removal (e.g. if getattr(agent, "space", None) is not None: agent.remove()).

2. Pairwise Collision / Elimination Loops

Continuous space models that resolve particle collisions, flocking boundaries, or physical combat iterate over neighbors:

for agent in space.active_agents:
    for other in agent.get_neighbors_in_radius(collision_radius):
        if resolves_to_elimination(agent, other):
            other.remove()

If Agent B is eliminated by Agent A, and later in the same sweep Agent C also collides with Agent B, calling other.remove() crashes.

3. Staged Activation & Batched Cleanup Queues

In multi-stage simulations, models commonly separate the active phase from the cleanup phase:

  • Agents flag themselves or call self.remove() upon hitting a terminal boundary or event.
  • A centralized death/event queue (e.g., model.dead_agents or an event queue) processes end-of-tick cleanups (for a in dead_agents: a.remove()). If any agent was already removed during an event callback, the end-of-tick sweep crashes.

4. Behavioral Consistency Across Mesa Agent Classes

  • In Agent.remove(): uses contextlib.suppress(KeyError) so subsequent removals are safe no-ops.
  • In CellAgent.remove(): checks if self.cell is not None: and safely exits. ContinuousSpaceAgent.remove() was the only agent implementation that was not idempotent, crashing with AttributeError: 'NoneType' object has no attribute '_remove_agent' and triggering a ValueError when registered with NumpyAgentDataSet.

Dilraj07 avatar Nov 16 '26 02:11 Dilraj07