Skip to content

Fix GridCell serialization and property-layer memory retention - #4025

Open
KaguraTart wants to merge 4 commits into
mesa:mainfrom
KaguraTart:codex/grid-property-layer-lifetime
Open

KaguraTart wants to merge 4 commits into
mesa:mainfrom
KaguraTart:codex/grid-property-layer-lifetime

Conversation

@KaguraTart

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

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:

import gc
import weakref
from random import Random

from mesa.discrete_space import OrthogonalMooreGrid

grid = OrthogonalMooreGrid((100, 100), random=Random(42))
grid.create_property_layer("sugar", default_value=1.0)
layer_ref = weakref.ref(grid.sugar)
del grid
gc.collect()
assert layer_ref() is None  # Fails 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

  • Install the existing reduction helper as __reduce_ex__ on GridCell classes created during both initialization and state restoration, replacing the two global copyreg registrations.
  • Return the base Cell constructor, constructor arguments, and state separately. This lets pickle/deepcopy memoize the Cell before restoring state and following cyclic references.
  • Retain unpickle_gridcell(parent, fields) so existing pickles using the previous reduction format remain readable.

Testing

Added 24 parameterized regression cases:

  • Nine cases covering collection of grids, dynamic classes, and writable/read-only layer arrays across three Grid types and original/deepcopy/pickle instances.
  • Three cases verifying that a retained Cell keeps its layer usable until the Cell itself is released.
  • Six behavioural round-trip cases: run a model for three steps, copy or pickle it, then run the original and restored models for five more steps. Check Cell identity, connections, agent positions, occupancy, property layers, and both RNG states.
  • Six compatibility cases covering the previous reduction format with pickle protocols 0–5, including read-only layers and a second round trip.

Local validation on macOS with Python 3.14.5, using upstream main at b3bedf72 as the baseline:

  • Unmodified baseline: 13 failed, 11 passed for the new cases.
  • Fixed version: 24 passed for the new cases.
  • Discrete-space suite: 161 passed.
  • Full repository suite with CI warning settings: 1,045 passed, including all nine Chromium example-page tests.
  • Doctests: 8 passed, 2 skipped; both skips are explicitly marked in the source.
  • Ruff 0.16.10 lint and formatting checks passed for both changed files.
  • git diff --check passed.

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.

Copilot AI balanced review requested due to automatic review settings October 30, 2026 13:46
@github-actions github-actions Bot added the testing Release notes label label Oct 30, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this, it's a clean fix. Two small suggestions:

  1. protocol isn't used, so this can be a plain __reduce__ instead of __reduce_ex__.
  2. The reducer still calls the base class with a dummy (0, 0), so a cell class whose __init__ requires capacity and random can't be copied. A small helper returning base.__new__(base) avoids that (copyreg.__newobj__ doesn't work here, pickle rejects it).

Also make sure to rebase once that lands

@mesa-triage-bot

Copy link
Copy Markdown

Thanks for the memory-retention reproducer and behavioural round-trip tests, @KaguraTart. This branch now has merge conflicts; main includes _mesa_scale and _mesa_offset in both GridCell class definitions touched here.

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.

@KaguraTart
KaguraTart requested a balanced review from Copilot November 16, 2026 01:31

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.

@KaguraTart
KaguraTart force-pushed the codex/grid-property-layer-lifetime branch from 176c5aa to b32aeee Compare November 16, 2026 02:01
@KaguraTart

Copy link
Copy Markdown
Contributor Author

Thanks for the review, @codebreaker32! I've addressed both suggestions in b32aeee:

  1. Switched to __reduce__ and removed the unused protocol argument.
  2. Added a helper using base.__new__(base) so restoration no longer calls the Cell constructor. The legacy unpickling helper now uses the same allocator.

I've also rebased onto main at f66b5cf2, preserving _mesa_scale and _mesa_offset in both GridCell class definitions.

Furthermore, I've added additional regression tests, which cover required capacity and random arguments, position mappings, and repeated deepcopy/pickle round trips.

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.

@quaquel

quaquel commented Nov 30, 2026

Copy link
Copy Markdown
Member

@KaguraTart, do you have time to resolve the conflict?

@KaguraTart

Copy link
Copy Markdown
Contributor Author

@KaguraTart, do you have time to resolve the conflict?

sure, @quaquel! I’ve resolved the merge conflicts.

@mesa-triage-bot

Copy link
Copy Markdown

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.

@prathameshfuke

Copy link
Copy Markdown
Contributor

An extra data point for this PR. Moving the state into the reduce tuple's state slot also fixes copy.deepcopy when a cell holds more than one agent. On main, deepcopy copies the reduce arguments before it records the new cell, so it reaches the cell again through agent.cell and creates a duplicate. Every agent after the first one in a cell ends up on a detached cell whose connections are still coordinate tuples:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants