Skip to content

Fix DataCollector agenttype reporters to be consistently exact-type - #3797

Merged
quaquel merged 2 commits into
mesa:mainfrom
AshNicolus:fix-datacollector-agenttype-subclass
Aug 26, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
AshNicolus:fix-datacollector-agenttype-subclass

Conversation

@AshNicolus

Copy link
Copy Markdown
Contributor

Describe the bug

agenttype_reporters collect subclass agents inconsistently. Whether a superclass reporter includes its subclass agents depends on whether the superclass also has direct instances:

  • No direct instances of the type: subclasses are collected (via isinstance).
  • A direct instance of the type exists: only exact-type agents are collected, and subclasses are silently dropped (via agents_by_type[agent_type]).

Same reporter, contradictory results, failing silently (wrong/missing rows).

Expected behavior

A reporter keyed on a type should collect all agents that are instances of it, including subclasses, regardless of whether the type has direct instances. This is the behavior the existing test_agenttype_superclass_reporter already documents (a MockAgent/Agent reporter collects all 10 subclass agents) — that test only passes today because its model has no direct superclass instances.

To Reproduce

from mesa import Agent, Model
from mesa.datacollection import DataCollector

class Animal(Agent): pass
class Wolf(Animal): pass

model = Model(rng=1)
Wolf(model); Wolf(model)        # 2 subclass agents
Animal(model)                   # 1 direct instance of the reporter's type

dc = DataCollector(agenttype_reporters={Animal: {"uid": "unique_id"}})
dc.collect(model)
print(len(dc.get_agenttype_vars_dataframe(Animal)))   # 1  -> should be 3

Without the direct Animal(model) line it returns 2 (the Wolves). Adding it flips the result to 1, dropping the subclasses.

Root cause

_record_agenttype used an exact-type lookup (model.agents_by_type[agent_type]) when the type had instances, but an isinstance scan otherwise. The two branches disagree on subclasses.

Fix

Always collect subclass-inclusively by iterating the per-type buckets and keeping those whose type is a subclass of the requested type:

agents = [
    agent
    for a_type, bucket in model.agents_by_type.items()
    if issubclass(a_type, agent_type)
    for agent in bucket
]

This is consistent in all cases, matches the documented test_agenttype_superclass_reporter intent, and iterates registered types rather than every agent. The non-Agent-type ValueError is preserved.

Test

Added test_agenttype_reporter_includes_subclasses_with_direct_instances (fails assert 2 == 5 on the old code, passes on the fix). All 41 test_datacollector.py tests pass under -Werror; ruff clean.

Note

I'm aware DataCollector is slated for deprecation (#3547). Flagging this anyway because it's a silent data-correctness bug that contradicts existing tested behavior, not a cosmetic one — but happy to close if you'd rather leave the deprecated collector untouched.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.2% [-0.6%, +0.2%] 🔵 -0.2% [-0.3%, -0.0%]
BoltzmannWealth large 🔵 +0.2% [-0.4%, +0.8%] 🔵 -1.6% [-2.9%, -0.5%]
Schelling small 🔵 -0.1% [-0.6%, +0.4%] 🔵 -0.3% [-1.1%, +0.5%]
Schelling large 🔵 +3.0% [+1.8%, +4.2%] 🔴 +7.6% [+5.9%, +9.3%]
WolfSheep small 🔵 +0.4% [-0.2%, +1.0%] 🔵 +4.1% [+0.7%, +7.4%]
WolfSheep large 🟢 -4.5% [-5.7%, -3.0%] 🟢 -11.8% [-13.7%, -9.8%]
SugarscapeG1mt small 🔵 -0.3% [-1.1%, +0.5%] 🔵 -0.9% [-2.6%, +0.7%]
SugarscapeG1mt large 🔵 -0.9% [-3.9%, +2.1%] 🔵 -0.8% [-2.7%, +1.3%]
BoidFlockers small 🔵 +2.0% [+1.4%, +2.7%] 🔵 +0.2% [-0.1%, +0.6%]
BoidFlockers large 🔵 +0.8% [+0.2%, +1.6%] 🔵 -0.5% [-0.8%, -0.1%]

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

I looked over the old implementation where an exact-type lookup (model.agents_by_type[agent_type]) silently dropped subclass agents whenever a direct instance of the parent class existed. Your new implementation makes total sense to me, Moving from scanning all agents $O(N)$ to only checking registered agent types is also a great performance perk. Overall, LGTM!

I do have one quick thought on the architecture though:

Right now, DataCollector directly reaches into model.agents_by_type.items(). It might be cleaner if Model (or AgentSet) provided a public helper method for this lookup. That way, DataCollector doesn't need to depend on Model's internal dictionary layout, and simulation developers could easily reuse subclass-inclusive queries in their own model logic as well.

@shipitdev

shipitdev commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Right now, DataCollector directly reaches into model.agents_by_type.items(). It might be cleaner if Model (or AgentSet) provided a public helper method for this lookup. That way, DataCollector doesn't need to depend on Model's internal dictionary layout, and simulation developers could easily reuse subclass-inclusive queries in their own model logic as well.

for example something like

# Inside Model (or AgentSet)
def get_agents_by_type(self, agent_type: type[A], include_subclasses: bool = True) -> list[A]:
    if not include_subclasses:
        return list(self._agents_by_type.get(agent_type, []))
    return [
        agent
        for a_type, bucket in self._agents_by_type.items()
        if issubclass(a_type, agent_type)
        for agent in bucket
    ]

@quaquel quaquel added the bug Release notes label label Aug 18, 2026
@quaquel

quaquel commented Aug 18, 2026

Copy link
Copy Markdown
Member

I am not sure this is a bug or desired behavior that just needs to be documented better. From an analyst point of view, I would argue that it makes much more sense to collect on specific classes and not include subclasses as well.

@AshNicolus

Copy link
Copy Markdown
Contributor Author

Thanks both.

@quaquel fair point, and exact-type collection is a reasonable analyst view. One thing worth flagging for the decision: the codebase currently leans the other way. test_agenttype_superclass_reporter explicitly asserts that a reporter on MockAgent / Agent collects all 10 subclass agents and that the superclass and base dataframes are equal. So subclass-inclusive is what's tested/documented today, and it only passes because that test's model has no direct instances of the reported type.

Either semantics is defensible, but the current behavior is inconsistent regardless: the same reporter silently flips between including and excluding subclasses depending on whether a direct instance of the type happens to exist. So something should change either way, whether that is consistently subclass-inclusive (this PR) or consistently exact-type.

Happy to go whichever way you prefer:

  • subclass-inclusive: this PR already does it and matches the existing superclass test.
  • exact-type: I'll switch to exact-type collection, update test_agenttype_superclass_reporter, and document that agenttype reporters are exact-type only.

@shipitdev good point on not reaching into agents_by_type directly. A public Model.get_agents_by_type(agent_type, include_subclasses=...) would encapsulate that and, with the flag, could expose both behaviors so users choose per call, with DataCollector using whichever default is settled on. Happy to add it here or as a follow-up.

Just let me know the intended semantics and I'll align the PR.

@shipitdev

Copy link
Copy Markdown
Contributor

I agree with both of you here. The strongest point is the inconsistency, which is the real issue regardless of which direction the fix goes. The get_agents_by_type(agent_type, include_subclasses=True/False) helper would let users choose per call, covering both preferences cleanly and making it straightforward to document the intended behavior.

@AshNicolus

Copy link
Copy Markdown
Contributor Author

Sounds like we're converging. Concrete plan:

Add a public helper on Model so DataCollector doesn't depend on the internal
agents_by_type layout, and users get the same query in their own model code:

def get_agents_by_type(self, agent_type, *, include_subclasses=False):
    # exact-type by default, subclass-inclusive when asked

Then have the agenttype reporters call it. On the default: I'll go exact-type,
matching your analyst point, quaquel. That means updating
test_agenttype_superclass_reporter (which currently asserts subclass-inclusive)
and documenting that agenttype reporters are exact-type, with include_subclasses
available for anyone who wants subclasses.

That fixes the inconsistency (the real bug), and the flag covers both preferences
cleanly as @shipitdev suggested.

@shipitdev

Copy link
Copy Markdown
Contributor

sounds good, i'd say it'd be better if you covered the scope in two PRs - one for adding the helper get_agents_by_type on Model and another for DataCollector to use it. so its easier to roll back if anything comes up.

also Since DataCollector is slated for deprecation, the helper in the model is the piece with real long term value. The Datacollector update is more of a short-term fix. probably best to wait for quaquel before pushing ahead.

i'm also happy to co-author or help with a PR if you'd like

@AshNicolus

Copy link
Copy Markdown
Contributor Author

Works for me on splitting into two PRs: one adding Model.get_agents_by_type, and
a separate one switching the agenttype reporters to use it. Agreed the helper is
the durable part given the DataCollector deprecation.

I'll hold off on pushing either until you've weighed in, @quaquel: whether you're
happy adding get_agents_by_type as a public method on Model, and the default
(exact-type vs subclass-inclusive) plus what DataCollector should use. Once you
confirm the direction I'll put the helper PR up.

