mesa icon indicating copy to clipboard operation
mesa copied to clipboard

Backends mutate shared AgentPortrayalStyle instances

Open priyanshux-dev opened this issue 1 week ago • 5 comments

Describe the bug

MatplotlibBackend.collect_agent_data() and AltairBackend.collect_agent_data() mutate an AgentPortrayalStyle instance when resolving an agent’s position.

Both backends assign the resolved position directly to aps.x and aps.y. When the same portrayal instance is reused across agents or frames, the resolved position from one agent remains on the shared object and can affect subsequent collection calls.

Portrayals returned by agent_portrayal should be treated as configuration data and should not be modified by a backend.

Real-world impact

Mesa examples may create a new portrayal object for each call, but users can also reuse or cache an AgentPortrayalStyle to avoid repeated object creation. When the same instance is returned for multiple agents or frames, a backend’s mutation can cause later agents to use coordinates resolved for an earlier agent, making them appear in the wrong location.

To Reproduce

from types import SimpleNamespace
from unittest.mock import MagicMock

from mesa.visualization.backends.altair_backend import AltairBackend
from mesa.visualization.backends.matplotlib_backend import MatplotlibBackend
from mesa.visualization.components import AgentPortrayalStyle

space = SimpleNamespace(
    agents=[
        SimpleNamespace(position=(0, 1)),
        SimpleNamespace(position=(2, 3)),
    ]
)

shared_portrayal = AgentPortrayalStyle(x=None, y=None)

for backend_cls in (MatplotlibBackend, AltairBackend):
    backend = backend_cls(space_drawer=MagicMock())

    data = backend.collect_agent_data(
        space,
        lambda agent: shared_portrayal,
    )

    assert data["loc"].tolist() == [[0, 1], [2, 3]]
    assert (shared_portrayal.x, shared_portrayal.y) == (None, None)

On the affected backends, the first agent’s position is written onto shared_portrayal. The second agent may then be collected with the same coordinates as the first.

Expected behavior

  • Neither backend should mutate the AgentPortrayalStyle returned by agent_portrayal.
  • Automatic position resolution should occur independently for each agent.
  • Reusing or caching a portrayal instance across agents or frames should not change which coordinates are collected.
  • Existing explicit x and y coordinates should remain supported.

Affected components

  • mesa/visualization/backends/matplotlib_backend.py
  • mesa/visualization/backends/altair_backend.py

Suggested regression coverage

  • A shared portrayal used by two agents at different positions.
  • Repeated collection calls using the same portrayal.
  • Explicit coordinates remaining unchanged.
  • The shared portrayal remaining unchanged after collection.

priyanshux-dev avatar Nov 22 '26 16:11 priyanshux-dev

I’ve updated the issue to separate this shared-AgentPortrayalStyle mutation bug from the unrelated Matplotlib size=0 behavior. The issue now covers coordinate mutation and shared/cached portrayals only.

priyanshux-dev avatar Nov 23 '26 03:11 priyanshux-dev

please give a real use case, not a contrived one.

quaquel avatar Nov 23 '26 21:11 quaquel

To clarify, I haven’t encountered this in a live model or received a report from one. I reproduced the behavior with a minimal example using one shared style per agent type, where later agents can inherit the first agent’s coordinates; the example is in #4208. Is that reproduction sufficient to consider the issue and its fix, or would you prefer to wait for a concrete model report?

priyanshux-dev avatar Nov 24 '26 04:11 priyanshux-dev

Please post it here as well, so we track the discussion in 1 location. This deals with a part of the code base I am not intimately familiar with. So, I need a good example and a clear explanation based upon which I can figure out what is going on and how to fix it.

quaquel avatar Nov 24 '26 06:11 quaquel

Sure, @quaquel — I’ll do my best to explain the behavior clearly.

I found it by reading collect_agent_data, and I couldn't find any bundled Mesa example that triggers it. Every example builds a fresh AgentPortrayalStyle on each call (e.g. portrayal = AgentPortrayalStyle(...) inside the portrayal function), so the mutation never survives long enough to matter there. The bug only appears when a portrayal is reused — most naturally, cached per agent type. That's the case I want to walk through, with the exact observed output.

What collect_agent_data is supposed to do

For each agent it calls agent_portrayal(agent), gets back an AgentPortrayalStyle, and appends that style's values to arrays. x and y are optional: when the user doesn't set them, the backend derives the position from the agent. The derivation itself is correct. The problem is where the result is stored.

The bug

Both backends currently do this:

aps = portray_input
if aps.x is None and aps.y is None:
    aps.x, aps.y = self._get_agent_pos(agent, space)

arguments["loc"].append((aps.x, aps.y))

The derived position is written back onto the object that agent_portrayal returned. That turns shared configuration into per-agent working state. From the backend's point of view, the returned style should be read-only.

Why this breaks with a cached style

One style per agent type is a natural pattern:

PORTRAYALS = {
    "prey": AgentPortrayalStyle(size=5, color="green"),
    "predator": AgentPortrayalStyle(size=15, color="red"),
}

def agent_portrayal(agent):
    return PORTRAYALS[agent.type]

With agents at prey (0, 1), prey (2, 3), predator (4, 5):

  1. First prey: aps.x/aps.y are None, so the backend writes (0, 1) into the shared prey style and appends (0, 1).
  2. Second prey: the style now reads (0, 1), so the is None guard is false and position resolution is skipped entirely. The second prey is appended at (0, 1) too.
  3. Predator: uses its own style, still None, so it resolves correctly to (4, 5).

Observed output on both backends:

loc = [[0, 1], [0, 1], [4, 5]] prey style afterwards = (0, 1)

So the first prey "claims" the style, every later prey inherits its coordinates, and any agent collected after a resolution can also leak coordinates into later agents.

This persists across redraws too, because the cached object outlives the frame while collection re-runs each frame. Moving the agents to (5, 6) and (7, 8) and collecting again still returns [[0, 1], [0, 1]] — the coordinates resolved during the first frame are retained.

Expected behaviour

The style returned by agent_portrayal is configuration. Position resolution should happen per agent, into local variables, without touching the object. Explicit x/y should take precedence. I verified explicit coordinates are honoured and the style is left unchanged:

loc = [[10, 20], [10, 20]], style afterwards = (10, 20)

The fix

Resolve into locals and append those:

if aps.x is None and aps.y is None:
    agent_x, agent_y = self._get_agent_pos(agent, space)
else:
    agent_x, agent_y = aps.x, aps.y

arguments["loc"].append((agent_x, agent_y))

#4208 applies this in both MatplotlibBackend and AltairBackend, with parameterized regression tests (shared style across agents, repeated collection, explicit coordinates, and the style remaining unchanged).

Out of scope here: supplying only one of x/y (e.g. x=10, y=None) skips resolution because the guard uses and, yielding (10, None). That's a separate, pre-existing issue and not part of this fix.

I also found the same mutation in visualization/mpl_space_drawing.py, which appears to be used by the documented default space-component path. That may be a separate issue from the two backends changed in #4208.

priyanshux-dev avatar Nov 24 '26 07:11 priyanshux-dev