mesa icon indicating copy to clipboard operation
mesa copied to clipboard

`DataRecorder` Captures Stale Data Due to Redundant Observable Triggers in `_advance_time` of `model.py`

Open codebreaker32 opened this issue 9 months ago • 13 comments

Describe the bug

The DataRecorder captures incorrect intermediate states during event execution instead of the final state at each timestep. This occurs because model.time triggers the Observable signal before every event even when time hasn't changed.

When multiple events occur at the same simulation time, the DataRecorder captures data multiple times - once before each event executes. The final capture overwrites earlier ones, resulting in data that represents the state after some events but before others at that timestep.

Expected behavior

For the MRE below:

  • Time 0.0: wealth should be 0 (initial state)
  • Time 1.0: wealth should be 11 (after step: +1, then trade: +10)
  • Time 2.0: wealth should be 22 (after step: +1, then trade: +10)
  • Time 3.0: wealth should be 43 (after step: +1, then scheduled trade: +10, then recurring trade: +10)
  • Time 4.0: wealth should be 54 (after step: +1, then trade: +10)

Actual behavior

   unique_id  wealth  time
0          1       0   0.0
1          1       1   1.0
2          1      12   2.0
3          1      23   3.0
4          1      44   4.0

The DataRecorder shows values that suggest it's capturing after step() but before trade().

To Reproduce

from mesa import Model, Agent
from mesa.time import Schedule
from mesa.experimental.data_collection import DataRecorder
from mesa.datacollection import DataCollector

class MyAgent(Agent):
    def __init__(self, model):
        super().__init__(model)
        self.wealth = 0
    
    def step(self):
        self.wealth += 1 

class MyModel(Model):
    def __init__(self):
        super().__init__()
        MyAgent.create_agents(self,1)
        self.data_registry.track_agents(self.agents, "Wealth", "wealth")
        self.datacollector = DataCollector(
            agent_reporters={"Wealth": "wealth"},
        )
        self.recorder = DataRecorder(self)
        self.schedule_event(self.trade, at=3.0)
        self.schedule_recurring(
            self.trade,
            Schedule(interval=1)
        )
        self.datacollector.collect(self)
    
    def step(self):
        self.agents.shuffle_do("step")
        self.datacollector.collect(self)

    def trade(self):
        for agent in self.agents:
            agent.wealth += 10
        self.datacollector.collect(self)

model = MyModel()

model.run_until(4)

print(f"New DataRecorder: \n{model.recorder.get_table_dataframe('Wealth').to_string()}\n")
print(f"Old DataCollector: \n{model.datacollector.get_agent_vars_dataframe().to_string()}")

Note: Using either schedule_recurring() or schedule_event() will also reproduce the bug

MRE Output:

New DataRecorder: 
   unique_id  wealth  time
0          1       0   0.0
1          1       1   1.0
2          1      12   2.0
3          1      23   3.0
4          1      44   4.0

Old DataCollector: 
              Wealth
Step AgentID        
0.0  1             0
1.0  1            11
2.0  1            22
3.0  1            43
4.0  1            54

Root Cause Analysis

The bug is in model.py in the _advance_time() method (line 220):

https://github.com/mesa/mesa/blob/744df2a75b1df62c8a5dc8924012d35033155c53/mesa/model.py#L213-L224

Proposed Fix

    if event.time <= until: 
         if self.time != event.time
             self.time = event.time 
         event.execute()

codebreaker32 avatar Feb 14 '26 12:02 codebreaker32

What about instead handling this on the recorder side by comparing old and new?

The proposed fix will make it more difficult to handle signals from each individual event.

quaquel avatar Feb 14 '26 12:02 quaquel

What about instead handling this on the recorder side by comparing old and new?

Wouldn't it be equivalent to treating symptoms rather than bug itself. I mean, Observables will still be fired for every event and we will be adding an extra overhead to check for old and new time. Do you plan to use this Observables anywhere else also?

codebreaker32 avatar Feb 14 '26 12:02 codebreaker32

Honestly, I don't know. You can make a good case that sending a signal where old time is new time is a waste. At the same time, one might want to track all individual events, and one easy way to achieve that at the moment is via observing model.time.

Whether or not model.time being observable will be used elsewhere inside Mesa, I cannot say. Honestly, it also should not matter. What matters is that the behavior of model.time regarding emitting is well documented, so anyone can align with this.

quaquel avatar Feb 14 '26 14:02 quaquel

I should brainstorm over it a little bit more to find for better alternatives. Meanwhile we can keep this issue open to attract better suggestions.

codebreaker32 avatar Feb 14 '26 14:02 codebreaker32

The main tradeoff is behavioral, some observers may currently rely on “one time signal per event” even when time does not advance. If we keep that behavior, recorder-side filtering is a workaround; if we want cleaner semantics, suppressing redundant time assignments is the better fix and should be documented.

falloficaruss avatar Feb 15 '26 03:02 falloficaruss

If we keep that behavior, recorder-side filtering is a workaround

Could you elaborate?

some observers may currently rely on “one time signal per event”

I couldn't follow. Imk, DataRecorder is the only one observing the model.time for now and it wants "one signal per time change". But as @quaquel noted:

Whether or not model.time being observable will be used elsewhere inside Mesa, I cannot say. Honestly, it also should not matter. What matters is that the behavior of model.time regarding emitting is well documented, so anyone can align with this

That's why we are not implementing the proposed fix

codebreaker32 avatar Feb 15 '26 05:02 codebreaker32

Could you elaborate?

If time emits “changed” even when it didn’t change, every future observer has to rediscover and filter that quirk. That’s why I called it a workaround: it solves one consumer, not the source contract.

I couldn't follow. Imk, DataRecorder is the only one observing the model.time for now and it wants "one signal per time change". But as @quaquel noted:

Whether or not model.time being observable will be used elsewhere inside Mesa, I cannot say. Honestly, it also should not matter. What matters is that the behavior of model.time regarding emitting is well documented, so anyone can align with this

My concern is consistency: DataRecorder currently assumes model.time signals correspond to actual time boundaries, but _advance_time can emit time.changed multiple times with old == new for same-time events

  1. If we keep current model.time behavior (including old == new emits), then DataRecorder should be updated to handle that contract safely.
  2. If time.changed is intended to mean an actual time advance, then suppress redundant emits in _advance_time.

I’m not attached to one implementation path; I just want the signal semantics and recorder behavior to match.

falloficaruss avatar Feb 15 '26 06:02 falloficaruss

I think that to avoid unnecessary complexity and extra work for the system, it would be better to modify the model.time signal to only trigger when the time actually changes, rather than filtering it in the recorder. This ensures clearer behavior and prevents redundant checks down the line.

souro26 avatar Feb 15 '26 07:02 souro26

I have been thinking about this a bit more. I am inclined to fix this at the level of the Observable. In #3261, when aggregating observable signals, nothing is emitted if old==new. So, should an Observable not have the same behavior? That is, do the following in Observable.__set__:

        if instance._has_subscribers(self.public_name, ObservableSignals.CHANGED):
            old_value = getattr(instance, self.private_name, None)
            if old_value != value:
                send_notify = True

quaquel avatar Feb 15 '26 08:02 quaquel

I have been thinking about this a bit more. I am inclined to fix this at the level of the Observable. In #3261, when aggregating observable signals, nothing is emitted if old==new. So, should an Observable not have the same behavior? That is, do the following in Observable.__set__:

    if instance._has_subscribers(self.public_name, ObservableSignals.CHANGED):
        old_value = getattr(instance, self.private_name, None)
        if old_value != value:
            send_notify = True

It'd solve the stale data problem but we will miss the last run

I did some further testing and I noticed this MRE successfully captured the end state with current observable

from mesa import Model, Agent
from mesa.time import Schedule
from mesa.experimental.data_collection import DataRecorder
from mesa.datacollection import DataCollector

class MyAgent(Agent):
    def __init__(self, model):
        super().__init__(model)
        self.wealth = 0
    
    def step(self):
        self.wealth += 1 

class MyModel(Model):
    def __init__(self):
        super().__init__()
        MyAgent.create_agents(self,1)
        self.recorder = DataRecorder(self)
        self.data_registry.track_agents(self.agents, "Wealth", "wealth").record(self.recorder)
        self.datacollector = DataCollector(
            agent_reporters={"Wealth": "wealth"},
        )
        
        # self.schedule_event(self.trade, at=3.0)
        # self.schedule_recurring(
        #     self.trade,
        #     Schedule(interval=1)
        # )
        self.datacollector.collect(self)
    
    def step(self):
        self.agents.shuffle_do("step")
        self.datacollector.collect(self)

    def trade(self):
        for agent in self.agents:
            agent.wealth += 10
        self.datacollector.collect(self)

model = MyModel()

model.run_until(4)

print(f"New DataRecorder: \n{model.recorder.get_table_dataframe('Wealth').to_string()}\n")
print(f"Old DataCollector: \n{model.datacollector.get_agent_vars_dataframe().to_string()}")

Because https://github.com/mesa/mesa/blob/5e189694aa89b95824f6ffbc892e4edfd488e019/mesa/model.py#L226 fired the last signal for a single step events which helped recorder to capture last step but once we'll change the observable this will no longer be fired so we'll always me missing the last step

codebreaker32 avatar Feb 15 '26 13:02 codebreaker32

Adding

with contextlib.suppress(AttributeError):
        self.recorder.finalise()

at the end of run_for() and run_until() seems to solve the problem as a temporary workaround for them but not for step()

codebreaker32 avatar Feb 15 '26 13:02 codebreaker32

I agree we still have to solve the run ended problem. I am still inclined to solve that via a new signal rather than keeping it in run_for and run_until. For example, one might run for several steps, have some user-side code, and then continue the run. But making sure obervables only emit on an actual change is proper behavior regardless of the knock-on consequences, for e.g., the data recorder.

quaquel avatar Feb 15 '26 13:02 quaquel

I agree we still have to solve the run ended problem. I am still inclined to solve that via a new signal rather than keeping it in run_for and run_until. For example, one might run for several steps, have some user-side code, and then continue the run. But making sure obervables only emit on an actual change is proper behavior regardless of the knock-on consequences, for e.g., the data recorder.

I completely agree and I know this is already planned and discussed but I was looking for a temporary workaround for current release We also shouldn't encourage the use of finalise()

codebreaker32 avatar Feb 15 '26 13:02 codebreaker32