Repository navigation
Make create_agents raise on length-mismatched sequences - #3824
Merged
Merged
Conversation
Contributor
Author
|
For the mesa-examples side (step 3): the only thing that breaks is VirusAntibody, which passes a single length-3 The fix is a one-liner in its dna=[dna] * self.initial_virusesThat keeps the existing behavior (every virus starts with the same dna) and works under both the old and new |
|
Performance benchmarks:
|
quaquel
approved these changes
Aug 30, 2026
1 task done
4 tasks done
This was referenced Oct 12, 2026
This was referenced Oct 19, 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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Follow-up to #3817 (step 2 of the plan there). Switches
create_agentsonto the shared_resolve_per_agent_valueshelper withstrict=True, so it now raisesValueErroron a length-mismatched sequence argument instead of silently broadcasting the whole sequence to every agent. This alignscreate_agentswithAgentSet.set, which already raises.Behavior change (documented in the docstring, release-note-worthy):
create_agents(model, n, seq)wherelen(seq) != nnow raisesValueErrorinstead of broadcastingseqto 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 / examplescheck will be red until the mesa-examples fix lands.