Skip to content

fix(discrete_space): prevent CellCollection lookups from mutating cell occupancy - #4261

Merged
quaquel merged 3 commits into
mesa:mainfrom
arzaanxeng:fix/cellcollection-mutable-agents
Nov 30, 2026
Merged

quaquel merged 3 commits into
mesa:mainfrom
arzaanxeng:fix/cellcollection-mutable-agents

Conversation

@arzaanxeng

@arzaanxeng arzaanxeng commented Nov 28, 2026 •

Copy link
Copy Markdown
Contributor

Note

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

Pre-PR Checklist

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

Summary

This PR fixes an issue in CellCollection.__getitem__() where retrieving agents associated with a cell can expose its internal _agents list directly. In-place modifications to the returned list can corrupt cell occupancy and leave the simulation in an inconsistent state.

Bug / Issue

The current implementation returns self._cells[key] directly without protecting the cell's internal agent list.

Minimal reproducible example:

from mesa import Model
from mesa.discrete_space import CellAgent, OrthogonalMooreGrid

model = Model(rng=42)
grid = OrthogonalMooreGrid((3, 3), random=model.random)

cell = grid[(1, 1)]
agent = CellAgent(model)
agent.cell = cell

print("Before:", cell.agents)

grid.all_cells[cell].clear()

print("After:", cell.agents)
print("Agent location:", agent.cell)
print("Empty flag:", cell.empty)
print("Actual empty:", cell.is_empty)
print("Registered:", agent in model.agents)

Output:

Before: [<CellAgent id=1>]
After: []
Agent location: Cell((1, 1), [])
Empty flag: False
Actual empty: True
Registered: True

The agent remains registered with the model and retains its cell reference, even though the cell no longer contains it. The cached cell.empty flag also becomes inconsistent with cell.is_empty.

Real-world scenario:

In a predator-prey model, a predator might retrieve agents from a target cell and filter unsuitable prey from the returned list using in-place operations such as remove().

Instead of modifying only the candidate list, this can unintentionally remove agents from the cell's internal occupancy list without using Mesa's removal or movement APIs.

Implementation

  • Return a shallow copy of the agent list from CellCollection.__getitem__() unconditionally.
  • Follow the defensive copying behaviour introduced for Cell.agents in Minor (bug) fixes to discrete_space #2687.
  • Update the mapping regression test introduced in fix(discrete_space): snapshot CellCollection mappings #4232 to verify equality rather than identity, following maintainer feedback.
  • Add a non-identity assertion to explicitly verify defensive copying.
  • Retain the regression test verifying cell occupancy consistency.

The lookup requires O(n) time and auxiliary space, where n is the number of agents associated with the requested cell. The agent objects themselves are not copied.

Testing

  • Regression test before the original fix: failed as expected.
  • Regression test after the fix: passed.
  • Discrete space test suite: 185 passed in 5.19s.
  • Complete test suite: 1,442 passed in 50.02s.
  • Ruff lint: passed.
  • Ruff format: passed.
  • Git diff check: passed.

The revised implementation passes the complete local test suite, including the updated mapping test introduced in #4232.

Additional Notes

Following maintainer feedback, the implementation now unconditionally returns a shallow copy, extending the defensive copying behaviour introduced for Cell.agents in #2687.
The existing mapping test introduced in #4232 has been updated to verify equality rather than identity, ensuring consistent defensive copying across all CellCollection lookups.
The revised implementation passes all 1,442 tests.

@github-actions github-actions Bot added the testing Release notes label label Nov 28, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -4.8% [-5.4%, -4.2%] 🔵 +0.6% [+0.5%, +0.8%]
BoltzmannWealth large 🔵 -2.2% [-2.7%, -1.6%] 🟢 -11.8% [-13.0%, -10.3%]
Schelling small 🟢 -4.2% [-4.9%, -3.5%] 🔵 -1.3% [-2.1%, -0.6%]
Schelling large 🔵 -2.0% [-2.9%, -1.1%] 🟢 -12.1% [-15.9%, -8.3%]
WolfSheep small 🔵 +1.6% [+1.3%, +2.0%] 🔵 +3.0% [+1.2%, +4.9%]
WolfSheep large 🔵 +0.4% [-0.3%, +1.1%] 🔵 +1.6% [-0.3%, +3.5%]
SugarscapeG1mt small 🔴 +7.2% [+6.2%, +8.1%] 🔵 +3.2% [+1.6%, +5.0%]
SugarscapeG1mt large 🔵 -2.6% [-3.7%, -1.6%] 🔵 +1.7% [+0.3%, +3.2%]
BoidFlockers small 🔵 -1.6% [-2.0%, -1.2%] 🔵 -0.5% [-0.9%, -0.2%]
BoidFlockers large 🔵 -1.0% [-1.4%, -0.5%] 🔵 -0.4% [-0.7%, -0.1%]
MultiLevelAllianceModel small 🔵 -2.0% [-3.0%, -1.1%] 🔵 -0.0% [-0.6%, +0.6%]
MultiLevelAllianceModel large 🔵 -1.4% [-2.1%, -0.6%] 🔵 -1.6% [-3.0%, -0.2%]

