mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Infinite loop in Grid.select_random_empty_cell() when no empty cells exist

Open Nithin9585 opened this issue 11 months ago โ€ข 1 comments

Describe the bug

When a grid is completely full and you call select_random_empty_cell(), the program hangs forever in an infinite loop. No exception is raised, making it very hard to debug.

This happens in real models when populations grow and fill up all available space, which is pretty common in agent-based simulations.

Expected behavior

Should raise a clear error message instead of hanging:

ValueError: Cannot select random empty cell: grid is full.

To Reproduce

from mesa import Model
from mesa.discrete_space.cell_agent import CellAgent
from mesa.discrete_space.grid import OrthogonalMooreGrid

class SimpleAgent(CellAgent):
    def __init__(self, model, cell):
        super().__init__(model)
        self.cell = cell

model = Model()
grid = OrthogonalMooreGrid(dimensions=(3, 3), capacity=1, random=model.random)

for cell in grid.all_cells:
    SimpleAgent(model, cell)

empty_cell = grid.select_random_empty_cell()

Run this and the program will hang forever at the last line.

Why this happens

The code uses while True which never exits when there are no empty cells:

if self._try_random:
    while True:
        cell = self.all_cells.select_random_cell()
        if cell.is_empty:
            return cell

Nithin9585 avatar Dec 23 '25 12:12 Nithin9585

๐Ÿ“ CodeRabbit Plan Mode

Generate an implementation plan and prompts that you can use with your favorite coding agent.

  • [ ] Create Plan
Examples

๐Ÿ”— Similar Issues

Possible Duplicates

  • ISSUE-2968

Related Issues

  • https://github.com/mesa/mesa/issues/2968
  • https://github.com/mesa/mesa/issues/2982
  • https://github.com/mesa/mesa/issues/2962
  • https://github.com/mesa/mesa/issues/2980
๐Ÿ‘ค Suggested Assignees

๐Ÿงช Issue enrichment is currently in open beta.

You can configure auto-planning by selecting labels in the issue_enrichment configuration.

To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

issue_enrichment:
  auto_enrich:
    enabled: false

๐Ÿ’ฌ Have feedback or questions? Drop into our discord or schedule a call!

coderabbitai[bot] avatar Dec 23 '25 12:12 coderabbitai[bot]