Skip to content

Keep recording after JSONDataRecorder.clear() - #4015

Merged
quaquel merged 1 commit into
mesa:mainfrom
AshNicolus:fix/json-recorder-clear
Nov 6, 2026
Merged

quaquel merged 1 commit into
mesa:mainfrom
AshNicolus:fix/json-recorder-clear

Conversation

@AshNicolus

@AshNicolus AshNicolus commented Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

JSONDataRecorder.clear() broke recording: the next model step raised KeyError. This makes it behave like the other three recorders.

Bug / Issue

Fixes #4014.

clear() with no arguments called self.data.clear(), which deleted the datasets themselves instead of emptying them. The next time the model advanced, the recorder tried to append to a dataset that no longer existed:

model.run_for(2)
recorder.clear()
model.run_for(1)  # KeyError: 'model_data'

The other recorders all keep their datasets and just empty them, so JSON was the odd one out:

After clear() DataRecorder / Parquet / SQL JSONDataRecorder before JSONDataRecorder now
reading a dataset empty DataFrame KeyError empty DataFrame
recording more steps keeps recording KeyError keeps recording
clear("unknown_name") KeyError silently ignored KeyError

Implementation

clear() now empties each dataset's list in place instead of removing the datasets, and raises KeyError for an unknown dataset name with the same message the other recorders use. No other changes.

Testing

  • test_json_recorder_clear asserted the KeyError after clear(), so it was testing the bug. It now checks that the dataset is empty.
  • Added test_json_recorder_keeps_recording_after_clear (the repro above) and test_json_recorder_clear_nonexistent_dataset.
  • All three fail on main and pass here. I also ran the same clear, read, record and unknown-name sequence against all four recorders, and they now behave identically.
  • Full suite passes with pytest tests/ -W error (1018 passed), and pre-commit is clean.

cc @quaquel @codebreaker32

@github-actions github-actions Bot added experimental Release notes label testing Release notes label labels Oct 28, 2026

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! Thanks

clear() with no arguments removed the per-dataset storage instead of
emptying it, so the next model step raised KeyError. Empty each dataset's
list instead, and raise KeyError for an unknown dataset name, which is
what DataRecorder, ParquetDataRecorder and SQLDataRecorder already do.

The existing test asserted the KeyError after clear(), so it now checks
for an empty dataset instead.

Fixes mesa#4014
@AshNicolus
AshNicolus force-pushed the fix/json-recorder-clear branch from 2ca4106 to 0075e97 Compare October 30, 2026 03:57

@lahari936 lahari936 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Peer review. The fix is right and the reasoning in the description holds up. I checked it rather than read it: I ran the same six operations against all four recorders, on main and on this branch, instead of taking the comparison table on trust.

On main:

check DataRecorder JSON Parquet SQL
read a dataset after clear() empty KeyError empty empty
keeps recording after clear() yes KeyError yes yes
clear('unknown') raises KeyError raises silently returns raises raises
summary() after clear() dict dict dict dict
clear() twice fine fine fine fine
clear() before any step fine fine fine fine

On this branch all four agree on all six rows. That is exactly the three rows your table claims and no others, so the scope is as advertised.

Two things I specifically looked for and did not find a problem with:

  • _store_dataset_snapshot pops the last entry when is_overwrite=True. After clear() the list is empty, but the guard is if is_overwrite and self.data[dataset_name]:, so it short-circuits rather than raising IndexError.
  • The KeyError message is character-for-character the one used at lines 160, 498 and 664, so a caller matching on it keeps working across recorders.

I left one question inline about files on disk. It is out of scope for this PR, I would not hold the merge for it.

Separately: tests/experimental/test_datarecorder.py 59 passed on this branch for me.

One ask, if you have time. I have #4026 open, a one-method fix in DiscreteSpace with a self-review posted, and it needs a GSoC peer review before a maintainer picks it up. No rush, and no obligation given you have four PRs of your own waiting.

"""Clear recorded data, keeping the datasets so recording can continue."""
if dataset_name is None:
self.data.clear()
for snapshots in self.data.values():

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Noting the thing that makes this correct rather than just symmetrical, since it is not obvious from the diff: JSONDataRecorder only touches disk when someone calls save_to_json() explicitly, unlike ParquetDataRecorder, which flushes buffers to .parquet as it goes, and SQLDataRecorder, which writes to the database continuously.

So emptying the in-memory lists really is the whole job here, where for Parquet it is not. Good call keeping the change to this.


def clear(self, dataset_name: str | None = None) -> None:
"""Clear data."""
"""Clear recorded data, keeping the datasets so recording can continue."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of scope for this PR, but worth a decision somewhere: ParquetDataRecorder.clear() unlinks model_data.parquet, and this leaves an already-written model_data.json alone.

save_to_json()   file rows = 2
clear()          file rows = 2, in-memory rows = 0

So after clear() the JSON file on disk still holds the old data while the recorder is empty, and the next save_to_json() overwrites it with nothing.

I think the current behaviour is defensible, maybe more defensible than Parquet's: save_to_json() is something the user asked for explicitly, and deleting an export because the recorder was cleared would be surprising. Not suggesting you change it here. Flagging it because "make JSON behave like the others" is the premise of the PR, and this is one way it still does not.

assert df.empty

# Clear All
# Clear All: the datasets stay registered and are empty, like the other recorders

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Worth calling out that the old test_json_recorder_clear asserted pytest.raises(KeyError) after clear(), so the suite was pinning the bug in place. That is the part of this PR a reader is most likely to skim past, and it is the reason the bug survived.

The replacement assertion is the right one.

@AshNicolus

Copy link
Copy Markdown
Contributor Author

Thanks @lahari936 for checking it against all four recorders. Good point on the .json file staying on disk after clear(). That feels like its own small decision (should clear() touch saved files at all?), so I kept it out of this PR.

@quaquel
quaquel merged commit d420962 into mesa:main Nov 6, 2026
16 checks passed
EwoutH pushed a commit that referenced this pull request Nov 22, 2026
clear() with no arguments removed the per-dataset storage instead of
emptying it, so the next model step raised KeyError. Empty each dataset's
list instead, and raise KeyError for an unknown dataset name, which is
what DataRecorder, ParquetDataRecorder and SQLDataRecorder already do.

The existing test asserted the KeyError after clear(), so it now checks
for an empty dataset instead.

Fixes #4014

(cherry picked from commit d420962)
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.

JSONDataRecorder.clear() breaks recording: the next step raises KeyError

4 participants