Repository navigation
fix(discrete_space): prevent CellCollection lookups from mutating cell occupancy - #4261
Conversation
|
Performance benchmarks:
|
|
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? |
|
My main motivation was the inconsistency between 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? |
|
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! |
|
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). |
|
I checked the Git history. The protection was introduced in #2687 (commit 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. |
|
Hi @quaquel I'd appreciate your thoughts on this whenever you get a chance :) |
|
Thanks for checking. Given the motivation behind #2687, I am inclined to favor extending the approach here as well.. |
| while preserving independently supplied mapping values. | ||
| """ | ||
| agents = self._cells[key] | ||
| if agents is key._agents: |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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!
* 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
Note
This PR is a bug fix, not a new feature or enhancement.
Pre-PR Checklist
Summary
This PR fixes an issue in
CellCollection.__getitem__()where retrieving agents associated with a cell can expose its internal_agentslist 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:
Output:
The agent remains registered with the model and retains its cell reference, even though the cell no longer contains it. The cached
cell.emptyflag also becomes inconsistent withcell.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
CellCollection.__getitem__()unconditionally.Cell.agentsin Minor (bug) fixes to discrete_space #2687.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
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.agentsin #2687.The existing mapping test introduced in #4232 has been updated to verify equality rather than identity, ensuring consistent defensive copying across all
CellCollectionlookups.The revised implementation passes all 1,442 tests.