mesa icon indicating copy to clipboard operation
mesa copied to clipboard

NumpyAgentDataSet accessors read the last-created model's data

Open 0xnithinmys opened this issue 1 month ago • 0 comments

track_agents_numpy() silently mixes data between models. NumpyAgentDataSet installs its getter/setter on the agent class, and they close over one dataset's array. Each new dataset for the same class reinstalls them, so the agents of every live model read and write the array of the dataset created last. No error is raised.

Expected behavior

Each model's agents use only their own model's dataset, and a deepcopy is independent of the original.

To Reproduce

import copy
from mesa import Agent, Model

class Cow(Agent):
    def __init__(self, model, energy):
        super().__init__(model)
        self.energy = energy

def make_model(seed, energy):
    model = Model(rng=seed)
    model.data_registry.track_agents_numpy(Cow, "cows", "energy")
    for _ in range(3):
        Cow(model, energy)
    return model

m1 = make_model(1, 10.0)
m2 = make_model(2, 99.0)
print("m1:", [float(a.energy) for a in m1.agents])  # expected [10.0, 10.0, 10.0]

clone = copy.deepcopy(m2)
for a in clone.agents:
    a.energy = -1.0
print("m2:", [float(a.energy) for a in m2.agents])  # expected [99.0, 99.0, 99.0]

Output on current main (0a17aa6a):

m1: [99.0, 99.0, 99.0]
m2: [-1.0, -1.0, -1.0]

Additional context

  • Root cause: _make_getter_setter captures data = self._agent_data (mesa/experimental/data_collection/dataset.py:354-366), and _install_properties sets it on the shared agent_type (:368-371).
  • Same cause, other symptoms: run_scenarios with a ThreadPoolExecutor returned different results from a sequential run for 6–8 of 8 replications, and remove_all_agents() on one model deletes the accessors for every other live model (close(), :508-518).

Proposed fix

Store the owning dataset on each agent and let the accessors resolve storage through it, so they no longer depend on which model was created last:

# add_agent()
agent.__dict__[self._dataset_in_table] = self   # e.g. "_datatable_cows"

# _make_getter_setter()
def getter(agent):
    state = agent.__dict__
    return state[dataset_attr]._agent_data[state[index_attr], j]

In addition: drop the reinstall in _expand_storage, have close() only remove the accessors once no open dataset uses them, and add a __setstate__ that reinstalls them so pickled models restore in a fresh process.

I've prototyped this. The repro above gives the expected output, the full test suite passes (excluding tests/visualization), and the overhead is about 20 ns per attribute access. I'm happy to open a PR with a regression test.

0xnithinmys avatar Oct 06 '26 18:10 0xnithinmys