Skip to content

Backport fixes for Mesa 3.5.3 - #4129

Merged
EwoutH merged 47 commits into
mesa:3.5.x-maintenancefrom
EwoutH:3.5.3-backport
Nov 22, 2026
Merged

EwoutH merged 47 commits into
mesa:3.5.x-maintenancefrom
EwoutH:3.5.3-backport

Conversation

@EwoutH

@EwoutH EwoutH commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

Backports 42 PRs from main, plus the Starlette 1.x support from #4007 and the Solara floor from #4170 (still open on main), to 3.5.x-maintenance and bumps the version to 3.5.3, with release notes in HISTORY.md. The notes also cover #4064, which went straight into the maintenance branch after 3.5.2.

All 75 PRs merged to main from the 3.5.2 cut-off (#4012) up to #4161 (merged 2026-11-21) were triaged, including the four labelled backport-candidate (#3913, #3916, #3951, #4028). The second round (#3913, #4061, #4072, #4105, #4126, #4136, #4141, #4157, #4161 and the Starlette change) was added on 2026-11-22. Picks are git cherry-pick -x, oldest first. Adapted commits keep the original author and explain what changed in the commit message.

Changes that can alter results

#3932, #3946, #3959, #3995, #4048, #4052 and #4119 can change simulation results, but only where the 3.5.2 behaviour was wrong or contradicted the docs. #4061 and #4072 change what the experimental JSONDataRecorder stores (agent ids and field names for numpy datasets; window_size is now honoured). The release notes call this out.

Adapted for 3.5.x

Not backported

Testing

  • pytest tests/ -Werror -Wdefault::PendingDeprecationWarning: 831 passed, 1 skipped, on both Python 3.13 and 3.15.2 for the first round. With the second round: 839 passed, 1 skipped on Python 3.14; the 5 tests that need pytest-mock weren't run locally (not installed), so CI covers those. The 9 Playwright browser tests in tests/examples/test_examples_viz.py were not run locally (no browser installed).
  • With Require Solara 1.65.2 and document the ipyvue 3 workaround #4170: tests/visualization passes (148 tests) with Solara 1.66.3 and ipyvue/ipyvuetify 3.1.1.
  • CI: Start testing Python 3.15 #3830 adds Python 3.15 to CI. The full local run on 3.15.2 passes.
  • ruff check: the two remaining warnings are in files this branch doesn't touch.
  • Docs were not built locally.

After merging (fast-forward), publish the v3.5.3 draft release and set __version__ to 3.5.4.dev.

AI use: the backport triage, cherry-picks, adaptations, tests and release notes were prepared with Claude Code.

dietcoke-17 and others added 30 commits November 16, 2026 23:47
When no agent data has been recorded (e.g. before collect() is called or when collect() runs on a model with zero agents), all_records is an empty generator. Passing an empty generator to pd.DataFrame.from_records with an index parameter causes pandas to misparse the index labels as row entries, producing a non-empty DataFrame of length 2 containing spurious all-NaN rows instead of an empty DataFrame of length 0.

Materialize all_records to a list before constructing the DataFrame, matching the behavior and fix established in get_agenttype_vars_dataframe (mesa#3797).

Co-authored-by: Gracy769 <[email protected]>
(cherry picked from commit c45fbb7)
)

Adapted for 3.5.x: uses the HasPropertyLayers API (_mesa_properties, _mesa_property_layers) instead of 4.0's property_layers and read-only layers; tests adapted the same way.

(cherry picked from commit b3bedf7)

Assisted-by: Claude Opus 5.5
clear() with no arguments removed the per-dataset storage instead of
emptying it, so the next model step raised KeyError. Empty each dataset's
list instead, and raise KeyError for an unknown dataset name, which is
what DataRecorder, ParquetDataRecorder and SQLDataRecorder already do.

The existing test asserted the KeyError after clear(), so it now checks
for an empty dataset instead.

Fixes mesa#4014

(cherry picked from commit d420962)
* fix: wrap torus query points before distance calculations

ContinuousSpace.calculate_distances and calculate_difference_vector
applied the minimum-image convention without first wrapping the query
point into the space bounds. That convention only holds when the
per-axis separation is at most the space size, so an out-of-bounds
query point produced a negative intermediate which then surfaced as an
incorrect positive distance once squared.

On a unit torus with an agent at [0.1, 0.1], a query at [2.9, 0.1]
returned 1.8 and [1.9, 0.1] returned 0.8, although both are congruent
to [0.9, 0.1] modulo the space size and should return 0.2.

Agent positions are already wrapped on assignment, so only the query
side could violate the invariant. Both methods now apply the existing
torus_correct before computing deltas. This also fixes
get_agents_in_radius and get_k_nearest_agents, which delegate to
calculate_distances.

* Correct the torus separation lazily to avoid a hot-path cost

The benchmark bot reported BoidFlockers run time up 11.8% (small) and 9.4%
(large). BoidFlockers is the only continuous-space model in the suite and the
only one flagged, so the cost came from calling torus_correct on the query
point in every calculate_distances call.

Agents query with their own position, which the position setter has already
wrapped, so for that case the wrap was pure overhead. The separation is now
computed first and only folded when some axis actually exceeds the space size,
which is the only situation where the minimum image convention breaks.

The check is per axis rather than against the largest axis. A global maximum is
wrong for a space such as [[0, 0.5], [0, 50]], where a separation of 1.0 on the
first axis exceeds that axis but not the global maximum of 50.

* Use a Python-level bounds check to cut the hot-path cost

Replaces the numpy per-axis guard from the previous commit, which was slower
than the wrap it was meant to avoid because it scanned the whole separation
array.

Agents query with their own position, which the setter has already wrapped, so
the correction is almost never needed. The bounds are cached as plain Python
floats in __init__ and compared without touching numpy, which is what makes the
check cheaper than the work it skips.

Measured on BoidFlockers small, 20 steps, minimum of 15 replications:
main 290.7 ms, torus_correct on every call 329.4 ms, numpy per-axis guard
333.6 ms, this version 324.9 ms. So this is the cheapest correct option I
found, but it does not remove the cost: roughly 12% remains, since any
per-query check costs microseconds and the benchmark makes about 8000 queries.

* Skip the bounds check on the agent query paths

ContinuousSpaceAgent.get_neighbors_in_radius and get_nearest_neighbors query
with the agent's own position, which the position setter keeps inside the
bounds. Those calls can therefore skip the bounds check in
calculate_distances, which is what the benchmark regression was paying for.

calculate_distances, get_agents_in_radius and get_k_nearest_agents take a
private keyword-only _in_bounds flag, and only the two agent methods set it.
Model code calling any of these directly is unaffected and still gets the
check, so an out-of-bounds query point is handled exactly as before.

BoidFlockers small, 20 steps, minimum of 15 replications: main 290.7 ms,
this branch 287.0 ms. The earlier commits measured 329.4 ms with the wrap on
every call and 324.9 ms with the Python bounds check.

* Only wrap the query point in calculate_difference_vector when needed

The benchmark re-run on the previous commit still showed BoidFlockers run time
up 6.1% (small) and 5.4% (large). calculate_distances had been optimised, but
calculate_difference_vector still called torus_correct unconditionally, and the
boids example calls it once per agent per step with the agent's own position,
which is already inside the bounds.

It now uses the same plain Python bounds check as calculate_distances and only
wraps when some coordinate is outside, so an out-of-bounds query point behaves
exactly as before.

BoidFlockers small, 20 steps, minimum of 15 replications, three interleaved
rounds on one machine: main 289.9 ms on average, previous commit 308.7 ms
(+6.5%, in line with the bot's +6.1%), this commit 295.9 ms (+2.1%).

* Simplify torus query-point wrapping

Call torus_correct(point) unconditionally on a torus instead of checking the
bounds first. This removes the per-axis bounds tuples and the private
_in_bounds flag, and restores continuous_space_agents.py to its original form.

* Wrap torus query points only when they are outside the bounds

Benchmarks showed that calling torus_correct on every query adds about 1.5 us
per call, which is 20 to 40 percent of a query in small spaces. A small helper
that wraps only out-of-bounds points keeps the overhead near 0.5 us, without the
_in_bounds flag or changes to continuous_space_agents.py.

* Skip the torus bounds check for agent queries

Agents query with their own position, which the setter keeps inside the
space, so they pass a private flag to skip the check. Other queries are
still checked and wrapped.

---------

Co-authored-by: AryamannSrivastava <[email protected]>
Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 9251a9f)
_scatter popped s and alpha out of the arguments, which the image marker
branch needs, but ordinary markers then never got them, so every agent was
drawn at the default size and fully opaque. Read them without popping, as
MatplotlibBackend already does.

(cherry picked from commit 7728f16)
copy_renderer still copied space_kwargs and agent_kwargs, but
SpaceRenderer stores them as draw_space_kwargs and draw_agent_kwargs.
The old names don't exist anymore, so pressing Reset silently dropped
everything passed to setup_structure() and setup_agents().

Copy the right attributes, and copy the dicts so the old and new
renderer don't share them. Add a regression test.

Fixes mesa#3948

(cherry picked from commit b687223)
* Remove the dead inner cache on Cell._neighborhood

Cell.get_neighborhood() and Cell._neighborhood() are both decorated with
functools.cache and take the same arguments, and _neighborhood() is only
ever called from get_neighborhood(). That means the inner cache can never
serve a hit: on an outer hit _neighborhood() is not called at all, and on
an outer miss it is called exactly once for that key. Its cache only ever
accumulates entries.

Measured on a 100x100 Moore grid warmed at radius 1 and 2, the inner cache
reports hits=0, misses=20000, currsize=20000, and dropping it gives:

  retained memory   32.420 MiB -> 30.026 MiB  (-7.4%)
  cold first pass   76.7 ms    -> 68.3 ms     (-11%, median of 5 runs)
  warm 20x pass     48.5 ms    -> 47.4 ms     (unchanged, as expected)

Both arms ran against the same source, interleaved, with the decorator
stripped at runtime in the second arm.

Because functools.cache keys on self, the removed cache also held a second
strong reference to every Cell on top of the one the get_neighborhood cache
already holds, so it doubled the number of cells pinned alive by the
class-level caches.

Adds two tests covering what the deleted cache_clear() call could otherwise
have been protecting: that connect() and disconnect() invalidate the cached
neighborhood, at radius 1 and at radius 2.

* Assert radius-2 invalidation instead of clearing the cache by hand

The second test called cells[0]._clear_cache() by hand after connecting
cells[1] to cells[2], and my review note claimed the assertion failed
without it. That was wrong, and I had not actually tried removing it.

functools.cache on a method is one cache shared by the whole class, so the
cache_clear() that cells[1].connect() triggers already drops cells[0]'s
cached radius-2 entry. Verified on this branch:

    cells[0].connect(cells[1], key=(1,))
    cells[0].get_neighborhood(radius=2)   # {cells[1]}
    cells[1].connect(cells[2], key=(1,))  # no manual clear
    cells[0].get_neighborhood(radius=2)   # {cells[1], cells[2]}

Dropping the manual clear makes the test assert the case worth asserting:
that a connect() one hop away invalidates a radius-2 neighborhood that spans
it. That is also the case that would regress if invalidation is later scoped
per cell for mesa#3445.

Thanks to @AshNicolus for catching this in review.

---------

Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 6cfb252)
Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit f3dc333)
* fix: process events due at the current time in run_until

* fix: align time advancement warnings with the guards

---------

Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit c9600b8)
_advance_time assigned the end time and each event's time as given, so
run_until(5) or schedule_event(at=2) left model.time as an int, while
run_for always gave a float. That showed up as mixed 3.0 / 3 times in
JSONDataRecorder output and t=5 vs t=5.0 in labels. Convert both
assignments to float.

(cherry picked from commit 1d3b61e)
Adapted for 3.5.x: tests use 3.5's setup_propertylayer/draw_propertylayer names and the _mesa_property_layers API; the fix itself applied unchanged.

(cherry picked from commit aa4ca48)

Assisted-by: Claude Opus 5.5
…ger (mesa#4082)

* fix(logging): resolve qualified method name dynamically in method_logger

- Replace static inspect.getouterframes() lookup at decorator definition time with dynamic func.__qualname__ evaluation inside the wrapper.
- Prevent '<module>' or outer frame names from being logged when decorating class methods.
- Add unit test in tests/test_mesa_logging.py verifying qualified class and method name logging.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* style(tests) : move method_logger import to top of file.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
(cherry picked from commit 86a34d8)
mesa#3995)

* fix(continuous_space): return at most k agents from get_nearest_neighbors

get_nearest_neighbors requests the k + 1 nearest agents and filters out
self. When more than k other agents share the querying agent's position,
self may not be among the k + 1, so k + 1 agents were returned. Keep at
most k.

Also correct the get_k_nearest_agents docstring: ties at the k-th
distance are resolved deterministically by np.argpartition, which is not
stable, so they do not follow insertion order.

Fixes mesa#3898

* fix(continuous_space): collect nearest neighbors in a single loop

Stop at k neighbors in one pass instead of filtering and slicing three
times, and drop the docstring change since argpartition is no longer used.

---------

Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 89dd9ca)
)

