Skip to content

Keep agents on the copied grid's cells after deepcopy - #4306

Closed
prathameshfuke wants to merge 1 commit into
mesa:mainfrom
prathameshfuke:fix/deepcopy-grid-shared-cells
Closed

prathameshfuke wants to merge 1 commit into
mesa:mainfrom
prathameshfuke:fix/deepcopy-grid-shared-cells

Conversation

@prathameshfuke

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

copy.deepcopy of a model whose grid cells hold more than one agent leaves most agents on detached duplicate cells that aren't part of the copied grid. Those duplicates still have their neighbours stored as coordinate tuples, so the copied model crashes on its first neighbourhood lookup. Boltzmann wealth and wolf-sheep both hit it; pickling the same models works.

Bug / Issue

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)

grid_cells = {id(cell) for cell in c.grid.all_cells}
sum(id(a.cell) not in grid_cells for a in c.agents)   # 34 agents on cells the grid doesn't have
c.run_for(1)
# AttributeError: 'tuple' object has no attribute '_agents'   (cell.py, _neighborhood)

For a deep-copied wolf-sheep model it's 117 agents. With one agent per cell (e.g. Schelling) nothing goes wrong, which is why it's easy to miss.

Cause. pickle_gridcell returns the cell's whole state, including _agents, as the reconstructor's arguments: (unpickle_gridcell, (parent, state)). copy.deepcopy copies the arguments before it creates the new cell and records it in its memo. While copying the agents list it reaches the second agent, then agent.cell, which is the same cell that isn't recorded yet, so it reduces and copies that cell again. Every agent after the first one in a cell ends up on such a duplicate, and its connections are still the coordinate tuples from Cell.__getstate__, because Grid.__setstate__ only rebuilds connections for the cells in _cells.

pickle doesn't have this problem, because save_reduce checks whether the object was already saved while saving its arguments. deepcopy has no such check.

Implementation

pickle_gridcell now returns the state in the reduce tuple's state slot: (unpickle_gridcell, (parent,), state). The cell is created and recorded before its agents are copied, so agent.cell resolves to the same copy. Both copy and pickle apply a (dict, slots) state the same way unpickle_gridcell did by hand.

unpickle_gridcell keeps accepting the old (parent, fields) form, so pickles written before this change still load.

Testing

  • Grids: OrthogonalMooreGrid, OrthogonalVonNeumannGrid and HexGrid with 1 and 3 agents per cell, under deepcopy and pickle.
    • On main, deepcopy leaves 12 of 18 agents on detached cells with 3 agents per cell.
    • With this change there are 0. Every cell's connections are cells again, each cell has the same agents as the original, property layers carry over, and all cells share one GridCell class.
  • Examples: wolf-sheep and Boltzmann wealth, deep-copied at step 5. The copy and the original stay identical (agent positions, wealth and energy) for 10 more steps. On main, Boltzmann's copy raises as above.
  • Backward compatibility: a model pickled with the old pickle_gridcell loads with this change (agents, property layer and neighbourhoods intact).
  • Test suite:
    • pytest tests/discrete_space -W error -W default::PendingDeprecationWarning: 194 passed.
    • On the rest of tests/ (1306 passed), the failing set is identical to main's. Those are the visualization tests, which need Solara, Matplotlib and Altair, which I didn't install.
  • ruff check and ruff format --check are clean.

Additional Notes

Related to #3914, which fixed the GridCell class after a pickle round trip. This fixes cell identity under deepcopy.

AI use: I used Claude Code to run a pickle/deepcopy round trip over the bundled examples (which surfaced this), trace it to pickle_gridcell, and draft the change. I checked the cause, the before/after numbers and the test results myself.

pickle_gridcell passed a cell's whole state, including its agents, as
the reconstructor's arguments. copy.deepcopy copies those arguments
before it records the new cell, so for a cell holding several agents
it reached the cell again through agent.cell and copied it a second
time. In the copy, every agent but one per cell then sat on a detached
duplicate whose connections were still coordinate tuples, and the next
neighborhood lookup raised AttributeError (Boltzmann wealth, wolf-sheep).
pickle has a guard for this case, so only deepcopy was affected.

Return the state in the reduce tuple's state slot so the cell is
recorded before its agents are copied. unpickle_gridcell still accepts
the old two-argument form so existing pickles load.
Copilot AI balanced review requested due to automatic review settings November 30, 2026 22:32

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.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.8% [-1.7%, +0.1%] 🔵 +0.5% [+0.3%, +0.7%]
BoltzmannWealth large 🔵 -0.4% [-0.9%, +0.1%] 🔵 -1.3% [-2.9%, +0.6%]
Schelling small 🔵 -1.2% [-1.7%, -0.7%] 🔵 -0.8% [-1.6%, +0.0%]
Schelling large 🟢 -3.6% [-4.4%, -3.1%] 🟢 -5.3% [-6.4%, -4.1%]
WolfSheep small 🔵 +0.9% [+0.5%, +1.3%] 🔵 +1.6% [-0.1%, +3.4%]
WolfSheep large 🔵 -0.3% [-0.9%, +0.6%] 🔵 +1.8% [+0.5%, +3.3%]
SugarscapeG1mt small 🔵 -3.1% [-3.7%, -2.4%] 🔵 -0.8% [-2.3%, +0.8%]
SugarscapeG1mt large 🔵 -1.8% [-4.9%, +0.9%] 🔵 -2.3% [-4.1%, -0.4%]
BoidFlockers small 🔵 +0.4% [+0.1%, +0.7%] 🔵 +1.5% [+1.0%, +2.0%]
BoidFlockers large 🔵 -0.6% [-1.1%, -0.3%] 🔵 +0.3% [+0.0%, +0.5%]
MultiLevelAllianceModel small 🔵 +1.8% [+0.3%, +3.3%] 🔵 +0.8% [+0.3%, +1.4%]
MultiLevelAllianceModel large 🔵 +1.5% [-0.4%, +3.5%] 🔴 +9.7% [+7.0%, +12.8%]

@mesa-triage-bot

Copy link
Copy Markdown

Thanks for the Boltzmann reproducer, @prathameshfuke. I reproduced the 34 detached agents and next-step crash on main; applying your reducer change in memory gives zero detached agents and a successful next step. #4025 already contains the same state-slot correction, alongside round-trip tests and a memory-retention fix.

@quaquel, should this fix proceed separately or be consolidated into #4025? I'd consolidate into #4025 because it already covers the same cause and includes regression tests.

@prathameshfuke, please inspect and resolve the failing codecov/patch check, or link evidence explaining the failure. No log was supplied, so I couldn't determine whether it is related, stale, or flaky.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

@arzaanxeng arzaanxeng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

noticed that unpickle_gridcell() still reconstructs the cell using parent((0, 0)). Would this remain compatible with user-defined cell classes whose constructors require additional arguments?

PR #4025 appears to address this by allocating the instance through base.__new__(base), while also implementing the state-slot correction and adding regression tests.

Given the overlap, would consolidating these changes into #4025 be preferable?

Additionally, it would be helpful to include the multi-agent deepcopy reproducer as a committed regression test if this PR proceeds independently.

@prathameshfuke

Copy link
Copy Markdown
Contributor Author

You're right, #4025 already makes the same state-slot change and also avoids re-running the cell constructor, so it's the better place for this. Closing in favour of it. I'll leave the multi-agent reproducer on #4025 in case it's useful there.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants