Skip to content

Make create_agents raise on length-mismatched sequences - #3824

Merged
quaquel merged 1 commit into
mesa:mainfrom
AshNicolus:create-agents-raise-on-mismatch
Aug 30, 2026
Merged

quaquel merged 1 commit into
mesa:mainfrom
AshNicolus:create-agents-raise-on-mismatch

Conversation

@AshNicolus

Copy link
Copy Markdown
Contributor

Follow-up to #3817 (step 2 of the plan there). Switches create_agents onto the shared _resolve_per_agent_values helper with strict=True, so it now raises ValueError on a length-mismatched sequence argument instead of silently broadcasting the whole sequence to every agent. This aligns create_agents with AgentSet.set, which already raises.

Behavior change (documented in the docstring, release-note-worthy):

  • create_agents(model, n, seq) where len(seq) != n now raises ValueError instead of broadcasting seq to every agent.

As expected from the discussion on #3817, this breaks the VirusAntibody example in mesa-examples (it passes a length-3 vector to broadcast across 20 agents). Per the break-here-fix-there workflow, a matching mesa-examples PR follows to fix it (broadcasting the vector explicitly as [vec] * n, which works under both the old and new behavior).

Verified locally: core suite passes, ruff check and format clean. The build / examples check will be red until the mesa-examples fix lands.

@github-actions github-actions Bot added the testing Release notes label label Aug 30, 2026
@AshNicolus

Copy link
Copy Markdown
Contributor Author

For the mesa-examples side (step 3): the only thing that breaks is VirusAntibody, which passes a single length-3 dna list to VirusAgent.create_agents for initial_viruses (~20) agents, relying on the old broadcast behavior.

The fix is a one-liner in its model.py, broadcasting the shared value explicitly:

dna=[dna] * self.initial_viruses

That keeps the existing behavior (every virus starts with the same dna) and works under both the old and new create_agents, so it can merge independently. I'll put that up as a matching mesa-examples PR to turn the examples check green.

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔴 +8.3% [+7.5%, +9.2%] 🔵 -1.2% [-1.5%, -1.0%]
BoltzmannWealth large 🔴 +12.3% [+11.5%, +13.1%] 🔵 -4.6% [-8.1%, -1.4%]
Schelling small 🔴 +10.9% [+10.4%, +11.5%] 🔵 -0.1% [-1.1%, +0.9%]
Schelling large 🔴 +7.5% [+6.8%, +8.4%] 🔵 -0.1% [-1.7%, +1.6%]
WolfSheep small 🔴 +7.5% [+6.8%, +8.2%] 🔵 +3.4% [-0.6%, +7.6%]
WolfSheep large 🔴 +7.6% [+6.6%, +8.6%] 🔵 -2.5% [-3.2%, -1.7%]
SugarscapeG1mt small 🔴 +14.9% [+14.4%, +15.5%] 🔵 +0.5% [-0.9%, +1.9%]
SugarscapeG1mt large 🔴 +13.2% [+11.3%, +15.3%] 🔵 +0.8% [-0.6%, +2.2%]
BoidFlockers small 🔵 +2.0% [+1.4%, +2.6%] 🔵 +0.6% [+0.2%, +1.0%]
BoidFlockers large 🔵 +1.4% [+0.7%, +2.1%] 🔵 +0.4% [+0.2%, +0.7%]
MultiLevelAllianceModel small 🔵 -0.0% [-2.1%, +2.3%] 🔵 +0.9% [+0.1%, +2.2%]
MultiLevelAllianceModel large 🔵 -2.1% [-4.9%, +0.9%] 🔵 -1.8% [-3.4%, +0.1%]

@quaquel
quaquel merged commit da5f59a into mesa:main Aug 30, 2026
13 of 14 checks passed
@quaquel quaquel added the enhancement Release notes label label Aug 30, 2026
lahari936 added a commit to lahari936/mesa that referenced this pull request Nov 2, 2026
_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
quaquel added a commit that referenced this pull request Nov 7, 2026
…3956)

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

_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 #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 #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 #3955

* Keep broadcasting an AgentSet and a UserString

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.

* Broadcast every Set, rather than naming AbstractAgentSet

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

---------

Co-authored-by: Jan Kwakkel <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants