Skip to content

fix(data_collection): collect() overwrites a same-time snapshot instead of duplicating it - #4148

Open
RudraDudhat2509 wants to merge 4 commits into
mesa:mainfrom
RudraDudhat2509:fix/collect-overwrite-same-time
Open

RudraDudhat2509 wants to merge 4 commits into
mesa:mainfrom
RudraDudhat2509:fix/collect-overwrite-same-time

Conversation

@RudraDudhat2509

Copy link
Copy Markdown
Contributor

Fixes #4147.

Diff:

     @abstractmethod
     def _store_dataset_snapshot(
-        self, dataset_name: str, time: int | float, data: Any
+        self,
+        dataset_name: str,
+        time: int | float,
+        data: Any,
+        is_overwrite: bool = False,
     ) -> None:
-        """Store a single snapshot of data."""
+        """Store a single snapshot of data.
+
+        Args:
+            dataset_name: Name of the dataset being stored.
+            time: Simulation time of this snapshot.
+            data: The data to store.
+            is_overwrite: If True, replace the most recently stored
+                snapshot for this dataset instead of appending a new one.
+                Every concrete recorder gets this from both collection
+                paths (the observable-driven one and manual ``collect()``)
+                whenever two snapshots land on the same ``time``.
+        """

     def collect(self) -> None:
         """Manually trigger collection (for manual mode or testing).
@@
             if not config.enabled:
                 continue

+            # A second collect() at the same time (e.g. two manual calls
+            # between real steps) replaces the prior snapshot for that time
+            # instead of appending a duplicate, matching _on_time_change.
+            is_overwrite = current_time == config._last_collection
+
             dataset = self.registry.datasets[name]
             data_snapshot = dataset.data
-            self._store_dataset_snapshot(name, current_time, data_snapshot)
+            self._store_dataset_snapshot(
+                name, current_time, data_snapshot, is_overwrite
+            )
+            config._last_collection = current_time
             if (current_time - config.start_time) % config.interval == 0:
                 config.update_next_collection(current_time)

The abstract method's declared signature was also missing is_overwrite entirely, even though every one of the four concrete recorders (DataRecorder, JSONDataRecorder, ParquetDataRecorder, SQLDataRecorder) already implements it — fixed that too so the base class actually documents the real contract.

Test changes:

  • Fixed test_data_recorder_window_eviction_custom to advance model.time between each collect() call, so it tests actual eviction across distinct times instead of accidentally re-testing the duplicate-write bug under a misleading name.
  • Added test_base_recorder_manual_collect_same_time_overwrites: three collect() calls at the same time produce exactly one stored block and one dataframe row for that time.
  • Added test_base_recorder_manual_collect_distinct_times_append: confirms the fix doesn't regress the normal case — three collect() calls at three different times still produce three blocks.

Verification:

Both repro scripts from #4147, re-run against the fix:

 unique_id  value  time
         1     10   0.0

rows for time=0.0: 1
 unique_id  value  time
         1     10   2.0
         1     10   3.0

times retained: [2.0, 3.0]
$ python -m pytest tests/experimental/test_datarecorder.py -v
...
======================== 88 passed in 4.09s ========================

Also ran the wider tests/experimental/ suite (516/514/513 passed depending on the run, one environment-dependent failure in test_locations.py from a NumPy ABI mismatch between the installed NumPy and a compiled extension — present identically on unmodified main, unrelated to this change and to data_collection entirely).

Also checked two things that could make the fix worse than the bug, not just better: the very first collect() call ever on a fresh config can't be mistaken for an overwrite (config._last_collection starts at -1, and model.time starts at 0.0, so 0.0 == -1 is False); and mixing a real model.step() (auto-collect) with a manual collect() right after at the same resulting time still produces exactly one row per distinct timestamp, no new inconsistency.

ruff check and ruff format --diff both clean on the two touched files.

What I didn't verify: this only covers DataRecorder (the in-memory backend) in the repro scripts above, though the fix lives in the shared base class and all four backends already implement the is_overwrite parameter identically, so JSONDataRecorder/ParquetDataRecorder/SQLDataRecorder should behave the same way — I didn't write a dedicated repro script for each of those three specifically, only the existing test suite's test_run_ended[...]-style parametrized tests, which cover all four recorders and still pass.

…ad of duplicating it

collect() never computed is_overwrite or updated _last_collection, so a
second manual call at an unchanged model.time appended a duplicate row
instead of replacing the prior one, unlike _on_time_change which
already does this (introduced by mesa#3424 to prevent duplicate rows on
pause/resume). With a bounded window_size, the duplicate could evict a
real, distinct snapshot.

Also declares is_overwrite on the abstract _store_dataset_snapshot
signature, since every concrete recorder already implements it, and
fixes test_data_recorder_window_eviction_custom, which was unknowingly
exercising this same bug under a "window eviction" label since it
never advanced model.time between its three collect() calls.
@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Nov 19, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -2.0% [-2.4%, -1.7%] 🔵 -0.7% [-0.9%, -0.5%]
BoltzmannWealth large 🔵 +0.1% [-0.6%, +0.8%] 🔵 -0.6% [-1.1%, -0.1%]
Schelling small 🔵 -0.6% [-1.1%, -0.1%] 🔵 -1.0% [-1.9%, -0.2%]
Schelling large 🔵 -3.1% [-3.5%, -2.7%] 🔵 -1.4% [-2.5%, -0.3%]
WolfSheep small 🔵 -1.7% [-2.0%, -1.5%] 🔵 -1.3% [-2.9%, +0.2%]
WolfSheep large 🔵 -1.9% [-2.3%, -1.6%] 🔵 -1.7% [-2.3%, -1.1%]
SugarscapeG1mt small 🔵 -1.1% [-1.6%, -0.6%] 🔵 -0.8% [-2.7%, +1.2%]
SugarscapeG1mt large 🔵 +1.0% [+0.2%, +1.8%] 🔵 -0.7% [-2.3%, +0.7%]
BoidFlockers small 🔵 -1.5% [-1.8%, -1.2%] 🔵 +0.2% [-0.2%, +0.6%]
BoidFlockers large 🔵 -2.1% [-2.5%, -1.8%] 🔵 -0.2% [-0.4%, +0.1%]
MultiLevelAllianceModel small 🔵 -1.9% [-2.5%, -1.4%] 🔵 -1.4% [-1.7%, -1.1%]
MultiLevelAllianceModel large 🔵 -2.3% [-3.1%, -1.7%] 🔵 -2.4% [-2.8%, -2.0%]

@mesa-triage-bot

Copy link
Copy Markdown

Thanks @RudraDudhat2509 for the window-loss reproducer; I reproduced it and verified that the proposed collect() change retains times 2 and 3.

@quaquel, #3969 also touches this collection path, and you asked there what is_overwrite should replace and requested the missing base-method parameter. Should this manual-collection fix proceed separately, or should the contract be settled together? I recommend keeping the fixes separate while coordinating the contract: this restores the existing automatic-collection behaviour, whereas #3969 changes which table rows a snapshot contains.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

@quaquel

quaquel commented Nov 21, 2026

Copy link
Copy Markdown
Member

I just closed #3969 because it was stale. @RudraDudhat2509, can you check that PR and the associated issue and see how it exactly intersects with this one? Let's first agree before making any further code changes.

@RudraDudhat2509

RudraDudhat2509 commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor Author

hey @quaquel , i went over #3969 (a call by reference bug that records the same pointer at different timestamps)

heres what this pr fixes:

-> adds the missing forth parameter from the abstarct method _store_dataset_snapshot (is_overwrite)
-> adds a one line check to see if current_time == config._last_collection in collect()

the overlap is basically how to handle the overwrite, ig you stated that you wanted to erase all old data however that may breaks things downstream, window_size sliding eviction breaks, since a single overwrite collapses the rolling buffer to 1 and one overwrite event under full-wipe collapses a 5-step run from 6 rows to 1, (reproduced on main)

also the intended semantics of the 4 recorder classes (i may have interpreted them wrong) are to remove the last block not the entire old data and thats what is implemented in this pr.

# DataRecorder
if is_overwrite and storage.blocks:
    _, old_data = storage.blocks.pop()        # removes ONE box: the last one

# JSONDataRecorder
if is_overwrite and self.data[dataset_name]:
    self.data[dataset_name].pop()              # removes ONE entry: the last one

# SQLDataRecorder
if is_overwrite and self.metadata[dataset_name]["table_created"]:
    self.conn.execute('DELETE FROM "..." WHERE time = ?', (time,))   # only rows matching THIS time

# ParquetDataRecorder
while buffer and buffer[-1]["time"] == time:
    buffer.pop()                                # only entries matching THIS time

do lmk if this reads correctly, also cis are failing after you merged main into this branch do you need me to fix the same or wait for your triage? thx

@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

also Jan, the ci failure is because of one test test_json_recorder_numpy_dataset_ids_stay_aligned_after_removal in test_datarecorder.py

that test calls collect() twice at the same model.time (no step in between) to grab a before/after snapshot around an agent removal, then does before, after = recorder.data["numpy_data"] expecting 2 entries. my fix computes is_overwrite = current_time == config._last_collection, so the second collect() at the same unchanged time now reads as an overwrite and JSONDataRecorder pops the first entry, leaving 1 instead of 2, hence the unpack error.

wanted to flag before touching anything, lmk how you want to handle it

quaquel added a commit to quaquel/mesa that referenced this pull request Nov 22, 2026
The time-change, run-end and manual collect() paths each decided
whether to overwrite, took a snapshot and stored it. The rule that
append-only datasets are never overwritten lived only in the first two;
collect() did not need it because it never overwrites.

Move these steps into _record_dataset(), used by all three paths. This
changes no behavior today, but keeps the rule in one place: once
collect() overwrites at an already recorded time (as mesa#4148 proposes),
a table's recorded rows would otherwise be deleted at that time while
the snapshot only holds the new rows.

Adds a test that an overwrite never deletes the recorded rows of an
append-only dataset, across all four recorders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW
@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

also Jan, the ci failure is because of one test test_json_recorder_numpy_dataset_ids_stay_aligned_after_removal in test_datarecorder.py

that test calls collect() twice at the same model.time (no step in between) to grab a before/after snapshot around an agent removal, then does before, after = recorder.data["numpy_data"] expecting 2 entries. my fix computes is_overwrite = current_time == config._last_collection, so the second collect() at the same unchanged time now reads as an overwrite and JSONDataRecorder pops the first entry, leaving 1 instead of 2, hence the unpack error.

wanted to flag before touching anything, lmk how you want to handle it

@quaquel would appreciate guidance on how u wanna handle this, apologies for the repeated follow ups

quaquel added a commit that referenced this pull request Nov 25, 2026
* Fix TableDataSet rows being duplicated by data recorders

TableDataSet.data returns its live, append-only rows list. The recorders
stored it by reference on every collection, so all stored blocks aliased
the same list, and even with a copy each collection re-recorded the full
table (1+2+...+n rows with wrong timestamps).

BaseDataRecorder now takes a snapshot via _take_snapshot(): for a
TableDataSet it returns a new list holding only the rows added since the
previous collection (re-including the replaced block's rows on an
overwrite). Row dicts are shared with the dataset rather than copied,
since neither the dataset nor the recorders mutate them; the
TableDataSet.data docstring documents this. Other datasets are unchanged.

Adds a regression test across DataRecorder, JSONDataRecorder,
ParquetDataRecorder and SQLDataRecorder.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Address review feedback on TableDataSet recording

- Add TableDataSet.get_rows_since(index), so BaseDataRecorder only
  tracks the cursor and no longer imports TableDataSet. The recorder
  looks the method up on the dataset's type, so only dataset classes
  that define it qualify.
- Document that window_size keeps the rows of the last N collections
  for a TableDataSet.
- Add a test that adds rows on only some steps and runs twice.
- Drop the dropna in the table test now that #4168 is merged.
- Import TableDataSet at the top of the test module.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Never overwrite rows of append-only datasets

Collecting again at an already recorded time (for example, the end of a
run followed by collect()) made the next recording of that time an
overwrite. The backends delete what is stored for that time on an
overwrite, but the cursor only re-supplied rows from the latest
collection, so rows were lost (e.g., run_for(2), collect(), run_for(1)
dropped the t=2 row in DataRecorder, ParquetDataRecorder and
SQLDataRecorder).

Rows of an append-only dataset never change once added, so an overwrite
has nothing to correct. The recorder now skips overwrites for such
datasets and only records rows it has not recorded yet, tracked with a
single forward-only counter per dataset. _is_append_only() holds the
class-level get_rows_since check.

Adds a regression test for the case above across all four recorders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

* Record datasets through a single method on all collection paths

The time-change, run-end and manual collect() paths each decided
whether to overwrite, took a snapshot and stored it. The rule that
append-only datasets are never overwritten lived only in the first two;
collect() did not need it because it never overwrites.

Move these steps into _record_dataset(), used by all three paths. This
changes no behavior today, but keeps the rule in one place: once
collect() overwrites at an already recorded time (as #4148 proposes),
a table's recorded rows would otherwise be deleted at that time while
the snapshot only holds the new rows.

Adds a test that an overwrite never deletes the recorded rows of an
append-only dataset, across all four recorders.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01RbrUQUQAArrpH7rYQFt6KW

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
@quaquel

quaquel commented Nov 26, 2026

Copy link
Copy Markdown
Member

my fix computes is_overwrite = current_time == config._last_collection, so the second collect() at the same unchanged time now reads as an overwrite and JSONDataRecorder pops the first entry, leaving 1 instead of 2, hence the unpack error.

This makes sense to me.

Two manual collect() calls at the same unchanged model.time now overwrite
rather than duplicate, so the test's second collect() was replacing the
first snapshot instead of adding a second one.
@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

CI should be green after latest commit, resolving the merge conflict shortly

…te-same-time

# Conflicts:
#	mesa/experimental/data_collection/basedatarecorder.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

experimental Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

2 participants