Repository navigation
Fix GridCell serialization and property-layer memory retention - #4025
KaguraTart wants to merge 4 commits into
Conversation
codebreaker32
left a comment
There was a problem hiding this comment.
Thanks for this, it's a clean fix. Two small suggestions:
protocolisn't used, so this can be a plain__reduce__instead of__reduce_ex__.- The reducer still calls the base class with a dummy
(0, 0), so a cell class whose__init__requirescapacityandrandomcan't be copied. A small helper returningbase.__new__(base)avoids that (copyreg.__newobj__doesn't work here, pickle rejects it).
Also make sure to rebase once that lands
|
Thanks for the memory-retention reproducer and behavioural round-trip tests, @KaguraTart. This branch now has merge conflicts; main includes Please rebase onto main and resolve the conflicts, preserving those mapping attributes alongside the reducer. Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
176c5aa to
b32aeee
Compare
|
Thanks for the review, @codebreaker32! I've addressed both suggestions in b32aeee:
I've also rebased onto Furthermore, I've added additional regression tests, which cover required I ran Mesa's test suites locally on macOS with Python 3.14.5 at commit b32aeee: 204 discrete-space tests passed, and the full repository suite passed all 1,187 tests. These counts include the regression tests added in this PR. |
|
@KaguraTart, do you have time to resolve the conflict? |
sure, @quaquel! I’ve resolved the merge conflicts. |
|
Thanks for resolving the conflicts and following up on the constructor feedback, @KaguraTart. The branch is mergeable and all checks pass; #4306 also addresses agents referencing the wrong cells after deepcopy. @quaquel, should the overlapping deepcopy work be consolidated here? I'd keep this focused reducer fix and incorporate any distinct regression case from #4306, leaving #4030's neighborhood-cache lifetime fix separate. Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
|
An extra data point for this PR. Moving the state into the reduce tuple's state slot also fixes import copy
from mesa.examples.basic.boltzmann_wealth_model.model import BoltzmannWealth, BoltzmannScenario
m = BoltzmannWealth(scenario=BoltzmannScenario(rng=1)); m.run_for(5)
c = copy.deepcopy(m)
cells = {id(x) for x in c.grid.all_cells}
sum(id(a.cell) not in cells for a in c.agents) # 34 on main
c.run_for(1) # AttributeError: 'tuple' object has no attribute '_agents'A deep-copied wolf-sheep model has 117 such agents. With the state in the state slot, both come back with 0, and the copies stay identical to the originals over 10 more steps. I had opened #4306 for this before seeing your PR, and I've closed it in favour of this one. |
Pre-PR Checklist
Summary
Allow discarded grids and their property-layer arrays to be garbage-collected, and preserve Cell identity when deep-copying models with references between agents and the grid.
Bug / Issue
Related to #4023 — Pickling and deepcopy of spaces keep breaking; fix the cause, not the symptoms.
Each Grid registers its dynamically created GridCell class in the global
copyreg.dispatch_table. That registration keeps the class alive, and its property accessors retain the layer arrays even after the Grid has been collected. Repeatedly creating and discarding grids therefore accumulates retained arrays.Minimal reproduction before this fix:
The behavioural round-trip tests also reproduce a Cell identity problem on the unmodified baseline: after deep-copying a Von Neumann model, an agent can reference a different Cell object from the one stored at the same coordinate in the restored Grid. Continuing the model can then encounter coordinate tuples instead of restored neighbour Cells.
The old reducer passes the Cell's state as a constructor argument. Copying that state traverses references back to the Cell before the new Cell has been memoized, allowing duplicate instances to be created.
Implementation
__reduce_ex__on GridCell classes created during both initialization and state restoration, replacing the two globalcopyregregistrations.unpickle_gridcell(parent, fields)so existing pickles using the previous reduction format remain readable.Testing
Added 24 parameterized regression cases:
Local validation on macOS with Python 3.14.5, using upstream main at
b3bedf72as the baseline:git diff --checkpassed.A separate batch reproduction created, updated, and discarded 40 grids of size 100×100, each with three layer arrays. After garbage collection, the baseline retained 40 dynamic classes and 120 arrays containing 6,800,000 bytes of array data. The fixed version retained zero of these classes or arrays and added no global registry entries. This measures retained objects and array bytes rather than process RSS.
A same-seed Sugarscape comparison (50×50, 200 initial agents, seed 42, 20 steps) produced identical agent, layer, and RNG state fingerprints before and after the change.
Additional Notes
#3914 addressed restoring a single GridCell class for all cells in a Grid. This change addresses the remaining global-registration retention and Cell identity cases.
This is a scoped contribution toward #4023. The broader proposal to redesign per-grid cell classes, cover every example model, and define a general checkpoint/pickling contract remains for further discussion.