mesa icon indicating copy to clipboard operation
mesa copied to clipboard

FixedAgent.remove() raises AttributeError when the agent has no cell

Open AshNicolus opened this issue 5 months ago • 13 comments

Describe the bug

FixedAgent.remove() raises AttributeError when the agent was never placed on a cell (self.cell is None). It calls self.cell.remove_agent(self) unconditionally:

class FixedAgent(Agent, FixedCell):
    def remove(self):
        super().remove()
        self.cell.remove_agent(self)   # AttributeError if self.cell is None
        self._mesa_cell = None

CellAgent.remove() handles the no-cell case safely (it goes through the HasCell setter, which no-ops when the cell is already None), so this is also an inconsistency between the two agent types.

The most visible impact is that Model.remove_all_agents() crashes if any unplaced FixedAgent exists, so the model cannot be torn down.

Expected behavior

Removing a FixedAgent that has no cell should succeed (a no-op for the cell part), the same way CellAgent.remove() does. remove_all_agents() should not crash.

To Reproduce

from mesa import Model
from mesa.discrete_space import FixedAgent

model = Model(rng=1)
agent = FixedAgent(model)   # created but not assigned a cell
agent.remove()              # AttributeError: 'NoneType' object has no attribute 'remove_agent'

Or via teardown:

from mesa import Model
from mesa.discrete_space import FixedAgent

model = Model(rng=1)
FixedAgent(model)               # unplaced
model.remove_all_agents()       # AttributeError

CellAgent in the same situation removes cleanly:

from mesa.discrete_space import CellAgent
CellAgent(model).remove()       # OK

Additional context

Mesa 4.0.0a0 / current main. The fix is a one-line guard mirroring CellAgent:

def remove(self):
    super().remove()
    if self._mesa_cell is not None:
        self._mesa_cell.remove_agent(self)
        self._mesa_cell = None

