mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Grid.remove_property_layer("empty") silently removes internal layer and corrupts grid state

Open Dilraj07 opened this issue 1 month ago • 0 comments

Summary

In Grid.__init__, Mesa automatically creates a built-in "empty" property layer (self.create_property_layer("empty", default_value=True, dtype=bool)). This internal layer backs grid.empty, cell.empty, and the fallback coordinate selection in grid.select_random_empty_cell().

While _attach_property_layer() explicitly exempts "empty" from collision checks with cell attributes, remove_property_layer() currently has no guard against removing "empty".

Allowing grid.remove_property_layer("empty") silently strips grid.empty and deletes the empty property descriptor from the cell class, breaking core grid invariants and causing select_random_empty_cell() to raise KeyError: 'empty' when the grid is full.

Reproducible Example

import random
from mesa import Model
from mesa.discrete_space import OrthogonalMooreGrid, CellAgent

grid = OrthogonalMooreGrid((2, 2), capacity=1, random=random.Random(42))
model = Model(rng=42)

# Fill all cells so select_random_empty_cell triggers the property-layer fallback
for cell in grid.all_cells:
    CellAgent(model).cell = cell

# Removing 'empty' silently succeeds without error
grid.remove_property_layer("empty")

# 1. grid.empty attribute is deleted
print(hasattr(grid, "empty"))  # False

# 2. cell.empty descriptor is deleted
cell = grid._cells[(0, 0)]
print(hasattr(cell, "empty"))  # False

# 3. select_random_empty_cell crashes with KeyError instead of ValueError
grid.select_random_empty_cell()
# KeyError: 'empty'

Expected Behavior

Grid.remove_property_layer("empty") should raise a ValueError:

if name == "empty":
    raise ValueError("Cannot remove the built-in 'empty' property layer.")

Dilraj07 avatar Oct 23 '26 21:10 Dilraj07