Repository navigation
fix(data_collection): collect() overwrites a same-time snapshot instead of duplicating it - #4148
RudraDudhat2509 wants to merge 4 commits into
Conversation
…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.
|
Performance benchmarks:
|
|
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 Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
|
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. |
|
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) 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. 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 |
|
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 |
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
@quaquel would appreciate guidance on how u wanna handle this, apologies for the repeated follow ups |
* 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]>
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.
|
CI should be green after latest commit, resolving the merge conflict shortly |
…te-same-time # Conflicts: # mesa/experimental/data_collection/basedatarecorder.py
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_overwriteentirely, 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:
test_data_recorder_window_eviction_customto advancemodel.timebetween eachcollect()call, so it tests actual eviction across distinct times instead of accidentally re-testing the duplicate-write bug under a misleading name.test_base_recorder_manual_collect_same_time_overwrites: threecollect()calls at the same time produce exactly one stored block and one dataframe row for that time.test_base_recorder_manual_collect_distinct_times_append: confirms the fix doesn't regress the normal case — threecollect()calls at three different times still produce three blocks.Verification:
Both repro scripts from #4147, re-run against the fix:
Also ran the wider
tests/experimental/suite (516/514/513 passed depending on the run, one environment-dependent failure intest_locations.pyfrom a NumPy ABI mismatch between the installed NumPy and a compiled extension — present identically on unmodifiedmain, unrelated to this change and todata_collectionentirely).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_collectionstarts at-1, andmodel.timestarts at0.0, so0.0 == -1isFalse); and mixing a realmodel.step()(auto-collect) with a manualcollect()right after at the same resulting time still produces exactly one row per distinct timestamp, no new inconsistency.ruff checkandruff format --diffboth 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 theis_overwriteparameter identically, soJSONDataRecorder/ParquetDataRecorder/SQLDataRecordershould behave the same way — I didn't write a dedicated repro script for each of those three specifically, only the existing test suite'stest_run_ended[...]-style parametrized tests, which cover all four recorders and still pass.