Note: FixedAgent.remove() has been revised a few times before (#3100, #3466, #3099), but those addressed the setter blocking removal and post-removal state, not the cell is None case. Happy to open a PR if this is worth handling.

AshNicolus avatar Jun 15 '26 07:06 AshNicolus

I am not sure about this.

I agree that getting an exception on remove can crash a simulation and thus be annoying. However, having cell being None is likely also a bug and as such should not be passed over silently. One alternative idea is to add cell as a (keyword) argument to the init of CellAgent and FixedAgent and raise an exception if it is None.

quaquel avatar Jun 16 '26 08:06 quaquel

See also #3687

quaquel avatar Jun 16 '26 08:06 quaquel

Thanks, and agreed that a None cell on a FixedAgent probably signals a setup bug rather than something to swallow silently.

One wrinkle with "require cell at init and raise on None": it's clean for FixedAgent (a patch should always be fixed to a cell), but trickier for CellAgent. CellAgent currently supports cell=None by design: agents are often created and placed in a second step (a = MyAgent(model); a.cell = grid.select_random_empty_cell()), and the HasCell setter explicitly allows moving an agent off-grid by assigning cell = None. Making cell a required non-None init argument would break that create-then-place pattern and the movable-off-grid semantics.

So maybe the split is:

  • FixedAgent: require a cell at init (raise on None), matching its "always fixed to a cell" contract.
  • CellAgent: keep None valid, and just make remove() tolerate it the way it already does today.

This also overlaps #3687 (making cell a proper init parameter), so the init-side change probably belongs there. Happy to go whichever way you prefer: fold the FixedAgent init requirement into #3687, or do the minimal teardown fix here. What's your call?

AshNicolus avatar Jun 17 '26 12:06 AshNicolus

I am still not sure. FixedAgent might at times also be more convenient to use if you can assign cells after agent instantiation.

quaquel avatar Jul 02 '26 12:07 quaquel

That makes sense, and it matches how CellAgent already works (create the agent, assign the cell in a later step).

If we do want FixedAgent to support assigning the cell after instantiation, then an unplaced FixedAgent (cell is None) is a valid transient state by definition, and the only thing needed is for remove() to not crash on it, i.e. the one-line guard from the issue. That keeps FixedAgent flexible and just brings its teardown in line with CellAgent, without requiring cell at init.

Happy to open a small PR for that (the guard plus a regression test) if you're on board. If you'd rather sit with it, no rush.

AshNicolus avatar Jul 02 '26 21:07 AshNicolus

That makes sense, and it matches how CellAgent already works (create the agent, assign the cell in a later step).

If we do want FixedAgent to support assigning the cell after instantiation, then an unplaced FixedAgent (cell is None) is a valid transient state by definition, and the only thing needed is for remove() to not crash on it, i.e. the one-line guard from the issue. That keeps FixedAgent flexible and just brings its teardown in line with CellAgent, without requiring cell at init.

Happy to open a small PR for that (the guard plus a regression test) if you're on board. If you'd rather sit with it, no rush.

occurred to me that since you pointed that CellAgent doesn't get the same "diagnostic" treatment for the identical situation, which made me wonder if the crash here is more of a side effect of FixedAgent's cell setter being unable to accept None, rather than a deliberate choice have you looked into it? also happy to be corrected if I'm missing context.

shipitdev avatar Aug 02 '26 09:08 shipitdev

@shipitdev yes, I think you're right, it's a side effect rather than a deliberate check.

FixedAgent.remove() can't go through the cell setter, because FixedCell's setter refuses any change once a cell is set, and it calls cell.add_agent(self) on whatever it gets, so it can't take None either. So remove() calls self.cell.remove_agent(self) directly, and that's the line that raises AttributeError when cell is None.

CellAgent doesn't hit this because its remove() sets self.cell = None through the normal setter, which handles None. So the guard in remove() just brings FixedAgent in line with CellAgent. It isn't hiding anything the code was meant to catch.

AshNicolus avatar Oct 19 '26 11:10 AshNicolus

I see there are still several open PRs for this. I am still not sure how to handle it.

It seems clear that we want to have the possibility to assign a cell once after agent creation. So None is a valid state when the agent is initialized and on the first set. Afterwards None is not valid anymore. I still think that agent.remove() should raise in case cell is None. If it is None, the agent was never added to the space and so remove is invalid.

I am closing all PRs on this and won't accept new PRs until we reach agreement here.

quaquel avatar Oct 24 '26 17:10 quaquel

I checked main against that rule. It already matches except in two cases, both before the agent has been placed:

your rule main today
unplaced, remove() fine AttributeError
unplaced, agent.cell = None fine AttributeError
placed, agent.cell = None not allowed ValueError: Cannot move agent in FixedCell ✓
placed, move to another cell not allowed same ValueError ✓

So it should only need two small guards: skip add_agent when the first assignment is None, and skip remove_agent in remove() when there's no cell. The placed cases already behave the way you describe.

The PRs for this all look closed now (#3794, #3890), so there's nothing left to choose between. Happy to open one with those two guards and tests if that works for you.

AshNicolus avatar Oct 25 '26 17:10 AshNicolus

  1. The attribute error is not particularly clear. We might want to catch and reraise with a clearer error or at least a clearer message.
  2. I don't think I was clear. A remove() on an unplaced agent should raise. So the first line your your table should read not allowed.
  3. The second line is trickier. I think it should be fine, but it should also leave the agent in the unassigned state.

Hope this helps and thanks for the table that is useful to clarify the reasoning.

quaquel avatar Oct 25 '26 18:10 quaquel

Thanks, that's clearer. So remove() on an unplaced agent raises, with a clear message instead of the AttributeError, and agent.cell = None before placement is a no-op that leaves it unassigned.

Two things I noticed while checking that, worth deciding before a PR:

  1. FixedAgent.remove() deregisters from the model before it touches the cell. So today the unplaced agent is already gone from model.agents by the time the AttributeError is raised. If remove() should raise, it should check first, so a failed remove leaves the agent untouched.
  2. model.remove_all_agents() calls remove() on every agent. With one unplaced FixedAgent in the model it currently stops partway (1 of 3 agents left in my test), and with remove() raising it would still fail. Should remove_all_agents tolerate unplaced fixed agents, or is raising there fine too?

If (1) sounds right and you have a preference on (2), I'll put the PR together.

AshNicolus avatar Oct 25 '26 18:10 AshNicolus

  1. yes makes sense.
  2. raising is fine here to. The main idea is that errors should not be passed over silently. An unplaced fixed agent is in my view an error. So it should always raise.

quaquel avatar Oct 25 '26 18:10 quaquel

Opened #3986 for this.

AshNicolus avatar Oct 25 '26 18:10 AshNicolus