Fix caching_and_replay example for Mesa 3.x compatibility
Summary
The caching_and_replay example was completely broken when run with Mesa 3.x, throwing multiple TypeErrors and AttributeErrors that prevented both recording and replay functionality. This PR fixes all Mesa 3.x compatibility issues, implementing custom serialization/deserialization logic to properly handle the new CellAgent architecture and internal agent management structures.
Bug / Issue
Fixes #289
The example was broken with Mesa 3.x due to fundamental changes in how Mesa handles agents, grids, and positioning:
What was expected: The example should record simulation states to a cache file and replay them deterministically.
What actually happened:
TypeError: 'AgentSet' object does not support item assignmentAttributeError: 'OrthogonalMooreGrid' object has no attribute 'get_cell'- Agent duplication during replay (114 agents instead of 57)
TypeError: AgentSet.__init__() missing required positional argument: 'agents'- Agents had
pos = None(CellAgents don't use pos, they usecell.coordinate) - Visualization crashed with
IndexErrordue to missing position data
Root causes:
- Mesa 3.x CellAgents use
cell.coordinatefor positioning, notpos(which is always None) - Default mesa-replay serialization couldn't handle Mesa 3.x's internal agent tracking dictionaries
- Mesa 3.x uses multiple agent tracking structures (
_agents,_agents_by_type,_all_agents) that weren't being cleared during deserialization - Grid API changed from
get_cell()to direct_cellsdictionary access - Visualization used deprecated
mesa.visualization.ModularServerwhich was removed in Mesa 3.x in favor of Solara-based visualization
Implementation
Core Changes:
-
Custom Serialization (
_serialize_state)- Serialize agent positions using
agent.cell.coordinateinstead ofagent.pos - Save grid state as coordinate → agent ID mapping
- Properly serialize DataCollector state
- Store random number generator state
- Save agent ID counter for consistent restoration
- Serialize agent positions using
-
Custom Deserialization (
_deserialize_state)- Clear all Mesa 3.x agent tracking dictionaries before restoration to prevent duplicates
- Recreate agents with correct cell relationships via
agent.cell = cell - Restore grid structure using Mesa 3.x's
_cellsdictionary - Properly restore DataCollector data without double-counting
- Restore agent ID counter for consistent ID generation
-
Visualization Migration
- Old (deprecated): Used
mesa.visualization.ModularServerwith manual component setup:server = mesa.visualization.ModularServer( model_cls=CacheableSchelling, visualization_elements=[canvas_element, happy_chart, ...], name="Schelling Segregation Model", model_params=model_params, ) - New (Mesa 3.x): Migrated to Solara-based
SolaraVizwith modern component factory pattern:space_component = make_space_component(agent_portrayal) happy_chart = make_plot_component("happy") Page = SolaraViz( model, components=[space_component, happy_chart, get_happy_agents, get_cache_file_status], model_params=model_params, name="Schelling Segregation Model (Cacheable)", ) - Use
AgentPortrayalStylefor consistent agent rendering - Added cache status display showing mode and file size
- Simplified UI with clear record/replay controls
- Error Handling
- Added try-except for
IndexErrorwhen grid is full (agent can't move) - Handle missing cache files gracefully with fallback to record mode
- Clear verbose logging for debugging (optional
verboseparameter)
- Added try-except for
Files Modified:
cacheablemodel.py- Complete rewrite with Mesa 3.x-compatible serializationrun.py- Updated visualization with replay controls and cache statusserver.py- Mesa 3.x visualization componentsmodel.py- Added error handling for full gridREADME.md- Updated documentation with clearer instructions
Testing
Comprehensive testing performed:
Cache Recording
- Successfully records simulations with all agent states preserved
- Cache file creation verified (proper compression and file size)
- Multiple runs with different parameters tested
Replay Determinism
- Agent counts match exactly (57 agents → 57 agents)
- Agent positions match 100% across all steps
- Happy agent counts match datacollector records
- Grid state preserved accurately
- Random number generation consistent
Mesa 3.x Compliance
- CellAgent positioning works correctly (using
cell.coordinate) - Grid API uses proper
_cellsdictionary access - Agent tracking dictionaries properly managed
- AgentSet initialization follows Mesa 3.x patterns
- DataCollector integration verified
Visualization
- Grid rendering works without errors
- Agent colors display correctly (red/blue for types)
- Charts update properly during replay
- Cache status display shows correct information
- UI controls function as expected
Edge Cases
- Full grid scenario handled (agents can't move)
- Missing cache file handled gracefully
- Custom cache file paths work
- Manual simulation stop tested
- Multiple record/replay cycles verified
Test Results:
All agent counts match: Pass
All positions match: Pass
All happy counts match: Pass
DataCollector synchronized: Pass
Replay determinism: 100%
No Regressions:
- Verified that base Schelling model tests pass
- Confirmed other mesa-examples tests unaffected
- Test suite shows no new failures related to these changes
Additional Notes
Technical Decisions:
-
Why custom serialization? Mesa 3.x's internal structures (WeakKeyDictionary for
_agents, CellAgent architecture) don't serialize well with default dill serialization. Custom implementation ensures reliability. -
Agent dict clearing: Mesa 3.x maintains multiple agent tracking dictionaries. All must be cleared before deserialization to prevent agent duplication.
-
CellAgent positioning: Mesa 3.x CellAgents have
pos = Noneby design. They usecell.coordinateinstead, which is what we serialize. -
Incremental cache writing: Cache is written after each step in RECORD mode for persistence, though full write happens on simulation completion.
Compatibility:
- Tested with Mesa 3.x (latest)
- Python 3.10+ required (for mesa-replay)
- No breaking changes to mesa-replay API
- Follows Mesa example standards
Future Improvements:
- Could add
cache_step_rateparameter to UI for large simulations - Could add cache compression options
- Could add replay speed controls
Documentation:
- README simplified with clear record/replay instructions
- Docstrings follow Mesa standards
- No verbose technical explanations
Hi @EwoutH , could you please take a look at this PR when you have a chance? It fixes the caching_and_replay example for Mesa 3.x compatibility (fixes #289).