Adapted for 3.5.x: 3.5 has no mesa.exceptions, so removing a missing cell from a directed Network raises KeyError, like DiscreteSpace.remove_cell on 3.5.

(cherry picked from commit f36fcfd)

Assisted-by: Claude Opus 5.5
mesa#4086)

PlotMatplotlib called post_process(ax) before it set the x label to
"Step" and the x tick locator to MaxNLocator(integer=True). Any x label
or x tick change made in post_process was therefore overwritten, for
example ax.set_xlabel("Time Step") in tutorials 8 and 9.

Call post_process last, after the defaults, as SpaceMatplotlib and
PlotAltair already do. Plots without post_process look the same.

(cherry picked from commit 257aebf)
…recorders (mesa#4079)

* Explain what clear() does with files on disk in the JSON and Parquet recorders

* Say Parquet file(s) in the clear() docstring

(cherry picked from commit 17deb72)
HexGrid connects cells using even-r offsets (even rows shifted right),
as its docstring says, and the hex mesh in mpl_space_drawing uses the
same layout. cell.position was computed with odd rows shifted instead,
so on every cell some connected neighbours were not touching hexagons
when drawn at cell.position.

Shift even rows in _init_hex_geometry so positions agree with the
connections. Connectivity itself is unchanged.

Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit e1ca9ea)
…a#4084)

When schedule.start is None, EventGenerator.start() schedules the first
event at model.time + interval without checking it against schedule.end.
If that time is already past end, the generator fires once outside its
window. Check _should_stop() before scheduling the first event, matching
what resume() already does.

(cherry picked from commit 6319f9b)
Unpickling a ContinuousSpace turned agent_positions into an independent
array instead of a view on the backing array. Positions written through
agents then went only to the copy, and were lost as soon as an agent was
added or removed and the view was taken again. Take the view again in
__setstate__.

(cherry picked from commit 28e4136)
…3953)

Adapted for 3.5.x: uses 3.5's propertylayer_mesh / draw_propertylayer / setup_propertylayer names.

(cherry picked from commit e43e3c9)

Assisted-by: Claude Opus 5.5
Fixes the flaky Playwright viz tests by taking the two initial screenshots from the newest image, like the later screenshots already do.

(cherry picked from commit 667c62b)
…#4046)

Fixes property layer visualization on HexGrid where colors are drawn on the wrong hexagons due to mismatched array ordering.

Partly backported for 3.5.x: only the legacy draw_property_layers fix. On 3.5 the
SpaceRenderer hexagon mesh is still row-major, so the matplotlib backend already
uses data.T.ravel() correctly and is left unchanged. The SpaceRenderer test
checks the row-major order instead.

(cherry picked from commit ac849e1)

Assisted-by: Claude Opus 5.5
Adapted for 3.5.x: the Agent.remove() and Event/EventGenerator parts only. 3.5 has no experimental states (Threshold) or locations, so those hunks and their tests are dropped.

(cherry picked from commit eac7447)

