Skip to content

Meta-Agents Rewrite - #3811

Merged
tpike3 merged 17 commits into
mesa:mainfrom
falloficaruss:meta-agents-clean
Aug 27, 2026
Merged

tpike3 merged 17 commits into
mesa:mainfrom
falloficaruss:meta-agents-clean

Conversation

@falloficaruss

@falloficaruss falloficaruss commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

Note

This PR is a part of GSoC 2026 project "Hypergraph-Based Meta-Agents for Mesa"

Related: #3016, #3403 mesa/mesa-examples#483
A detailed write-up is available here

Summary

A complete rewrite of Mesa's meta-agent capability. Meta-agents are agents composed of other agents (alliances, households, teams, org units) with overlapping, typed, and nested memberships. This PR replaces the old experimental implementation where each group object held its own member set and membership state was duplicated on member agents with a backend-authoritative architecture: all memberships live as (member, group, relation) triplets in a single store on the model, and every read/write goes through one MetaAgents manager. The module is moved out from mesa.experimental.meta_agents to a top-level mesa.meta_agents package (the old API is removed outright, consistent with the Mesa 4.0 breaking-change window).

Motive

The old implementation scattered membership state across live objects (meta_agent.constituting_agents, agent.meta_agent, agent.meta_agents), which made overlapping and nested hierarchies a bolt-on rather than a structural property, gave no single source of truth for invariants, and offered no indexed queries. The rewrite follows @tpike3's direction: a hypergraph-style conceptual basis, a canonical incidence backend, and a facade-style public API making overlap, typed relations, and multi-level containment first-class while keeping groups as ordinary Mesa agents that participate in scheduling, datacollection, and visualization.

Implementation

Three layers under mesa/meta_agents/:

MembershipBackend (backend.py) :

  • Memberships as (member_id, group_id, relation) triplets with bidirectional _by_agent / _by_group indexes
  • Identity normalized to unique_id, so the store never holds live-object references (no dangling pointers when agents die)
  • Idempotent add/remove, replace_relation, bulk add, cascade remove_agent / remove_group, and assert_invariants for tests

MetaAgents manager (meta_agents_api.py) : the public API, installed once per model (model.meta_agents = MetaAgents(model)) and the intended only write path:

  • create(...) builds a live group agent (dynamic subclass of user-supplied or existing model classes, with meta_attributes / meta_methods) and records edges in bulk
  • add_member / remove_member accept live objects, unique_ids, or group names
  • members_of / groups_of return live AgentSets, optionally filtered by relation
  • query_memberships returns an immutable MembershipView of resolved MembershipEdge(s)
  • deactivate (detach all edges, keep the object) vs dissolve (detach and remove from the model)
  • at_level(n, root=...) - BFS containment depth with shallowest-path semantics; cycle-safe
  • Subscribes to ModelSignals.AGENT_REMOVED so memberships are deactivated automatically when an agent leaves the model

Internal MetaAgent + discovery helpers (meta_agent.py) a thin Agent subclass bound to the manager (its remove() routes through dissolve); find_combinations / evaluate_combination are kept as pure, non-mutating discovery helpers.

Key design decisions:

  • Groups cache nothing — every read resolves live from the backend, so overlap and multi-level nesting (groups of groups) cost nothing structurally
  • Typed relation labels (default "member") allow several roles between the same agent–group pair
  • All query results use deterministic id-stable ordering

Usage Examples

from mesa import Agent, Model
from mesa.meta_agents import MetaAgents

model = Model()
model.meta_agents = MetaAgents(model)

alice, bob = Agent(model), Agent(model)
team = model.meta_agents.create("Team", [alice, bob], Agent)

model.meta_agents.add_member("Team", Agent(model))
model.meta_agents.members_of("Team")        # AgentSet
model.meta_agents.groups_of(alice)          # AgentSet
model.meta_agents.query_memberships(alice)  # MembershipView
model.meta_agents.at_level(1, root=team)    # containment depth
model.meta_agents.dissolve(team)

The in-tree alliance formation model (moved experimental -> advanced) exercises the full surface: agents form alliances via a bilateral Shapley evaluation, alliances become meta-agents that form higher-level alliances, with overlapping memberships tracked by the manager and rendered as a multi-level network.
Additional Notes

  • Docs: new docs/apis/meta_agents.md page (added to the API index) and a migration-guide section with an old→new mapping for the removed helpers (create_meta_agent, agent.meta_agent, constituting_* mutators, etc.)
  • Tests: 44 tests covering the backend (indexes, cascades, invariants, multi-relation), the facade (create/add/remove/query/dissolve/deactivate/at_level incl. cycles and overlap), multi-level scenarios, example-level behavior, and the import namespace; old experimental test suites (~600 lines) removed with the old implementation
  • Benchmarks: MultiLevelAllianceModel small/large configurations added to benchmarks/configurations.py
  • Breaking change: mesa.experimental.meta_agents is gone with no shim; the warehouse example in mesa-examples still uses the old factory and is addressed in a companion PR to mesa-examples: Update warehouse example to the new meta-agents API mesa-examples#483
  • MetaAgents currently observes signals from mesa.experimental.mesa_signals; the dependency boundary needs to be resolved before Mesa 4 release

Future Scope & Limitations

  • make create always create a new group with an explicit join path (today it is join-or-create when a same-class group exists; the alliance example works around this with unique class names)
  • Scale: incremental live-entity index (membership lookups currently scan model.agents per call)
  • Docs: expansion of the how-to page and add a tutorial

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔴 +5.5% [+4.1%, +6.7%] 🔵 -2.2% [-2.4%, -2.0%]
BoltzmannWealth large 🔵 +3.0% [+2.6%, +3.4%] 🔵 -0.4% [-0.9%, +0.1%]
Schelling small 🔴 +4.0% [+3.3%, +4.7%] 🔵 -0.1% [-0.9%, +0.6%]
Schelling large 🔵 +2.0% [+1.5%, +2.5%] 🔵 +2.8% [+1.4%, +3.8%]
WolfSheep small 🔵 +2.6% [+2.2%, +3.0%] 🔵 +1.9% [-2.6%, +6.7%]
WolfSheep large 🔵 +3.7% [+2.9%, +4.4%] 🔴 +5.2% [+3.8%, +6.5%]
SugarscapeG1mt small 🔴 +7.6% [+7.2%, +7.9%] 🔵 +0.5% [-1.1%, +2.2%]
SugarscapeG1mt large 🔴 +4.8% [+4.2%, +5.4%] 🔵 +0.0% [-1.9%, +2.0%]
BoidFlockers small 🔵 -0.1% [-0.5%, +0.3%] 🔵 -0.5% [-1.0%, -0.0%]
BoidFlockers large 🔵 -1.6% [-2.8%, -0.5%] 🔵 -1.5% [-2.4%, -0.4%]

@falloficaruss
falloficaruss force-pushed the meta-agents-clean branch 2 times, most recently from 010b22d to b1c69df Compare August 20, 2026 17:25
@falloficaruss
falloficaruss marked this pull request as ready for review August 21, 2026 08:45
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +0.4% [+0.0%, +0.8%] 🔵 +1.2% [+0.9%, +1.5%]
BoltzmannWealth large 🔵 +0.4% [+0.1%, +0.6%] 🔵 -0.9% [-1.2%, -0.5%]
Schelling small 🔵 -0.5% [-0.9%, -0.1%] 🔵 -0.7% [-1.5%, -0.1%]
Schelling large 🔵 +0.0% [-0.6%, +0.8%] 🔵 -2.5% [-4.0%, -0.7%]
WolfSheep small 🔵 -0.0% [-0.4%, +0.3%] 🔵 -0.0% [-3.6%, +4.0%]
WolfSheep large 🔵 +0.2% [-0.6%, +1.0%] 🔵 -1.6% [-3.2%, -0.3%]
SugarscapeG1mt small 🔵 -1.1% [-1.5%, -0.8%] 🔵 -0.9% [-2.2%, +0.5%]
SugarscapeG1mt large 🔵 +0.6% [+0.0%, +1.2%] 🔵 -0.1% [-1.5%, +1.5%]
BoidFlockers small 🔵 -0.0% [-0.4%, +0.3%] 🔵 +0.6% [+0.0%, +1.1%]
BoidFlockers large 🔵 +0.1% [-0.3%, +0.5%] 🔵 +0.3% [-0.0%, +0.6%]

Comment thread benchmarks/configurations.py Resolved
Comment thread docs/apis/meta_agents.md Resolved
@falloficaruss
falloficaruss requested a review from tpike3 August 21, 2026 14:14
Comment thread mesa/meta_agents/meta_agent.py Resolved
Comment thread mesa/meta_agents/meta_agent.py Resolved
Comment thread mesa/meta_agents/meta_agents_api.py Resolved
Comment thread mesa/meta_agents/meta_agents_api.py Resolved
Comment thread mesa/meta_agents/meta_agents_api.py Resolved
Comment thread mesa/meta_agents/__init__.py Resolved

@tpike3 tpike3 left a comment

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.

@falloficaruss This is really some great work! The membership backend of storing the triplets, ensuring there can only be one, and the assert invariance makes meta-agents much better.

I think the biggest challenge is the lookup bottleneck in the meta_agents_api. So take a look at that, but unless I am missing something I don't think it is leveraging membership backend like it could be.

Overall though great work in moving meta-agents forward.

falloficaruss and others added 6 commits August 23, 2026 11:04
…ld option

Note that the live entity lookup should be cached
and only rebuilt on add or remove calls, with bulk adds and removes as a
future optimization, plus a cache_build staticmethod as a future iteration.

Co-Authored-By: Claude Opus 5 <[email protected]>
@falloficaruss

Copy link
Copy Markdown
Contributor Author

I think the biggest challenge is the lookup bottleneck in the meta_agents_api. So take a look at that, but unless I am missing something I don't think it is leveraging membership backend like it could be.

I have an initial idea of how we could handle this but would need some more thought. We should do this after this PR.

@falloficaruss
falloficaruss requested a review from tpike3 August 23, 2026 14:07
Comment thread mesa/meta_agents/meta_agents_api.py Resolved
@falloficaruss
falloficaruss requested a review from tpike3 August 26, 2026 13:57
falloficaruss and others added 3 commits August 26, 2026 19:52
Document future work for statically typing dynamically generated meta-agents
and reducing Any usage at the creation boundary.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions github-actions Bot added docs Release notes label example Changes the examples or adds to them. experimental Release notes label testing Release notes label labels Aug 27, 2026

@tpike3 tpike3 left a comment

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.

Excellent work for GSoC!!!

@tpike3
tpike3 merged commit 7823f07 into mesa:main Aug 27, 2026
13 of 14 checks passed
quaquel pushed a commit to mesa/mesa-examples that referenced this pull request Oct 28, 2026
The Meta-Agents Rewrite (mesa/mesa#3811, mesa/mesa#3875) moved the package
from mesa.meta_agents to mesa.experimental.meta_agents, and mesa no longer
exports meta_agents at the top level. The warehouse example still imported
the old path:

    from mesa.meta_agents import MetaAgents

Since test_examples.py imports every model module, that ModuleNotFoundError
aborts collection, so the whole examples suite fails before a single test
runs. That is the examples job currently red on mesa main, and therefore on
every open mesa PR.

mesa's own migration guide gives the new path: "Meta-agents still live in
mesa.experimental.meta_agents". Nothing else in the example needs changing,
since the rest already uses the rewritten API through model.meta_agents.

Against mesa main, test_examples.py goes from 1 collection error, 0 tests run
to 24 passed / 1 failed. The remaining failure is VirusAntibodyModel, a
separate pre-existing bug fixed by #496.
@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Release notes label example Changes the examples or adds to them. experimental Release notes label feature Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants