Repository navigation
Keep one GridCell class for all cells after unpickling a Grid - #3914
Conversation
|
I am not sure about this fix. What happens is a user wants to use a custom subclass of GridCell? This is not covered by the new tests. |
|
Good point, thanks. I checked what happens with a user-supplied cell class, both on The fix already handles it: I added The no- |
unpickle_gridcell created a fresh GridCell class for every cell, and Grid.__setstate__ re-attached the property_layer accessors only to the class of the first cell. After copy.deepcopy or a pickle round trip, cell.<layer> raised AttributeError on every cell except the first, cell.empty fell back to the Cell._empty slot instead of the "empty" layer, and pickling the restored grid a second time failed because the per-cell classes were never registered with copyreg. unpickle_gridcell now restores cells as plain instances of the base cell class, and Grid.__setstate__ recreates a single GridCell class exactly as __init__ does, moves all cells to it, registers it with copyreg and attaches the accessors (recording them in cell_klass.property_layers as well). The base class is kept in the pickled state so a grid without cells round-trips too.
Add a test that builds a grid on a user-supplied cell class, once with an extra slot and once without __slots__, and checks that after deepcopy and pickle the cells still share one GridCell class derived from that class, keep their own attributes, keep working property_layer accessors, and can be pickled again. The __slots__ case already passed. The other case lost the instance attributes, because unpickle_gridcell only restored the slots part of the state and ignored the __dict__ part, so restore that part as well.
0c87736 to
de6e244
Compare
Adapted for 3.5.x: uses the HasPropertyLayers API (_mesa_properties, _mesa_property_layers) instead of 4.0's property_layers and read-only layers; tests adapted the same way. (cherry picked from commit b3bedf7) Assisted-by: Claude Opus 5.5
Pre-PR Checklist
Summary
After
copy.deepcopyor a pickle round trip of aGrid, the property-layer accessors only work on the first cell. Every other cell raisesAttributeErrorforcell.<layer>,cell.emptysilently stops writing to the"empty"layer, and the restored grid cannot be pickled a second time. Anything that deep-copies or pickles a model holding a grid, for example to save and restore it or to hand it to another process, hits this.Bug / Issue
There is no issue filed for this; I ran into it while reading the pickling code in
mesa/discrete_space/grid.pyand I am opening the PR directly since CONTRIBUTING allows that for clear bug fixes.Reproduction on current
main:Expected: every cell of the restored grid behaves like the original, i.e.
cell.sugarworks everywhere,cell.emptywrites through to the"empty"layer, and the restored grid can be pickled again.Root cause:
pickle_gridcell/unpickle_gridcellare registered throughcopyregfor the dynamically createdGridCellclass, andunpickle_gridcellcallstype("GridCell", (parent,), ...)once per cell, so a restored grid ends up with one distinct class per cell.DiscreteSpace.__setstate__then setscell_klassto the class of the first cell andGrid.__setstate__attaches the accessors to that class only. The other cells fall back to the baseCell, whereemptyis the_emptyslot rather than the layer accessor, which is whyselect_random_empty_cell's fallback path can go stale on a copied grid. The per-cell classes are also never registered withcopyreg, so a secondpickle.dumpsfails. The existing tests only checked cell(0, 0), which is why this went unnoticed.Implementation
All in
mesa/discrete_space/grid.py:unpickle_gridcellno longer creates a class. It restores the cell as a plain instance of the base cell class (theparentargument it already received) and leaves the class to the grid.Grid.__setstate__recreates a singleGridCellclass the same way__init__does, re-registers it withcopyreg, moves every restored cell to it via__class__assignment (the base class and the empty-__slots__subclass have the same layout, so this is allowed), and then runs the existing accessor re-attachment, now also recording each name incell_klass.property_layerssoremove_property_layerkeeps working after a round trip. Cells of some other class that were added at runtime withadd_cellare left untouched.Grid.__getstate__stores the base cell class undercell_klassinstead of dropping the key, so a grid whose cells were all removed also restores a usablecell_klass. For grids with cellsDiscreteSpace.__setstate__sets the same value from the first cell, so this is only relevant for the empty case.Old pickles still load: they reference
unpickle_gridcellby name and get the new behaviour, and_read_only_layersis still defaulted when missing.Testing
Added
test_property_layer_accessors_survive_copy_on_all_cellsintests/discrete_space/test_discrete_space.py. For bothcopy.deepcopyand a pickle round trip of a 3x3OrthogonalMooreGridwith asugarlayer it checks that all cells share one class (the grid'scell_klass), thatcell_klass.property_layersis{"empty", "sugar"}, that every cell can read and writesugarthrough to the array, thatcell.empty = Falseon(2, 2)shows up in the"empty"layer, that a layer created after the round trip reaches every cell, and that the restored grid pickles again with the values intact. The test fails onmain(nine distinct classes) and passes with this change.Ran
pytest tests/ -Werror -Wdefault::PendingDeprecationWarning: 848 passed.ruff checkandruff format --checkare clean on the two touched files. I also checked by hand that a customcell_klasswith its own__slots__round-trips with one class and keeps its extra slot, that a cell of an unrelated class added withadd_cellkeeps its class after unpickling, and that read-only layers onHexGridandOrthogonalVonNeumannGridstill reject writes afterdeepcopy.Additional Notes
unpickle_gridcellstill ignoresfields[0](the__dict__part of the state), so attributes stored in__dict__on a user-suppliedcell_klasswithout__slots__are dropped on the round trip. That was already the case before and is separate from this fix, so I left it alone; happy to follow up if you want it addressed.