Skip to content

BaseDataRecorder.collect() duplicates a snapshot instead of overwriting when called twice at the same time #4147

Done

Description

@RudraDudhat2509

Environment:

Python 3.13.9, Windows
mesa main @ 668c892

What happened

BaseDataRecorder._on_time_change (the observable-driven collection path) already treats a second collection at the same model.time as an overwrite, not a new row:

is_overwrite = current_time == config._last_collection
...
self._store_dataset_snapshot(name, current_time, data_snapshot, is_overwrite)

collect() — the public method the class's own docstring tells you to call "for manual mode or testing" — never computes is_overwrite and never updates config._last_collection, so it always calls _store_dataset_snapshot as a plain append:

self._store_dataset_snapshot(name, current_time, data_snapshot)

Every concrete recorder's _store_dataset_snapshot defaults is_overwrite to False, so two manual collect() calls at the same time produce two rows for an event that only happened once.

Repro

from mesa import Agent, Model
from mesa.experimental.data_collection import DataRecorder, DatasetConfig


class Person(Agent):
    def __init__(self, model, value):
        super().__init__(model)
        self.value = value


model = Model()
Person(model, 10)
model.data_registry.track_agents(model.agents, "people", fields="value")

recorder = DataRecorder(model, config={"people": DatasetConfig(window_size=3)})

# Manual mode, exactly as the collect() docstring recommends.
recorder.collect()
recorder.collect()
recorder.collect()

df = recorder.get_table_dataframe("people")
print(df.to_string(index=False))
print()
print(f"rows for time={model.time}: {(df['time'] == model.time).sum()}")
 unique_id  value  time
         1     10   0.0
         1     10   0.0
         1     10   0.0

rows for time=0.0: 3

Same agent, same timestep, three rows.

It also eats real history out of the window

recorder = DataRecorder(model, config={"people": DatasetConfig(window_size=2)})

model.step()  # t=1
recorder.collect()
model.step()  # t=2
recorder.collect()
model.step()  # t=3
recorder.collect()
# Second manual collect at the SAME t=3 - exactly the "manual mode or
# testing" usage the collect() docstring recommends.
recorder.collect()

df = recorder.get_table_dataframe("people")
print(df.to_string(index=False))
print("times retained:", sorted(df["time"].unique().tolist()))
 unique_id  value  time
         1     10   3.0
         1     10   3.0

times retained: [3.0]

With window_size=2 after three distinct real steps, the window should hold [2.0, 3.0]. Instead the duplicate at t=3 consumes both slots in the deque, and t=2's real, distinct snapshot is gone.

Why this is a bug, not a design choice

mesa already picked an answer to "what happens when two collections land on the same time." _last_collection/is_overwrite were introduced by #3424, specifically "to prevent duplicate data rows when the model is paused, modified, and resumed at the same timestep." That mechanism was built generically into the storage layer (all four concrete recorders implement is_overwrite), then wired into _on_time_change and _on_run_ended but never into collect(). This reads as the one call site that got missed when #3424 landed, not a deliberate "manual mode manages its own dedup" contract — nothing in collect()'s docstring says that, and no test asserts it on purpose.

This also matches how adjacent tools treat a repeated write at the same key: pandas.DataFrame.loc[existing_index] = ... replaces the row in place rather than duplicating it, and InfluxDB's documented behavior is that a point with the same measurement, tag set, and timestamp merges into the existing point rather than creating a second one (docs). mesa's own _on_time_change already follows that same convention; collect() is the one place that doesn't.

There's also a test in the repo that currently encodes this exact confusion: test_data_recorder_window_eviction_custom calls collect() three times in a row with model.time never advanced, and asserts len(storage.blocks) == 2, labeled as "window eviction." It isn't testing eviction across real time steps — it's unknowingly testing (and locking in) this duplicate-write bug, since all three calls land on the identical timestamp.

One open PR, #3969, touches the same three methods (collect(), _on_time_change, _store_dataset_snapshot) for an unrelated bug (TableDataSet rows duplicating via a shared list reference). It doesn't fix this issue — collect() still calls _store_dataset_snapshot with no is_overwrite in that PR's diff — but flagging it here since a fix for this will likely need a rebase against it if #3969 merges first.

Activity

  1. added
    bug
    docs
    on Nov 19, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugdocs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions