Skip to content

Spread any sized sequence across agents, not four hard-coded types - #3956

Merged
quaquel merged 4 commits into
mesa:mainfrom
lahari936:fix-per-agent-sequence-types
Nov 7, 2026
Merged

quaquel merged 4 commits into
mesa:mainfrom
lahari936:fix-per-agent-sequence-types

Conversation

@lahari936

Copy link
Copy Markdown
Contributor

Note

Use this template for bug fixes only. For enhancements/new features, use the feature template and get maintainer approval in an issue/discussion before opening a PR.

Pre-PR Checklist

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

Summary

_resolve_per_agent_values chose between one-value-per-agent and broadcast with a hard-coded type check, while its own docstring described a different rule. range, collections.deque and array.array are all collections.abc.Sequence, and pandas.Index is sized and ordered, yet all four were broadcast as a single shared object.

Bug / Issue

Fixes #3955.

Two consequences, both silent.

create_agents(model, n, wealth=range(n)) gave every agent the same range object rather than its own number — probably the most natural thing a user writes.

And the length validation added in #3824 only ever covered the four listed types, so a wrong-length list raised while a wrong-length range did not:

Agent.create_agents(model, 4, val=[0, 1, 2])   # ValueError, as intended
Agent.create_agents(model, 4, val=range(3))    # silently broadcast

On main:

list(4)         [0, 1, 2, 3]
range(4)        BROADCAST
deque(4)        BROADCAST
array.array(4)  BROADCAST
pd.Index(4)     BROADCAST

Implementation

-    if isinstance(value, (list, tuple, np.ndarray, pd.Series)):
+    if isinstance(
+        value, (Sequence, np.ndarray, pd.Series, pd.Index)
+    ) and not isinstance(value, (str, bytes, bytearray)):

Sequence was already imported in the module. np.ndarray, pd.Series and pd.Index stay listed explicitly because none of them register as collections.abc.Sequence despite being sized and ordered.

str, bytes and bytearray keep being broadcast — handing a string out one character per agent is never what a caller means. set and dict keep being broadcast too, having no defined order to hand elements out in. The docstring now states both rules and the reasoning, rather than describing behaviour the code did not implement.

After:

list, tuple, range, deque, array, ndarray, Series, Index   -> spread
str, bytes, set, dict, int                                  -> broadcast, one shared object
range(3) / deque(3) / array(3) / Index(3) for 4 agents      -> ValueError

Testing

Three parametrised tests in tests/test_agent.py, 17 cases: every sequence type spreads, every sequence type raises on a length mismatch, and scalars and unordered containers broadcast as a single shared object.

Run against main with only the test file applied, they give 8 failed, 9 passed — failing exactly on range, deque, array and Index in both groups, passing on the four types that already worked.

pytest tests/test_agent.py → 32 passed. pytest --cov=mesa tests/ → 890 passed, 86% coverage, with one pre-existing unrelated failure (test_suppressed_wake_is_logged_at_debug, see #3935, fixed by #3938) and one environment error (test_schelling_model[chromium], playwright browser not installed). ruff check and ruff format --check clean.

Additional Notes

This is a behaviour change for anyone deliberately broadcasting a range or a deque as a single value. I opened #3955 first rather than going straight here, so that is on the record and easy to push back on.

Two things I deliberately left alone, happy to take either as follow-ups:

  • Generators and other non-sized iterables are still broadcast, which shares one consumable object across every agent. Worth a warning, but it is a different shape of problem since there is no length to validate.
  • pd.DataFrame is unchanged; create_agents already has its own handling for it.

cc @AshNicolus, same area as #3824 and #3817.

Copilot AI balanced review requested due to automatic review settings October 19, 2026 16:28
@github-actions github-actions Bot added the testing Release notes label label Oct 19, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@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.5% [-0.7%, -0.4%]
BoltzmannWealth large 🔵 -1.7% [-2.1%, -1.2%] 🔵 -0.9% [-1.7%, -0.1%]
Schelling small 🔵 -1.1% [-1.6%, -0.6%] 🔵 -0.4% [-1.1%, +0.3%]
Schelling large 🔵 -1.3% [-2.4%, -0.3%] 🔵 -2.4% [-5.3%, +0.2%]
WolfSheep small 🔵 -3.3% [-4.2%, -2.4%] 🔵 +0.2% [-4.1%, +4.6%]
WolfSheep large 🔵 -0.4% [-1.5%, +0.7%] 🔵 +0.8% [-1.7%, +4.1%]
SugarscapeG1mt small 🔵 +1.3% [+0.6%, +1.9%] 🔵 +0.4% [-1.1%, +2.1%]
SugarscapeG1mt large 🔵 +1.4% [-0.0%, +3.0%] 🔵 -1.7% [-3.8%, +0.2%]
BoidFlockers small 🔵 -0.0% [-0.3%, +0.3%] 🔵 +0.2% [-0.1%, +0.5%]
BoidFlockers large 🔵 +0.0% [-0.4%, +0.4%] 🔵 +0.2% [-0.1%, +0.6%]
MultiLevelAllianceModel small 🔵 -2.5% [-3.6%, -1.4%] 🔵 +1.5% [+0.8%, +2.1%]
MultiLevelAllianceModel large 🔵 -0.3% [-1.1%, +0.5%] 🔵 +1.3% [+0.0%, +2.5%]

@AshNicolus

Copy link
Copy Markdown
Contributor

Thanks for the cc. Agreed this reads as a bug, range(n) is exactly what people will write, and the length check should apply to every sequence type. I checked the branch out and the new tests behave as described.

One side effect though: AgentSet is itself a Sequence, so it now gets spread too. Passing a group of agents as a value used to share it, and now it either spreads one agent per agent or raises:

team = AgentSet(three_agents, random=model.random)

A.create_agents(model, 3, val=team)   # main: every agent gets team      PR: one agent each
A.create_agents(model, 5, val=team)   # main: every agent gets team      PR: ValueError
agents.set("val", team)               # on 4 agents, main: shared        PR: ValueError

Storing a team or a set of neighbours on each agent seems like a normal thing to do, and nothing in the repo does it, so the suite doesn't catch it. Excluding AbstractAgentSet the same way str is excluded would keep that working, plus a test for it. collections.UserString slips through the str check as well (it now spreads one character per agent), if you want to exclude that too.

@lahari936 lahari936 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, per #3536, now that @AshNicolus's finding is addressed.

Four notes below: one on the judgement call at the centre of the change, one on the exclusion list, one on the test I think is weakest, and one on the migration guide. I have tried to flag what I am least sure about rather than only what I am happy with.

Comment thread mesa/agentset.py Outdated
if isinstance(value, (list, tuple, np.ndarray, pd.Series)):
if isinstance(
value, (Sequence, np.ndarray, pd.Series, pd.Index)
) and not isinstance(value, (str, bytes, bytearray, UserString, AbstractAgentSet)):

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 exclusion list is the part of the change I would push on hardest if I were reviewing it.

str, bytes and bytearray are easy -- nobody means "one character per agent". The other two are judgement calls:

  • UserString is excluded because it is a string in every sense that matters to a caller, and is only missed by isinstance(value, str) due to being a wrapper rather than a subclass.
  • AbstractAgentSet is excluded because an AgentSet reaches Sequence through MutableSet -> Set, so it satisfies the predicate by inheritance while meaning the opposite of per-agent values. @AshNicolus caught this; I had not looked at the MRO.

What I am less sure of is whether excluding by type is the right shape at all, versus excluding anything that is a Set (unordered by nature, which is also why plain set is broadcast). AbstractAgentSet is a MutableSet, so a Set check would cover it and would read as a rule rather than a list of special cases. I kept the explicit exclusion because it is narrower and I did not want to change behaviour for other Set subclasses in the same PR, but I would switch if you prefer the general form.

Comment thread tests/test_agent.py
pytest.param(lambda n: pd.Index(range(n)), id="index"),
],
)
def test_create_agents_spreads_any_sized_sequence(make_sequence):

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.

These two parametrisations are the core of the change: every sized ordered sequence spreads, and every one of them raises on a length mismatch.

Run against main with only this file applied, they give 8 failed / 9 passed -- failing exactly on range, deque, array and pd.Index in both groups, passing on the four types that already worked. That split is the point: the new behaviour is pinned and the existing behaviour is protected, so a future narrowing of the predicate fails loudly.

Comment thread tests/test_agent.py
assert len({id(v) for v in values}) == 1


def test_create_agents_broadcasts_an_agentset():

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 test I would most like a second opinion on, because it exists only because a human spotted the case.

The isinstance(team, collections.abc.Sequence) assertion is deliberate. Without it, a future reader sees a test asserting that an AgentSet is broadcast and has no idea why that is worth asserting. With it, the failure message points straight at the reason.

Worth being blunt about the gap it covers: nothing in the repo stores a group on an agent, so the full suite passed on the broken version. A green run told me nothing here. That is the main thing I took away from this review round -- "no test failed" and "no behaviour changed" are different claims, and I had been treating them as the same one.

Comment thread docs/migration_guide.md

- Ref: [PR #3328](https://github.com/mesa/mesa/pull/3328)

### Any sized sequence is spread across agents

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 on reflection rather than in the first pass, since this is a behaviour change and the Mesa 4.0.0 section is where the others are recorded.

Precedent is mixed: #3824 changed behaviour (length validation) without an entry here. I went with documenting it because the failure mode is silent in the other direction -- someone relying on a broadcast range gets different values per agent, with no error -- and the workaround (wealth=[my_range] * n) is not obvious.

Note the prose here is unlinted by both of us: Vale is in the ci: skip: list, and it will not build locally on my machine, so a style pass from someone who can run it would be welcome.

@lahari936

Copy link
Copy Markdown
Contributor Author

Thanks @AshNicolus, that's a real regression and I'd missed it entirely. Fixed.

You're right about the inheritance chain, which I hadn't looked at:

AgentSet -> AbstractAgentSet -> ABC -> MutableSet -> Set -> Sequence

So AgentSet satisfies isinstance(value, Sequence) and my widened check started spreading it. Reproduced exactly as you described:

create_agents(model, 3, val=team)   spread one agent each   (main: shared)
create_agents(model, 5, val=team)   ValueError              (main: shared)

collections.UserString too — it isn't a str, so it went straight past that guard and spread one character per agent.

Both are now excluded alongside str/bytes/bytearray:

) and not isinstance(value, (str, bytes, bytearray, UserString, AbstractAgentSet)):

and the docstring says why, since "an AgentSet is a Sequence but is not per-agent values" is exactly the kind of thing the next person will otherwise rediscover the hard way.

Three tests added, all failing without the exclusion and passing with it:

  • create_agents broadcasts an AgentSet at both matching and mismatched length, with an isinstance(team, Sequence) assertion in the test so the reason is visible at the failure site
  • AgentSet.set() broadcasts one too, since that path goes through the same function
  • UserString joins the broadcast-scalars parametrisation

Your point that nothing in the repo stores a team on an agent is the part that stuck with me — the suite was never going to catch this, and I had convinced myself the change was safe because it was green. Worth remembering that "no test failed" and "no behaviour changed" are different claims.

I've also added a migration guide entry under Mesa 4.0.0, covering the spread change, the length check now applying to every sequence type, and what still broadcasts, with a note on how to restore the old behaviour for a range (wealth=[my_range] * n).

Pushed as af43ad8. pytest --cov=mesa tests/ → 893 passed, 86% coverage, with the same two non-failures as before: test_suppressed_wake_is_logged_at_debug (the #3935 logging leak, fixed by #3938 once it lands) and test_schelling_model[chromium] (no playwright browser locally). tests/test_agent.py → 35 passed.

Self-review is posted too, including a note on the exclusion list that I would value your opinion on: AbstractAgentSet is a MutableSet, so excluding anything that is a Set would cover it as a rule rather than a named special case, and would also read as the reason plain set is broadcast. I kept the explicit exclusion to avoid changing behaviour for other Set subclasses in the same PR, but the general form may be the better shape.

Also glad the resume() thing was useful on #3922.

@AshNicolus

Copy link
Copy Markdown
Contributor

Checked the update, AgentSets and UserStrings are broadcast again and the tests pass.

On the question, I'd go with the general Set rule. It matches what the docstring already says (sets are shared because they have no order), and it also covers anything else built on AbstractAgentSet without another special case.

One small correction for the test comment though: Set isn't a Sequence, and neither is AbstractAgentSet. AgentSet gets it from its own bases (class AgentSet(AbstractAgentSet, Sequence)), and model.agents isn't a Sequence at all. So the only things that are both are AgentSet and third-party ordered sets. That's another reason the Set check reads cleanly, as long as broadcasting an ordered set is OK with everyone.

@lahari936

Copy link
Copy Markdown
Contributor Author

You're right, and thanks for correcting the reasoning rather than just the code — I had the wrong model of why it happened, and I'd written that wrong model into the docstring, the commit message and my own self-review.

I read the MRO linearization as an inheritance chain:

AgentSet -> AbstractAgentSet -> ABC -> MutableSet -> Set -> Sequence

Sequence is last in that list because of C3 ordering, not because Set derives from it. Checking properly:

AgentSet.__bases__                      (AbstractAgentSet, Sequence, Generic)
AbstractAgentSet is Sequence subclass   False
Set is Sequence subclass                False
model.agents (_HardKeyAgentSet)         Set: True, Sequence: False

So it is exactly as you said: AgentSet lists Sequence among its own bases, and model.agents was never affected at all. Excluding AbstractAgentSet reached the right outcome by naming the wrong cause.

Switched to the general rule in 2916ef3:

) and not isinstance(value, (str, bytes, bytearray, UserString, AbstractSet)):

It covers AgentSet, anything else built on AbstractAgentSet, and third-party ordered sets, and it unifies with plain set and frozenset — which, as you note, were only being broadcast by failing the sequence check rather than by any rule of their own. The docstring now leads with the rule ("a set is a group to share rather than a row of per-agent values") and mentions AgentSet as a consequence of it rather than as a special case.

On your caveat about ordered sets: I agree it should be an explicit decision, so it is now a test rather than an implication.

class _OrderedSet(collections.abc.Set, collections.abc.Sequence):
    """A container that is both a Set and a Sequence, as AgentSet is."""

It asserts both isinstance checks before exercising the behaviour, so if someone later decides ordered sets should spread, the test that has to change says plainly what it is protecting. All three group tests fail without the Set exclusion.

Migration guide now says "every collections.abc.Set" rather than listing set and AgentSet separately.

pytest --cov=mesa tests/ → 895 passed, 86% coverage, with the same #3935 logging failure outstanding until #3938 lands. tests/test_agent.py + tests/test_agentset.py → 87 passed. ruff clean.

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

Checked the latest commit, works as expected. LGTM 👍

_resolve_per_agent_values decided between one-value-per-agent and broadcast
with a hard-coded isinstance check:

    if isinstance(value, (list, tuple, np.ndarray, pd.Series)):

Its own docstring described a different rule, that a scalar, a string or a
non-sequence is broadcast. range, collections.deque and array.array are all
collections.abc.Sequence, and pandas.Index is sized and ordered, so all four
were broadcast as a single shared object instead.

Two silent consequences. create_agents(model, n, wealth=range(n)) gave every
agent the same range object rather than its own number. And the length check
added in mesa#3824 only ever applied to the four listed types, so a wrong-length
list raised while a wrong-length range did not:

    create_agents(model, 4, val=[0, 1, 2])   # ValueError
    create_agents(model, 4, val=range(3))    # silently broadcast

Widening the check to collections.abc.Sequence plus the sized-but-not-Sequence
numpy and pandas types makes the behaviour match the documented contract, and
extends the length guard to every sequence type rather than four of them.

str, bytes and bytearray stay broadcast, since handing a string out one
character per agent is never what a caller means. set and dict stay broadcast
too, having no defined order to hand elements out in. The docstring now says
both, and why.

This changes behaviour for anyone deliberately broadcasting a range or a deque
as a single value. See mesa#3955 for that discussion.

Adds parametrised tests over every sequence type: each spreads, each raises on
a length mismatch, and scalars and unordered containers broadcast as one shared
object. On main the new tests give 8 failed / 9 passed, failing exactly on
range, deque, array and Index.

Fixes mesa#3955
AgentSet reaches Sequence through its base classes:

    AgentSet -> AbstractAgentSet -> ABC -> MutableSet -> Set -> Sequence

so widening the per-agent check to collections.abc.Sequence started spreading
it. Passing a group to every agent, a team or a set of neighbours, either
handed out one member each or raised on a length mismatch:

    create_agents(model, 3, val=team)   spread one agent each   (was shared)
    create_agents(model, 5, val=team)   ValueError              (was shared)

collections.UserString is not a str, so it went past that guard too and spread
one character per agent.

Both are now excluded alongside str, bytes and bytearray, and the docstring
records why: an AgentSet is a Sequence by inheritance, but passing one means
"give every agent this group" rather than one member each.

Nothing in the repo stores a group on an agent, so the suite could not have
caught this. Thanks to @AshNicolus for spotting it in review.

Adds three tests, all failing without the exclusion: create_agents broadcasts
an AgentSet at matching and mismatched length, AgentSet.set broadcasts one too
since it shares the same code path, and UserString joins the broadcast-scalar
cases.

Also documents the whole change in the migration guide under Mesa 4.0.0: what
now spreads, that the length check applies to every sequence type, what still
broadcasts, and how to keep a range broadcast if you were relying on it.
@AshNicolus pointed out that my previous explanation was wrong. I had read
the MRO linearization as an inheritance chain:

    AgentSet -> AbstractAgentSet -> ABC -> MutableSet -> Set -> Sequence

Set does not derive from Sequence, and neither does AbstractAgentSet.
AgentSet lists Sequence among its own bases:

    AgentSet.__bases__          (AbstractAgentSet, Sequence, Generic)
    AbstractAgentSet            Set subclass, not a Sequence subclass
    _HardKeyAgentSet            Set subclass, not a Sequence subclass

So model.agents was never affected, and excluding AbstractAgentSet named the
wrong reason for the right outcome.

Excluding collections.abc.Set instead states the actual rule: a set is a
group to share, not a row of per-agent values. It covers AgentSet, anything
else built on AbstractAgentSet, and third-party ordered sets, and it unifies
with plain set and frozenset, which were already broadcast by falling the
sequence check rather than by any rule of their own.

The tradeoff is that an ordered set is broadcast rather than spread. That is
deliberate, and a test now pins it with a container that is both a Set and a
Sequence, so the decision is visible rather than implied by AgentSet alone.

Test wording corrected in the same way, and the migration guide now says
"every collections.abc.Set" rather than listing set and AgentSet separately.
@lahari936
lahari936 force-pushed the fix-per-agent-sequence-types branch from 2916ef3 to 58d118f Compare November 2, 2026 11:42
@quaquel
quaquel merged commit 40e7060 into mesa:main Nov 7, 2026
16 of 17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

create_agents broadcasts range, deque, array and pd.Index instead of spreading them, and skips the length check

4 participants