Skip to content

Fix DataCollector model_reporters list-shape validation to avoid IndexError - #3514

Merged
quaquel merged 8 commits into
mesa:mainfrom
falloficaruss:datacollector-model-reporter-list-validation
Mar 18, 2026
Merged

quaquel merged 8 commits into
mesa:mainfrom
falloficaruss:datacollector-model-reporter-list-validation

Conversation

@falloficaruss

@falloficaruss falloficaruss commented Mar 11, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes a DataCollector validation gap where malformed list-style model_reporters (for example [func]) bypass validation and later crash in collect() with IndexError: list index out of range.
Impact: users get an internal low-level exception instead of a clear actionable validation error.

Bug / Issue

Closes #3513

Context:

  • model_reporters supports list format: [function, [params...]].
  • Current validation only checks that the list is non-empty and the first item is callable.
  • A malformed reporter like [func] passes validation, then fails at collection time when code accesses reporter[1].

Expected:

  • Malformed list-style reporters should raise a clear ValueError describing expected format.

Actual (before fix):

  • IndexError: list index out of range raised from collect().

Implementation

Updated mesa/datacollection.py in two places:

  1. _validate_model_reporter(...)
  • Strengthened list reporter validation to require:
    • exactly 2 elements,
    • callable first element,
    • second element is a params container (list or tuple).
  1. collect(...)
    • Added defensive validation in the list branch before calling reporter[0](*reporter[1]).
    • Raises the same clear ValueError message if format is invalid.

This ensures malformed list reporters fail with a user-facing validation error instead of an internal IndexError.

Testing

Added regression tests in tests/test_datacollector.py:

  • test_function_error_missing_params_list
    • verifies [lambda m: ...] raises ValueError with informative message.
  • test_function_error_invalid_params_type
    • verifies [lambda m, x: ..., 1] raises ValueError with informative message.

Additional Notes

  • This PR intentionally focuses on malformed list-shape handling and clearer exceptions.

GSoC contributor checklist

Context & motivation

I was exploring DataCollector and testing edge cases around reporter validation when I noticed an inconsistency in how malformed model_reporters lists were handled. A clearly invalid format like ["not_callable", [1, 2]] already raised a clean ValueError, but another malformed case like [func] slipped through validation and later failed with a low-level IndexError during collect(). I wanted to fix this because it felt like a small but important usability bug: users should get a clear validation error that points to what they configured wrong, rather than an internal indexing failure.

What I learned

Working on this helped me understand the different reporter shapes supported by DataCollector and how validation and collection interact. What was more subtle than I expected was that fixing the obvious bug was only part of the work; I also had to think about exception consistency, test coverage, and whether the validation change might unintentionally narrow accepted input types. That made the review process more interesting, because it was not just about making the error go away, but about making the behavior clearer and safer without changing more than necessary.

Learning repo

🔗 My learning repo: https://github.com/falloficarus22/GSoC-learning-space.git
🔗 Relevant model(s): This is a bug fix in DataCollector validation and does not require a new feature example model.

Readiness checks

  • This PR addresses an agreed-upon problem (linked issue or discussion with maintainer approval), or is a small/trivial fix
  • I have read the contributing guide and deprecation policy
  • I have performed a self-review: I reviewed my own PR as if I were a reviewer and left comments on anything that needs explanation
  • Another GSoC contributor has reviewed this PR: @souro26
  • Tests pass locally (pytest --cov=mesa tests/)
  • Code is formatted (ruff check . --fix)
  • If applicable: documentation, examples, and/or migration guide are updated

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +1.8% [+1.2%, +2.3%] 🔵 -0.3% [-0.5%, -0.2%]
BoltzmannWealth large 🔵 -0.1% [-0.9%, +0.7%] 🔵 +2.7% [-1.2%, +6.7%]
Schelling small 🔵 +0.7% [-0.1%, +1.4%] 🔵 +0.2% [-0.2%, +0.5%]
Schelling large 🔵 +1.3% [+0.8%, +1.7%] 🔴 +11.3% [+7.8%, +15.6%]
WolfSheep small 🔵 -1.5% [-2.0%, -1.1%] 🔵 -0.6% [-0.8%, -0.4%]
WolfSheep large 🔵 +0.5% [-0.8%, +2.1%] 🔵 +3.6% [+2.2%, +5.2%]
SugarscapeG1mt small 🔵 -0.5% [-1.1%, +0.1%] 🔵 -1.6% [-2.0%, -1.3%]
SugarscapeG1mt large 🔵 -3.5% [-5.3%, -1.5%] 🔵 -1.5% [-2.3%, -0.8%]
BoidFlockers small 🟢 -4.2% [-4.8%, -3.6%] 🔵 -2.7% [-2.9%, -2.6%]
BoidFlockers large 🔵 -3.4% [-3.8%, -2.7%] 🔵 -2.0% [-2.3%, -1.8%]

Comment thread mesa/datacollection.py Outdated
# Check if function with arguments
elif isinstance(reporter, list):
if (
len(reporter) != 2

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.

there is already validation for the reporter list format in _validate_model_reporter earlier in collect, so this additional check might be redundant.

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.

Validation only runs when self._validated is False (first collect cycle). After that, users can still mutate model_reporters (or load altered state), and without the guard you can still get a raw IndexError. The extra check preserves a clear ValueError contract instead of leaking internal indexing errors.

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.

My bad, i overlooked that. Thanks for this.

@falloficaruss falloficaruss 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.

Self Review

  • Fixes a real usability bug - users now get clear ValueError instead of cryptic IndexError
  • Dual validation (in _validate_model_reporter and collect) handles edge case where reporters are mutated after first validation
  • Tests verify both malformed cases mentioned in the PR
  • Error messages are clear and actionable

@falloficaruss

Copy link
Copy Markdown
Contributor Author

@EwoutH ready for review

@quaquel quaquel added bug Release notes label backport-candidate PRs we might want to backport to an earlier branch labels Mar 18, 2026

@quaquel quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks fine to me.

@quaquel
quaquel merged commit 806ed3b into mesa:main Mar 18, 2026
11 checks passed
@EwoutH

EwoutH commented Mar 18, 2026

Copy link
Copy Markdown
Member

Isn’t this just user error? Is the complexity it adds proportional to the improvement in user experience?

@falloficaruss

Copy link
Copy Markdown
Contributor Author

Isn’t this just user error? Is the complexity it adds proportional to the improvement in user experience?

I don’t think this is only user error in the usual sense. The reporter list format is part of the documented API, and malformed input was producing a low-level internal IndexError rather than a clear validation error. My goal was to make that failure mode consistent and actionable. In this case the added complexity seemed small relative to the benefit of replacing an internal crash with a predictable API-level error.

PietroMondini pushed a commit to PietroMondini/mesa that referenced this pull request Mar 19, 2026
codebreaker32 pushed a commit to codebreaker32/mesa that referenced this pull request Apr 1, 2026
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

backport-candidate PRs we might want to backport to an earlier branch bug Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

DataCollector accepts malformed list-style model_reporters ([func]) and crashes with IndexError during collect()

5 participants