Skip to content

Keep one GridCell class for all cells after unpickling a Grid - #3914

Merged
EwoutH merged 2 commits into
mesa:mainfrom
amanbn8:fix-gridcell-class-after-unpickle
Oct 29, 2026
Merged

EwoutH merged 2 commits into
mesa:mainfrom
amanbn8:fix-gridcell-class-after-unpickle

Conversation

@amanbn8

@amanbn8 amanbn8 commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

After copy.deepcopy or a pickle round trip of a Grid, the property-layer accessors only work on the first cell. Every other cell raises AttributeError for cell.<layer>, cell.empty silently 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.py and I am opening the PR directly since CONTRIBUTING allows that for clear bug fixes.

Reproduction on current main:

import copy, pickle, random
from mesa.discrete_space import OrthogonalMooreGrid

grid = OrthogonalMooreGrid((3, 3), random=random.Random(42))
grid.create_property_layer("sugar", default_value=1.0)

restored = pickle.loads(pickle.dumps(grid))      # same with copy.deepcopy(grid)
len({type(c) for c in restored.all_cells})        # 9, one class per cell
restored._cells[(0, 0)].sugar                     # 1.0
restored._cells[(1, 1)].sugar                     # AttributeError: 'GridCell' object has no attribute 'sugar'
restored._cells[(2, 2)].empty = False
restored.property_layers["empty"][2, 2]           # still True
pickle.dumps(restored)                            # PicklingError: Can't pickle <class 'mesa.discrete_space.grid.GridCell'>

Expected: every cell of the restored grid behaves like the original, i.e. cell.sugar works everywhere, cell.empty writes through to the "empty" layer, and the restored grid can be pickled again.

Root cause: pickle_gridcell/unpickle_gridcell are registered through copyreg for the dynamically created GridCell class, and unpickle_gridcell calls type("GridCell", (parent,), ...) once per cell, so a restored grid ends up with one distinct class per cell. DiscreteSpace.__setstate__ then sets cell_klass to the class of the first cell and Grid.__setstate__ attaches the accessors to that class only. The other cells fall back to the base Cell, where empty is the _empty slot rather than the layer accessor, which is why select_random_empty_cell's fallback path can go stale on a copied grid. The per-cell classes are also never registered with copyreg, so a second pickle.dumps fails. The existing tests only checked cell (0, 0), which is why this went unnoticed.

Implementation

All in mesa/discrete_space/grid.py:

  • unpickle_gridcell no longer creates a class. It restores the cell as a plain instance of the base cell class (the parent argument it already received) and leaves the class to the grid.
  • Grid.__setstate__ recreates a single GridCell class the same way __init__ does, re-registers it with copyreg, 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 in cell_klass.property_layers so remove_property_layer keeps working after a round trip. Cells of some other class that were added at runtime with add_cell are left untouched.
  • Grid.__getstate__ stores the base cell class under cell_klass instead of dropping the key, so a grid whose cells were all removed also restores a usable cell_klass. For grids with cells DiscreteSpace.__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_gridcell by name and get the new behaviour, and _read_only_layers is still defaulted when missing.

Testing

Added test_property_layer_accessors_survive_copy_on_all_cells in tests/discrete_space/test_discrete_space.py. For both copy.deepcopy and a pickle round trip of a 3x3 OrthogonalMooreGrid with a sugar layer it checks that all cells share one class (the grid's cell_klass), that cell_klass.property_layers is {"empty", "sugar"}, that every cell can read and write sugar through to the array, that cell.empty = False on (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 on main (nine distinct classes) and passes with this change.

Ran pytest tests/ -Werror -Wdefault::PendingDeprecationWarning: 848 passed. ruff check and ruff format --check are clean on the two touched files. I also checked by hand that a custom cell_klass with its own __slots__ round-trips with one class and keeps its extra slot, that a cell of an unrelated class added with add_cell keeps its class after unpickling, and that read-only layers on HexGrid and OrthogonalVonNeumannGrid still reject writes after deepcopy.

Additional Notes

unpickle_gridcell still ignores fields[0] (the __dict__ part of the state), so attributes stored in __dict__ on a user-supplied cell_klass without __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.

@github-actions github-actions Bot added the testing Release notes label label Oct 3, 2026
@quaquel

quaquel commented Oct 6, 2026

Copy link
Copy Markdown
Member

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.

@amanbn8

amanbn8 commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

Good point, thanks. I checked what happens with a user-supplied cell class, both on main and on this branch.

The fix already handles it: __getstate__ stores the user's class (the base of the dynamic GridCell), unpickle_gridcell restores each cell as an instance of that class, and Grid.__setstate__ rebuilds a single GridCell on top of it and moves the cells over. So after deepcopy/pickle the cells are still instances of the user's class, there is one GridCell, and the property layer accessors work on every cell. On main a grid built on a custom class fails in the same way as the default case (one class per cell, AttributeError for the layer on all but the first cell, second pickle fails).

I added test_custom_cell_klass_survives_copy_and_pickle, parametrized over two styles of custom cell: one with an extra slot (the pattern from the tutorials) and one without __slots__. It checks the class identity, that the cells' own attributes survive, that the layer accessors read and write through on all cells, and that the restored grid pickles again. Both parametrizations fail on main.

The no-__slots__ case turned up one more gap: instance attributes stored in __dict__ were dropped on the round trip, because unpickle_gridcell only applied the slots part of the state. That was already the case before this PR, but since the function is being touched anyway I included the two-line fix in the same commit.

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.
@EwoutH
EwoutH force-pushed the fix-gridcell-class-after-unpickle branch from 0c87736 to de6e244 Compare October 29, 2026 22:33

@EwoutH EwoutH left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR!

It seems like Jan's comment was addressed. @quaquel could you confirm?

This is blocking #3940, and everything seems good, so merging.

@EwoutH EwoutH added the bug Release notes label label Oct 29, 2026
@EwoutH
EwoutH merged commit b3bedf7 into mesa:main Oct 29, 2026
16 checks passed
EwoutH pushed a commit that referenced this pull request Nov 22, 2026
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants