extract_class raises StopIteration when a meta-agent group name is reused after dissolve
What this bug is about
If you create a meta-agent group, dissolve it, and then create another group with the same name, Mesa raises StopIteration.
I ran into this building an example where task forces form and dissolve as the model runs. Once every task force had been dissolved, the next create() with that name blew up.
Repro
Against mesa 4.0.0a0:
from mesa import Agent, Model
from mesa.meta_agents import MetaAgents
class Worker(Agent):
pass
model = Model()
membership = MetaAgents(model)
a, b = Worker(model), Worker(model)
team = membership.create("Team", [a, b]) # fine
membership.dissolve(team) # fine
membership.create("Team", [a, b]) # StopIteration
Traceback
File "mesa/meta_agents/meta_agents_api.py", line 259, in create
meta_agent = _create_meta_agent_instance(...)
File "mesa/meta_agents/meta_agent.py", line 132, in _create_meta_agent_instance
agent_class = extract_class(model.agents_by_type, new_agent_class)
File "mesa/meta_agents/meta_agent.py", line 47, in extract_class
return type(next(iter(agents_by_type[agent_type])))
StopIteration
Why it happens
extract_class (mesa/meta_agents/meta_agent.py:39-47) looks the class up by name, then grabs any live instance to read its type:
agent_type_names = {t.__name__: t for t in agents_by_type}
agent_type = agent_type_names.get(new_agent_class)
if agent_type is None:
return None
return type(next(iter(agents_by_type[agent_type])))
When you dissolve the last group of a given name, deregister_agent empties that agents_by_type set but keeps the key. So:
- the name lookup succeeds (the key is still there), so the None early-return doesn't fire
The retained empty bucket looks intentional — there's a regression test for it (19eff508). So the bucket isn't the problem. The problem is that extract_class asks "what class are the existing instances?" without checking whether any exist.
Why it doesn't show up much
Groups that are created once at startup and never dissolved never hit it. The warehouse example in mesa-examples does exactly that, which is presumably why this hasn't come up. You only hit it if your group structure changes during a run.
Version
mesa 4.0.0a0
I have a fix in mind and can open a PR if that's useful, also happy to be told a different approach is preferred.
Hi @shipitdev, I'd like to contribute to this issue. I have looked into the cause and would be happy to work on the fix and regression tests. I noticed your draft PR #3850 — would it be okay for me to take this up, or are you planning to continue with the existing PR?