mesa icon indicating copy to clipboard operation
mesa copied to clipboard

AgentSet.do/shuffle_do/map calls removed agents mid-iteration

Open 0xnithinmys opened this issue 1 month ago • 0 comments

The weak-ref AgentSet only checks agentref() is not None it never re-checks agent in self._agents. An agent removed by an earlier call in the same loop is still invoked. _HardKeyAgentSet (what model.agents actually returns) already has this guard; the two implementations disagree.

Trigger:

m.agents.select(lambda x: True).shuffle_do("step")  # derived → weak AgentSet
# b.step() fires even after a.step() called b.remove()

Consequences: crash (AttributeError on self.cell), silent wrong results (dead agent acts again), or non-reproducibility (depends on GC timing).

Fix:

# agentset.py – AgentSet.do / shuffle_do / map
if (agent := agentref()) is not None and agent in self._agents:
    ...

Regression test: Mirror tests/test_agentset.py:894-929 for the weak AgentSet (killer discards victim mid-loop; assert not victim.ran).


select_random(weights, replace=False) zero-weight agents returned

Location: mesa/agentset.py:262-273

Bug: The A-Res branch assigns key 0.0 to zero-weight agents and takes the top sample_size keys. When positive_count < sample_size ≤ len(aset), the slice pads with zero-weight agents silently.

Trigger:

aset.select_random(3, weights=[1.0, 0.0, 0.0, 0.0, 0.0], replace=False)
# returns weight-1 agent + 2 weight-0 agents — no error

Fix:

n_positive = sum(1 for wi in w if wi > 0)
if sample_size > n_positive:
    raise ValueError(f"Cannot sample {sample_size}: only {n_positive} have positive weight.")

Regression test: pytest.raises(ValueError) for the trigger above.


Cell.add_agent corrupts empty flag on rejected placement

Location: mesa/discrete_space/cell.py:150-156

Bug: self.empty = False is written before the capacity check. If the check raises CellFullException, the flag is not rolled back leaving cell.empty == False while cell.is_empty == True. On a Grid, this also corrupts property_layers["empty"], so select_random_empty_cell() silently excludes that cell forever.

Trigger: Any capacity=0 cell that an agent attempts to enter.

Fix: Move the flag assignment after the successful append:

def add_agent(self, agent):
    n = len(self._agents)
    if self.capacity is not None and n >= self.capacity:
        raise CellFullException(self.coordinate)
    self._agents.append(agent)
    self.empty = False          # only set on success

Regression test: Assert cell.empty is True and property_layers["empty"][(0,0)] after a rejected placement on a capacity=0 cell.


Areas checked

Event scheduling, DataCollector, ContinuousSpace torus math, grid BFS/torus, CellCollection, Network KD-tree, AgentSet pickling. VoronoiGrid.__init__ passes raw capacity to cell_klass instead of numeric_capacity, but _build_cell_polygons overwrites it immediately — latent, not filed.

0xnithinmys avatar Oct 05 '26 09:10 0xnithinmys