Skip to content

fix: add_row() no longer mutates caller's input dictionary - #3690

Merged
quaquel merged 7 commits into
mesa:mainfrom
Krishsharma179:fix-addrow
Apr 6, 2026
Merged

quaquel merged 7 commits into
mesa:mainfrom
Krishsharma179:fix-addrow

Conversation

@Krishsharma179

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

add_row() was mutating the caller's input dictionary (row), causing a KeyError when the same row dict was reused across multiple calls.

Bug / Issue

Closes #3689
add_row() internally used row.pop(k) to build row_to_add, which destructively removes keys from the user's original dictionary. This means after the first call, the passed-in row becomes {}, and any subsequent use of that dict raises a KeyError

Implementation

# Before
row_to_add = {k: row.pop(k) for k in self.fields}

# After
row_to_add = {k: row[k] for k in self.fields}

Testing

test_table_dataset — added empty row check, add_row({}) raises ValueError
test_add_row_does_not_mutate_input — verifies the original dict is unchanged after calling add_row()
test_add_row_reuse_same_dict — verifies that reusing the same dict across 10 iterations raises no error.

Additional Notes

It was important to fix this because add_row() should never alter the data the user passes in modifying a caller's input is unexpected behaviour and can cause silent bugs that are hard to track down

@github-actions

github-actions Bot commented Apr 3, 2026

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -3.5% [-3.9%, -3.1%] 🟢 -4.1% [-4.5%, -3.6%]
BoltzmannWealth large 🔵 -0.1% [-0.3%, +0.1%] 🔵 -1.3% [-1.5%, -1.1%]
Schelling small 🔵 +1.1% [+0.7%, +1.5%] 🔵 +1.1% [+0.3%, +1.8%]
Schelling large 🔵 +0.4% [+0.0%, +0.9%] 🔵 +2.3% [+1.5%, +3.1%]
WolfSheep small 🔵 +0.9% [+0.5%, +1.2%] 🔵 +0.6% [-3.5%, +4.5%]
WolfSheep large 🔵 +0.7% [+0.1%, +1.2%] 🔵 +0.3% [-0.5%, +1.1%]
SugarscapeG1mt small 🔵 +0.1% [-0.1%, +0.3%] 🔵 +2.9% [+0.9%, +4.7%]
SugarscapeG1mt large 🔵 +0.2% [-0.2%, +0.5%] 🔵 +0.1% [-1.5%, +1.7%]
BoidFlockers small 🔵 +0.6% [+0.4%, +0.8%] 🔵 +1.4% [+1.1%, +1.7%]
BoidFlockers large 🔵 +0.4% [-0.0%, +0.8%] 🔵 +1.4% [+1.0%, +1.8%]

@Krishsharma179 Krishsharma179 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This is the self review of my PR and would appreciate the peer review from anyone of you guys @souro26 @codebreaker32

# If the row user passed includes the unexpected fields
unexpected = [k for k in row if k not in self.fields]
if unexpected:
raise ValueError(f"Row contains unexpected fields: {unexpected}")

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

the the user's input includes the unexpected fields it will raise the Valueerror

Comment on lines +262 to 264
# Adding the row to rows
row_to_add = {k: row[k] for k in self.fields}
self.rows.append(row_to_add)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This was the core problem before it was k : row.pop(k) now k:row[k] it was altering the users input by popping it so I changed it

Comment on lines +443 to +445
dataset = TableDataSet("new", fields=["a", "b", "c"])
with pytest.raises(ValueError, match="row is empty"):
dataset.add_row({})

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added a test that expects a [ValueError] when the row is empty. The existing tests already cover unexpected fields and missing required fields

Comment on lines +448 to +454
def test_add_row_does_not_mutate_input():
"""add_row should not mutate the user's input."""
dataset = TableDataSet("test", fields=["a", "b", "c"])
row = {"a": 1, "b": 2, "c": 3}
original = row.copy()
dataset.add_row(row)
assert row == original

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This checks if the row passed by the user gets affected or not after calling add_row

Comment on lines +457 to +469
def test_add_row_reuse_same_dict():
"""Tests for resuablity of add_row."""
dataset = TableDataSet("t", fields=["a", "b"])

row = {"a": 1, "b": 2}

for i in range(1, 11):
row["a"] = row["a"] * i
row["b"] = row["b"] * i
dataset.add_row(row) # should not raise any error

assert len(dataset.rows) == 10

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

This test checks the reusability of add_row() it verifies that reusing the same dict across 10 calls adds 10 rows and raises no error

@quaquel

quaquel commented Apr 3, 2026

Copy link
Copy Markdown
Member

I agree that this should be addressed. I am less convinced by how you address it. Why not simply copy the original row?

@Krishsharma179

Copy link
Copy Markdown
Contributor Author

I agree that this should be addressed. I am less convinced by how you address it. Why not simply copy the original row?

@quaquel I thought creating an unnecessary copy of the user's dict is wasteful instead, simply not modifying the user's dict in the first place is cleaner. Using row[k] just fetches the value without any extra memory allocation. That said, if you prefer row.copy() I am happy to change it!

@quaquel

quaquel commented Apr 3, 2026

Copy link
Copy Markdown
Member

Not sure, but the current implementation involves iterating 3 times over fields.

@Krishsharma179

Copy link
Copy Markdown
Contributor Author

Not sure, but the current implementation involves iterating 3 times over fields.

yes, it’s technically less efficient, but the real impact is minimal unless you’re adding huge numbers of rows with many fields
That said, I do have an optimized implementation for this as well what do you think about this ?

row_keys = set(row)
fields_set = set(fields)

missing = fields_set - row_keys
if missing:
    raise ValueError("row is missing fields")

unexpected = row_keys - fields_set
if unexpected:
    raise ValueError(f"Row contains unexpected fields: {sorted(unexpected)}")

row_to_add = {k: row[k] for k in fields}
self.rows.append(row_to_add)

@Krishsharma179

Copy link
Copy Markdown
Contributor Author

@quaquel please check the changes I did now it doesnt iterate over fields 3 times

@codebreaker32 codebreaker32 added the bug Release notes label label Apr 5, 2026
@quaquel
quaquel merged commit 598efe5 into mesa:main Apr 6, 2026
12 checks passed
EwoutH pushed a commit that referenced this pull request Oct 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

add_row() mutates the caller's input dictionary via row.pop(), causing KeyError on reuse

3 participants