mesa icon indicating copy to clipboard operation
mesa copied to clipboard

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

Open lahari936 opened this issue 1 month ago • 2 comments

Describe the bug

_resolve_per_agent_values decides whether a value is one-per-agent or broadcast by checking against four hard-coded types:

https://github.com/mesa/mesa/blob/main/mesa/agentset.py#L98

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

Its own docstring describes 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, yet all four are broadcast as a single object.

Two consequences, both silent.

1. range(n) does not spread. Probably the most natural thing a user writes:

Agent.create_agents(model, n, wealth=range(n))

Every agent ends up holding the same range object as its wealth, with no error.

2. The length check added in #3824 does not apply. A wrong-length list raises; a wrong-length range does not:

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

So the guard protects the four listed types and nothing else.

To Reproduce

import array, collections
import pandas as pd
from mesa import Agent, Model

class A(Agent):
    def __init__(self, model, val=None):
        super().__init__(model)
        self.val = val

for label, value in [
    ("list", [0, 1, 2, 3]),
    ("range", range(4)),
    ("deque", collections.deque([0, 1, 2, 3])),
    ("array", array.array("i", [0, 1, 2, 3])),
    ("pd.Index", pd.Index([0, 1, 2, 3])),
]:
    m = Model(rng=1)
    A.create_agents(m, 4, val=value)
    vals = [a.val for a in m.agents]
    print(f"{label:9s}", "BROADCAST" if len({id(v) for v in vals}) == 1 else vals)

On current main:

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

Expected behavior

Any sized, ordered sequence of length n should be one value per agent, and a length mismatch should raise regardless of which sequence type carries it. Strings and bytes should keep being broadcast — element-wise is essentially never what a caller means — and so should unordered containers like set and dict, which have no defined order to hand out.

Additional context

The fix is to widen the check to collections.abc.Sequence plus the sized-but-not-Sequence pandas/numpy types, excluding str/bytes/bytearray.

This does change behaviour for anyone deliberately broadcasting a range or a deque as a single value, which is why I am opening this rather than going straight to a PR. I have the change and tests ready and am happy to open it if this reads as a bug rather than intended behaviour.

cc @AshNicolus, since this is the same area as #3824 and #3817.

lahari936 avatar Oct 19 '26 16:10 lahari936

Agree this is a bug rather than intended. The docstring already describes the sequence rule, and range(n) is the most natural thing to pass. Left a review on #3956 with one side effect to handle (AgentSet is a Sequence too).

AshNicolus avatar Oct 19 '26 19:10 AshNicolus

Credited the catch, showed the MRO chain I hadn’t checked, and put the Set-based alternative to them as an open question.

The line worth keeping from this round: “no test failed” and “no behaviour changed” are different claims, and I’d been treating them as the same one. That’s the actual lesson — my change was green when it was broken, because the repo has no model that stores a team on an agent.

On Tue, Oct 20, 2026 at 12:35 AM AshNicolus @.***> wrote:

AshNicolus left a comment (mesa/mesa#3955) https://github.com/mesa/mesa/issues/3955#issuecomment-6275025158

Agree this is a bug rather than intended. The docstring already describes the sequence rule, and range(n) is the most natural thing to pass. Left a review on #3956 https://github.com/mesa/mesa/pull/3956 with one side effect to handle (AgentSet is a Sequence too).

— Reply to this email directly, view it on GitHub https://github.com/mesa/mesa/issues/3955?email_source=notifications&email_token=BL3P7ACM4J5UOPOSVNTXAOT5UZQXNA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMMRXGUYDENJRGU4KM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KYZTPN52GK4S7MNWGSY3L#issuecomment-6275025158, or unsubscribe https://github.com/notifications/unsubscribe-auth/BL3P7AH7KCND7NKVQOF2ORL5UZQXNAVCNFSNUABEKJSXA33TNF2G64TZHMZDIMRUGU3TGNZ3JFZXG5LFHM2TSMRXGU4DQNBTGOQXMAQ . You are receiving this because you authored the thread.Message ID: @.***>

lahari936 avatar Oct 20 '26 12:10 lahari936