Assisted-by: Claude Opus 5.5
… agent (mesa#3970)

Adapted for 3.5.x: 3.5 has the pre-rewrite meta-agents API, so the same one-line fix is applied to its extract_class and a regression test is written for create_meta_agent (remove the last instance, then create the class again by name), which raised StopIteration before.

(cherry picked from commit f6f7e53)

Assisted-by: Claude Opus 5.5
arzaanxeng and others added 3 commits November 16, 2026 23:47
Python has released it final 3.15 release candidate, 3.15.0rc2. This seems to be a good moment to see what breaks and what not. Most likely we will have some upstream dependencies who are not ready yet.

https://www.python.org/downloads/release/python-3150rc2/
(cherry picked from commit b5c3b20)
Assisted-by: Claude Opus 5.5
@github-actions github-actions Bot added ci Release notes label docs Release notes label example Changes the examples or adds to them. experimental Release notes label packaging Release notes label testing Release notes label visualization labels Nov 16, 2026
@EwoutH
EwoutH requested a review from quaquel November 16, 2026 22:56
@mesa-triage-bot

Copy link
Copy Markdown

Thanks @EwoutH for documenting the adapted backports and changes that can affect results. The diff also reformats existing examples throughout docs/migration_guide.md, older HISTORY.md entries, benchmarks/README.md, and CONTRIBUTING.md.

Please drop those formatting-only hunks so reviewers can focus on the backports and release notes.

Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot.

@quaquel quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@tpike3 tpike3 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow that is a quite a bit of good changes, thanks @EwoutH !

EwoutH and others added 11 commits November 19, 2026 11:06
Backport the Starlette cap removal from cbba490 (mesa#4007). Require Solara 1.57.4 or newer for its Starlette lifespan fix (widgetti/solara#1151).

Assisted-by: GPT-6
DatasetConfig.window_size is documented as the maximum number of snapshots to keep. DataRecorder applies it, but JSONDataRecorder kept every snapshot, so memory grew without bound and save_to_json wrote the full history.

Adapted for 3.5.x: 3.5 recorders do not record when a run ends (mesa#4041 is 4.0-only), so after run_for(4) the window holds times 2.0 and 3.0; DataRecorder gives the same. The test's expected values are changed accordingly.

(cherry picked from commit 668c892)

Assisted-by: Claude Opus 5.5
mesa#4141)

* fix(examples): use citizen_vision for Citizen agents in Epstein Civil Violence

* refactor(examples): declare vision as type annotation on EpsteinAgent

(cherry picked from commit b593bee)
…strong ref leaks in set operations (mesa#4105)

* fix(agentset): implement _from_iterable to preserve random and avoid strong ref leaks in set operations

* fix(agentset): preserve subclass type in _from_iterable and test leak prevention

Adapted for 3.5.x: the conflict is only in tests/test_agentset.py, where main's tests follow 4.0-only weighted select_random tests. Only the tests added by mesa#4105 are taken, with their gc, warnings and weakref imports.

(cherry picked from commit 71f239a)

Assisted-by: Claude Opus 5.5
…esa#4136)

The tutorials were renumbered, so tutorials/4_visualization_basic.html
returns 404. Point the general visualization link at
6_visualization_basic and the SpaceRenderer link at
8_visualization_rendering_with_space_renderer.

(cherry picked from commit 5b63f09)
…esa#4061)

* Keep agent ids and field names when JSONDataRecorder stores a numpy dataset

A NumpyAgentDataSet hands the recorder a bare array of values. The JSON
recorder stored it with tolist() and nothing else, so neither the saved
file nor get_table_dataframe() said which agent a row belonged to or
which field a value was. The dataset removes agents by swapping in the
last row, so row order does not identify an agent either. The dataframe
came back as one row per snapshot with the whole nested list in a
"value" column, where the other three recorders return agent_id, the
fields and time.

Store such a snapshot as one dict per agent, with agent_id and the
field names, which is the shape the recorder already uses for an
AgentDataSet. An array from a dataset without agent ids is stored as
before.

Co-Authored-By: Claude <[email protected]>

* Test that agent ids stay with their values after a removal

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

---------

Co-authored-by: Claude <[email protected]>
(cherry picked from commit feb8845)
…mesa#4157)

JSONDataRecorder.data now holds a bounded deque per dataset (mesa#4072), while the test added in mesa#4061 compares it to a list, so main fails test_json_recorder_stores_a_plain_array_as_a_list. Convert to a list before comparing.

(cherry picked from commit e89f241)
* Fix partial model data collection after reporter failures

Signed-off-by: Sahil Kumar Singh <[email protected]>

* test(datacollector): cover model reporter evaluation and copy failures

Signed-off-by: Sahil Kumar Singh <[email protected]>

---------

Signed-off-by: Sahil Kumar Singh <[email protected]>
Co-authored-by: Jan Kwakkel <[email protected]>

Adapted for 3.5.x: 3.5 records the collection step even without model reporters (mesa#3579), so the step is appended after the model reporter block, once all model reporters have succeeded, instead of inside it.

(cherry picked from commit 7379e9e)

Assisted-by: Claude Opus 5.5
Add mesa#3913, mesa#4061, mesa#4072, mesa#4105, mesa#4126, mesa#4136, mesa#4141, mesa#4157, mesa#4161 and the Starlette 1.x support backported from mesa#4007, and move the release date to 2026-11-22.

Assisted-by: Claude Opus 5.5
Fresh installs now pull in ipyvue and ipyvuetify 3 (Vue 3), as Solara
doesn't cap them. Solara 1.65.2 fixes the blank GridDraggable that this
caused in SolaraViz, so require at least that version.

In Jupyter notebooks, the Solara sidebar and fullscreen mode still don't
work with ipyvuetify 3 (widgetti/solara#1292, mesa#1294; fix in mesa#1293).
Solara supports both Vue versions and declines to cap them, so document
installing ipyvue<3 and ipyvuetify<3 instead of capping them in Mesa.

Refs mesa#4133.

Backport of mesa#4170, which is still open on main.

Adapted for 3.5.x: raised the existing solara>=1.57.4 floor; 3.5 has no
websockets<14 pin, so that part of the context was left out.

Assisted-by: Claude Opus 5.5
@EwoutH
EwoutH merged commit ee3a808 into mesa:3.5.x-maintenance Nov 22, 2026
17 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Release notes label docs Release notes label example Changes the examples or adds to them. experimental Release notes label packaging Release notes label testing Release notes label visualization

Projects

None yet

Development

Successfully merging this pull request may close these issues.