@quaquel

quaquel commented Nov 28, 2026

Copy link
Copy Markdown
Member

I disagree that this is a bug. Rather, its behavior that should be documented. We are all adults here, so why protect everything against any possible misuse?

@arzaanxeng

Copy link
Copy Markdown
Contributor Author

My main motivation was the inconsistency between Cell.agents, which already returns a defensive copy and CellCollection.__getitem__(), which can expose the same internal agent list directly through a public API and I understand the concern about defensive copying and protecting against every possible misuse.

Modifying the latter can leave the cell's occupancy, cached empty flag, and agent's cell reference inconsistent without accessing any private attributes.

However, I agree that if exposing the underlying list is intentional for performance or flexibility, documenting this behavior would be a reasonable alternative.

Would you prefer that I replace the implementation change with documentation explicitly warning users that modifying the returned agent list may affect cell occupancy and that they should use a copy for local filtering operations?

@arzaanxeng

Copy link
Copy Markdown
Contributor Author

also happy to close this PR and open a separate documentation PR explaining the existing behavior with a reference to this discussion. Thanks for the feedback!

@quaquel

quaquel commented Nov 28, 2026

Copy link
Copy Markdown
Member

when did we add the protection on cell.agents?

it also points to a bigger issue that warrant discussion: how do we balance, consistently across the entire code base, protection against gotchas with code speed and user trust (i.e., the pythonic assumption that we are all adults here).

@arzaanxeng

Copy link
Copy Markdown
Contributor Author

I checked the Git history. The protection was introduced in #2687 (commit 22817e774) on February 13, 2025 which you authored .

The same PR made the agent list private, introduced the Cell.agents property returning a copy, and retained direct references to _agents when constructing neighborhoods.

I agree that the inconsistency raises a question about when defensive copying is necessary and when we should trust users to manage mutable references themselves.

@arzaanxeng

Copy link
Copy Markdown
Contributor Author

Hi @quaquel I'd appreciate your thoughts on this whenever you get a chance :)

@quaquel

quaquel commented Nov 29, 2026

Copy link
Copy Markdown
Member

Thanks for checking. Given the motivation behind #2687, I am inclined to favor extending the approach here as well..

Comment thread mesa/discrete_space/cell_collection.py Outdated
while preserving independently supplied mapping values.
"""
agents = self._cells[key]
if agents is key._agents:

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.

why this check?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The intention behind this identity check was to preserve the behavior introduced in #4232, specifically the assertion collection[cell] is supplied_agents in test_cell_collection_accepts_non_dict_mapping.

An unconditional copy would cause this test to fail. Therefore, I added this check to protect the cell's internal _agents list while preserving the identity of independently supplied mapping values.

Would you prefer unconditional defensive copying here and updating the existing test accordingly?

@quaquel quaquel Nov 30, 2026 •

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.

You mean this:

    cell = Cell((0,), random=random.Random(1))
    agent = CellAgent(Model())
    supplied_agents = [agent]
    cells = MappingProxyType({cell: supplied_agents})

    collection = CellCollection(cells, random=random.Random(1))

    assert collection[cell] is supplied_agents
    assert list(collection.agents) == [agent]

I would argue this test is too strong. It should be equal, not identical. So we can, and probably should, always copy.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I've updated the implementation to always return a shallow copy and modified the existing test introduced in #4232 to check equality rather than identity. I've also added a non-identity assertion to explicitly verify the defensive copying behaviour and also updated the PR desc accordingly.

Validation results:

  • Discrete space tests: 185 passed.
  • Complete test suite: 1,442 passed in 50.02s.
  • Ruff lint and formatting: passed.
  • git diff --check: passed.

Thanks for the feedback!

@quaquel
quaquel merged commit 487b45f into mesa:main Nov 30, 2026
17 checks passed
@quaquel quaquel added the bug Release notes label label Nov 30, 2026
EwoutH added a commit to EwoutH/mesa that referenced this pull request Nov 30, 2026
Seven PRs were merged after the notes were drafted: mesa#4284, mesa#3960,
mesa#4261, mesa#3979, mesa#4286, mesa#4216 and mesa#4301. Also moves the release date to
2026-11-30.

Assisted-by: Claude Code
EwoutH added a commit that referenced this pull request Nov 30, 2026
* Update release notes and version for 4.0.0a1

Add the 4.0.0a1 release notes to HISTORY.md, leaving out changes
already released in Mesa 3.5.1 to 3.5.4, and bump the version to
4.0.0a1. Move the #4182 replication id fix, which was added under
4.0.0a0, into the 4.0.0a1 notes where it was released.

Assisted-by: Claude Opus 5.5

* Leave dependabot and pre-commit.ci bumps out of the 4.0.0a1 notes

Assisted-by: Claude Opus 5.5

* Add PRs merged on 2026-11-30 to the 4.0.0a1 notes

Seven PRs were merged after the notes were drafted: #4284, #3960,
#4261, #3979, #4286, #4216 and #4301. Also moves the release date to
2026-11-30.

Assisted-by: Claude Code
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.

2 participants