Skip to content

Fix VirusAntibodyModel giving every virus agent the same shared dna list - #496

Merged
quaquel merged 2 commits into
mesa:mainfrom
RudraDudhat2509:fix/virus-antibody-shared-dna-mutation
Oct 28, 2026
Merged

quaquel merged 2 commits into
mesa:mainfrom
RudraDudhat2509:fix/virus-antibody-shared-dna-mutation

Conversation

@RudraDudhat2509

Copy link
Copy Markdown
Contributor

Found this while checking why mesa/mesa#3853's "examples" CI check was failing. It's unrelated to that PR, reproduces the same way on plain mesa main with no changes there.

dna = [self.random.randint(0, 9) for _ in range(3)] is one shared starting DNA meant to seed all initial_viruses virus agents, passed straight through as dna=dna to create_agents. create_agents now validates that a sequence kwarg's length matches the agent count (#3824 on mesa/mesa), so a 3-item list against 20 agents raises ValueError: sequence of length 3 does not match the number of agents (20) and the model never even starts.

Just broadcasting [dna] * initial_viruses would fix the crash but leave every agent holding a reference to the exact same list object. VirusAgent.generate_dna mutates that list in place on reproduction (dna[idx] = (dna[idx] + 1) % 10), so the first virus that reproduces would silently corrupt every other virus's starting DNA too. agents.py already deepcopies dna elsewhere for this same reason (AntibodyAgent's memory of a virus's dna), so this gives each of the 20 initial virus agents its own copy.deepcopy of the shared starting DNA instead.

Verified against the pre-fix commit: fails with the ValueError above before, passes after. Full test_examples.py 25 passed. ruff check + format clean.

create_agents recently started raising when a per-agent kwarg's sequence
length doesn't match the agent count. dna here is a single 3-gene list
meant to seed every initial virus, so passing it straight through as
dna=dna (length 3) against 20 virus agents now raises instead of the
model even starting.

Broadcasting it as dna=[dna]*initial_viruses would fix the crash but
every agent would then share the exact same list object. VirusAgent's
own generate_dna() mutates that list in place on reproduction
(dna[idx] = ...), so the first virus that reproduces would silently
corrupt every other virus's starting dna too. agents.py already
deepcopies dna for this same reason elsewhere (AntibodyAgent's memory
of a virus's dna), so give each of the 20 initial virus agents its own
deepcopy of the shared starting dna instead.
@quaquel

quaquel commented Sep 14, 2026

Copy link
Copy Markdown
Member

but is this not something that should be fixed inside mesa itself in some way?

@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

imo mesa core already has a strict=False broadcast hook in _resolve_per_agent_values but create_agents never exposes it, fixing that properly is an api call for you all. happy to open a follow-up on mesa/mesa, this just unblocks the example for now

@quaquel

quaquel commented Sep 14, 2026

Copy link
Copy Markdown
Member

I was actually referring more to the copy side of things. The strict api thing is a leftover that might even be removed.

@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

ah gotcha, missed that. yeah could make sense for create_agents to deepcopy mutable values per agent by default so no one has to remember to. do lmk how you plan on moving forward

@quaquel

quaquel commented Sep 16, 2026

Copy link
Copy Markdown
Member

ah gotcha, missed that. yeah could make sense for create_agents to deepcopy mutable values per agent by default so no one has to remember to. do lmk how you plan on moving forward

I suggest you open an issue on the main mesa repo where we can discuss it. There might be some performance considerations as well.

@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

opened mesa/mesa#3863

@lahari936

Copy link
Copy Markdown
Contributor

Nice catch, and the write-up made it easy to follow — the create_agents length validation from mesa/mesa#3824 is exactly what's turning the examples job red on every mesa PR right now.

One thing worth folding in before this merges, because I think it leaves the bug half-alive.

Giving each of the 20 initial viruses its own deepcopy fixes creation. But VirusAgent.generate_dna() writes into the list it is handed and returns that same object:

def generate_dna(self, dna=None):
    if dna is None:
        return [self.random.randint(0, 9) for _ in range(3)]
    idx = self.random.randint(0, 2)
    ...
    dna[idx] = (dna[idx] + 1) % 10
    return dna

and duplicate() calls it with the parent's own genome:

dna=self.generate_dna(self.dna)

So the first time a virus reproduces, it mutates its own dna in place and hands the child the identical list object. Parent and child alias from then on, and the population drifts back toward shared genomes — the thing this PR is fixing at creation time.

I applied just this PR's change to a clean checkout and checked:

initial dna objects distinct:                   True    <- this PR fixes it
parent genome unchanged by spawning a child:    False
child dna is a separate object:                 False

One line in agents.py closes it:

def generate_dna(self, dna=None):
    if dna is None:
        return [self.random.randint(0, 9) for _ in range(3)]
    dna = list(dna)   # copy, so a parent keeps its genome when it spawns a child
    idx = self.random.randint(0, 2)
    ...

That also makes the semantics match what duplicate() reads like it intends: the child is a mutated copy of the parent, not a rename of it.

Happy either way — add it here and I'll review, or merge this as-is and I'll open a small follow-up with that line plus tests for the invariants (viruses share a strain without sharing a list, mutating one leaves the others alone, duplication doesn't rewrite the parent). I have them written and passing locally; test_examples.py goes 24 passed / 1 failed → 25 passed. Your call, it's your fix.

@RudraDudhat2509

Copy link
Copy Markdown
Contributor Author

good catch, gonna keep this pr scoped to just the creation time fix tho as the scope as already been agreed, feels like a separate thing in duplicate()/generate_dna rather than something this pr should also be carrying.

go ahead and open the follow up, sounds like you already got the fix + tests ready which would be clutch. appreciate you digging into it this deep !

@quaquel
quaquel merged commit 6f0eae5 into mesa:main Oct 28, 2026
3 checks passed
quaquel added a commit that referenced this pull request Oct 28, 2026
VirusAgent.generate_dna() writes into the list it is handed and returns that
same object, and duplicate() calls it with the parent's own genome:

    dna=self.generate_dna(self.dna)

So the first time a virus reproduces it rewrites its own dna in place and
hands the child the identical list. Parent and child alias from then on, and
any later mutation by either one changes both.

Copying before mutating makes the behaviour match what duplicate() reads
like it intends: the child is a mutated copy of the parent, not another name
for it.

This is the follow-up to #496, which fixes the matching problem at creation
time, where one shared dna list was passed for every initial virus. Scope
agreed with @RudraDudhat2509 there. The two halves are independent: this one
is reproducible on main today without #496, because it goes through
VirusAgent directly rather than VirusAntibodyModel.

Adds two tests, both failing on main:
- generate_dna() leaves the genome it is given alone
- duplicate() gives the child its own list, and mutating the child does not
  change the parent

Co-authored-by: Jan Kwakkel <[email protected]>
quaquel pushed a commit that referenced this pull request Oct 28, 2026
The Meta-Agents Rewrite (mesa/mesa#3811, mesa/mesa#3875) moved the package
from mesa.meta_agents to mesa.experimental.meta_agents, and mesa no longer
exports meta_agents at the top level. The warehouse example still imported
the old path:

    from mesa.meta_agents import MetaAgents

Since test_examples.py imports every model module, that ModuleNotFoundError
aborts collection, so the whole examples suite fails before a single test
runs. That is the examples job currently red on mesa main, and therefore on
every open mesa PR.

mesa's own migration guide gives the new path: "Meta-agents still live in
mesa.experimental.meta_agents". Nothing else in the example needs changing,
since the rest already uses the rewritten API through model.meta_agents.

Against mesa main, test_examples.py goes from 1 collection error, 0 tests run
to 24 passed / 1 failed. The remaining failure is VirusAntibodyModel, a
separate pre-existing bug fixed by #496.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants