Repository navigation
Spread any sized sequence across agents, not four hard-coded types - #3956
Conversation
|
Performance benchmarks:
|
|
Thanks for the cc. Agreed this reads as a bug, One side effect though: 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: ValueErrorStoring 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 |
lahari936
left a comment
There was a problem hiding this comment.
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.
| 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)): |
There was a problem hiding this comment.
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:
UserStringis excluded because it is a string in every sense that matters to a caller, and is only missed byisinstance(value, str)due to being a wrapper rather than a subclass.AbstractAgentSetis excluded because anAgentSetreachesSequencethroughMutableSet->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.
| pytest.param(lambda n: pd.Index(range(n)), id="index"), | ||
| ], | ||
| ) | ||
| def test_create_agents_spreads_any_sized_sequence(make_sequence): |
There was a problem hiding this comment.
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.
| assert len({id(v) for v in values}) == 1 | ||
|
|
||
|
|
||
| def test_create_agents_broadcasts_an_agentset(): |
There was a problem hiding this comment.
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.
|
|
||
| - Ref: [PR #3328](https://github.com/mesa/mesa/pull/3328) | ||
|
|
||
| ### Any sized sequence is spread across agents |
There was a problem hiding this comment.
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.
|
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: So
Both are now excluded alongside ) 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:
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 Pushed as af43ad8. Self-review is posted too, including a note on the exclusion list that I would value your opinion on: Also glad the |
|
Checked the update, AgentSets and UserStrings are broadcast again and the tests pass. On the question, I'd go with the general One small correction for the test comment though: |
|
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:
So it is exactly as you said: Switched to the general rule in 2916ef3: ) and not isinstance(value, (str, bytes, bytearray, UserString, AbstractSet)):It covers 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 Migration guide now says "every
|
AshNicolus
left a comment
There was a problem hiding this comment.
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.
2916ef3 to
58d118f
Compare
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
Summary
_resolve_per_agent_valueschose between one-value-per-agent and broadcast with a hard-coded type check, while its own docstring described a different rule.range,collections.dequeandarray.arrayare allcollections.abc.Sequence, andpandas.Indexis 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 samerangeobject 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
listraised while a wrong-lengthrangedid not:On
main:Implementation
Sequencewas already imported in the module.np.ndarray,pd.Seriesandpd.Indexstay listed explicitly because none of them register ascollections.abc.Sequencedespite being sized and ordered.str,bytesandbytearraykeep being broadcast — handing a string out one character per agent is never what a caller means.setanddictkeep 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:
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
mainwith only the test file applied, they give 8 failed, 9 passed — failing exactly onrange,deque,arrayandIndexin 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 checkandruff format --checkclean.Additional Notes
This is a behaviour change for anyone deliberately broadcasting a
rangeor adequeas 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:
pd.DataFrameis unchanged;create_agentsalready has its own handling for it.cc @AshNicolus, same area as #3824 and #3817.