@quaquel

quaquel commented Aug 25, 2026

Copy link
Copy Markdown
Member

I am not sure. We have the agency_by_type attribute already, so adding a get method as well smells funny and seems not particularly pythonic. I am inclined towards documenting more clearly that subclasses are not included and shift the problem to the user if they want to handle this.

Also, any idea how this will work with the new dataset data collection stuff?

@shipitdev

Copy link
Copy Markdown
Contributor

I am not sure. We have the agency_by_type attribute already, so adding a get method as well smells funny and seems not particularly pythonic. I am inclined towards documenting more clearly that subclasses are not included and shift the problem to the user if they want to handle this.

Also, any idea how this will work with the new dataset data collection stuff?

oh didn't realize that, that's right. two getter for the same fetch isn't very pythonic. i should look into the new data collection stuff. lemme get back to in sometime

@AshNicolus

Copy link
Copy Markdown
Contributor Author

Good points, I'll drop the helper idea. With agents_by_type already there, a
parallel get_agents_by_type is redundant and not very pythonic, agreed.

On the new dataset collection: it sidesteps this by design. AgentDataSet is built
from an explicit AbstractAgentSet you pass in
(mesa/experimental/data_collection/dataset.py), not from a type key it has to
resolve, so subclass inclusion is entirely in the caller's hands and there's no
include/exclude decision hidden inside the collector. The new API already does
the "shift it to the user" thing you're leaning towards. (NumpyAgentDataSet is
the one type-keyed variant, but it installs observable properties on the class
rather than resolving membership at collect time, so it's a separate mechanism.)

Given that, I'm fine going exact-type for the legacy collector and documenting
it. One thing worth flagging before we close it out: the actual issue isn't
subclass-inclusive vs exact-type, it's that the reporter is currently
inconsistent, it silently switches between the two depending on whether a direct
instance of the reported type exists. Documenting alone leaves that silent flip
in place.

Minimal fix matching your preference: make the reporter consistently exact-type
(drop the isinstance branch, always use agents_by_type[type]), update
test_agenttype_superclass_reporter to the exact-type expectation, and add the
doc note that subclasses aren't included. No new API, and it removes the silent
inconsistency. Happy to do that, or if you'd rather not touch the deprecated
collector, I'll close this and open a docs-only PR instead. Your call.

@quaquel

quaquel commented Aug 26, 2026

Copy link
Copy Markdown
Member

I agree with your proposed minimum fix. So document properly and ensure behavior is also always exact-type.

@AshNicolus
AshNicolus force-pushed the fix-datacollector-agenttype-subclass branch from ff82049 to a4c8390 Compare August 26, 2026 10:13
@AshNicolus AshNicolus changed the title Fix DataCollector agent-type reporters to consistently include subclasses Fix DataCollector agenttype reporters to be consistently exact-type Aug 26, 2026
@AshNicolus

Copy link
Copy Markdown
Contributor Author

Updated to exact-type per your call, @quaquel. Changes:

  • _record_agenttype now collects only agents of exactly the reported type (model.agents_by_type.get(agent_type, [])), so subclasses are never included and the result no longer depends on whether a direct instance exists.
  • Documented on DataCollector that agenttype reporters are exact-type only.
  • Updated the two affected tests: the superclass reporter now asserts it collects nothing when only subclasses exist, and the direct-instance test asserts the exact count (2), not the subclass-inclusive count (5).

One extra thing I hit while doing this: with exact-type, a reporter on a type with no exact instances legitimately collects nothing, and get_agenttype_vars_dataframe returned a spurious 2-row all-NaN frame in that case (an empty generator passed to pd.DataFrame.from_records with an index gets misparsed as rows). Materializing the records to a list fixes it, so empty collections now return a proper empty frame. Included it here since exact-type makes empty results a normal outcome.

Rebased on main. Full suite passes locally (761), ruff clean.

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

Looks great, thanks for breaking down the AgentDataSet mechanics and keeping the legacy collector strictly exact-type.

@github-actions github-actions Bot added the testing Release notes label label Aug 26, 2026
@quaquel
quaquel merged commit 0683549 into mesa:main Aug 26, 2026
13 checks passed
quaquel pushed a commit that referenced this pull request Oct 28, 2026
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0.

Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (#3797).

Co-authored-by: Gracy769 <[email protected]>
EwoutH pushed a commit that referenced this pull request Oct 28, 2026
EwoutH pushed a commit that referenced this pull request Nov 22, 2026
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0.

Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (#3797).

Co-authored-by: Gracy769 <[email protected]>
(cherry picked from commit c45fbb7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants