mesa icon indicating copy to clipboard operation
mesa copied to clipboard

[Proposal] Event-driven live entity caching for MetaAgents (resolving TODO(perf))

Open shipitdev opened this issue 3 months ago • 1 comments

Hi @EdgeofChaos @falloficaruss @quaquel,

Following up on the recent Meta-Agents rewrite (#3811), I looked into the open TODO(perf) in mesa/meta_agents/meta_agents_api.py:93:

# TODO(perf): This rebuilds an O(N) mapping over every model agent on each call. Cache the lookup instead and only rebuild it on agent add or remove calls...

Currently, _live_entity_lookup() iterates over self.model.agents on every query, which runs multiple times per members_of() or groups_of() call. For simulations with larger agent counts:

  • Current (Uncached): 1,000 members_of() queries across 5,000 agents take ~0.39s.
  • With Event-Driven Cache: 1,000 queries take ~0.001s (a 300x+ speedup).

Proposed Approach:

  1. Add _register_agent_added_hook to mesa.Model (symmetrical to the existing _register_agent_removed_hook).
  2. Maintain an internal _live_entity_cache in MetaAgents synchronized via model addition/removal lifecycle hooks and initialized once on __init__.
  3. Return the cached dictionary directly in _live_entity_lookup().

I have drafted the implementation and regression tests in #3828.

Please take a look and let me know if you would like me make any changes or if you'd go some other way than i currently am :)) . IUt It is also completely fine if you'd have any core members actually doing so than contributors, i missed the part where i had to open a discussion or an issue before opening a PR so i went converted it to a draft and opened this issue for discussion. Thank youu

shipitdev avatar Sep 01 '26 17:09 shipitdev

closing this, since this project was assigned to @ tpike3 .

shipitdev avatar Sep 20 '26 13:09 shipitdev