Skip to content

Remove the dead inner cache on Cell._neighborhood - #3934

Merged
quaquel merged 4 commits into
mesa:mainfrom
lahari936:fix-redundant-neighborhood-cache
Nov 7, 2026
Merged

quaquel merged 4 commits into
mesa:mainfrom
lahari936:fix-redundant-neighborhood-cache

Conversation

@lahari936

@lahari936 lahari936 commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

Cell.get_neighborhood() and Cell._neighborhood() are both decorated with
functools.cache and take the same arguments, and _neighborhood() is only
called from get_neighborhood(). The inner cache therefore never serves a hit —
it only accumulates entries, and because functools.cache keys on self, it
holds a second strong reference to every Cell.

Bug / Issue

Related to #3379 (third bullet: neighborhood access constructing intermediate
mappings). Not a full fix for that issue — it addresses one concrete piece of it.

On a 100x100 Moore grid warmed at radius 1 and 2:

inner _neighborhood: CacheInfo(hits=0, misses=20000, maxsize=None, currsize=20000)

Zero hits across 20 000 entries, on every workload, by construction.

Implementation

Removed @cache from _neighborhood and the corresponding
self._neighborhood.cache_clear() from _clear_cache. get_neighborhood
stays cached; no API changes, _neighborhood is private and has no external
callers.

Testing

pytest tests --ignore=tests/examples → 837 passed. pytest tests/discrete_space
→ 109 passed. ruff check and ruff format --check clean. (tests/examples has
9 pre-existing fixture 'solara_test' not found errors, identical on main.)

Added two regression tests covering what the deleted cache_clear() call could
have been protecting: that connect() and disconnect() invalidate a cell's own
cached neighborhood, and that a connect() one hop away invalidates a radius-2
neighborhood spanning it. The second case is the one that would regress if
invalidation is later scoped per cell for #3445.

Benchmark, both arms on identical source, interleaved across 5 runs, with the
decorator stripped at runtime in the second arm:

metric (100x100 Moore, warmed r=1 and r=2) with inner cache without delta
retained memory 32.420 MiB 30.026 MiB -7.4%
cold first pass over 10 000 cells 76.7 ms 68.3 ms -11%
warm 20x pass 48.5 ms 47.4 ms unchanged

The warm path is unchanged, as it should be — the outer cache serves every warm
call either way. That is the control for the methodology.

Additional Notes

This also halves the number of Cell references pinned by the class-level
caches, which is relevant background for #3445, though it does not address the
global-invalidation question there.

It halves the cache_clear() work during space construction as well, since
connect() now clears one cache instead of two. That one is deterministic rather
than a timing claim:

connect() calls building a 100x100 Moore torus: 80000
cache_clear() calls -> main: 160000, this branch: 80000

GSoC contributor checklist

Context & motivation

Why I'm addressing it

I wanted to find a useful improvement in Mesa that no open PR already covered.

How I found it

  • I went through open issues and PRs, then read mesa/discrete_space/cell.py.
  • Both get_neighborhood() and _neighborhood() use functools.cache, but _neighborhood() is only ever called through get_neighborhood().

What caught my attention

In my benchmark, the inner cache had zero hits and built up 20,000 entries. It was holding memory and adding overhead for nothing.

Why it interests me

It's a small, contained fix. It saves memory without changing the public API or how neighborhood queries behave.

How I investigated it

  • Compared the two implementations on memory and execution time.
  • Ran regression tests to confirm neighborhood invalidation still works.

What I learned

As a new contributor, the best part was digging through Mesa's codebase until I found the exact lines behind an unnecessary cache. What looked like a small optimization took hours of tracing function calls, reading existing code, and working out how the pieces fit together. I used AI to help me understand unfamiliar code, but I still had to check the behavior myself and tie each explanation back to what the project was actually doing. Finding and fixing a real issue in a real codebase felt great.

On the technical side, I learned how functools.cache holds references to its arguments, including self, and how a redundant cache can cost memory without giving anything back. Tracing Cell.get_neighborhood() and Cell._neighborhood() showed me why the inner cache never got a hit: the outer cache always answered first. I also learned to back an optimization with evidence. I compared memory and execution time, tested cold and warm runs, and ran regression tests to make sure nothing broke.

I also saw how open-source contribution works in practice. Finding an issue is only the start. You have to understand the surrounding code, check existing issues and PRs, follow the project's conventions, write tests, and be honest about limitations. A three-line change can need a lot of investigation before it's safe.

Mostly, I learned to read unfamiliar code patiently before writing any. I have a lot more to learn about Mesa, but I'm now more comfortable finding my way around an established codebase, asking sharper questions, and using AI to learn rather than to skip understanding the code.

Specific takeaways

  • How functools.cache keys results on arguments, and that caching a method keeps a reference to self, so objects can live longer than they should.
  • To trace who calls a function before deciding its cache is redundant.
  • To benchmark fairly: same workload, interleaved runs, cold and warm cache measured separately.
  • That removing an optimization means re-checking what depends on it. Here, that was neighborhood invalidation after cells connect or disconnect.
  • To check existing issues and PRs before picking one, so I don't duplicate someone's work.

What was harder than I expected

  • Finding an open issue. Most easy bugs already had competing PRs.
  • Spotting the redundant cache. One function didn't show it. I had to trace the callers and look at cache stats.
  • The deleted lines were few, but proving the change safe took much longer than writing it.
  • The gains were clear for memory and cold runs but small for warm runs. That showed me why testing different conditions matters.
  • Telling my own breakage apart from the environment's. Some example tests errored on a missing solara_test fixture, which went away once I installed solara[pytest], and one unrelated test still fails in full-suite order. Running the same suite on an unchanged baseline checkout showed both were pre-existing, not regressions I caused.

Learning repo

🔗 My learning repo: https://github.com/lahari936/GSoC-learning-space
🔗 Relevant model(s): n/a — this fix came out of reading and profiling discrete_space rather than from a model

Readiness checks

  • This PR addresses an agreed-upon problem (linked issue or discussion with maintainer approval), or is a small/trivial fix
  • I have read the contributing guide and deprecation policy
  • I have performed a self-review: I reviewed my own PR as if I were a reviewer and left comments on anything that needs explanation
  • Another GSoC contributor has reviewed this PR: @AshNicolus
  • Tests pass locally (pytest --cov=mesa tests/)
  • Code is formatted (ruff check . --fix)
  • If applicable: documentation, examples, and/or migration guide are updated — n/a, _neighborhood is private and no public behaviour changes

Test run: pytest --cov=mesa tests/ → 861 passed, 1 failed, 86% coverage. The failure is
tests/experimental/test_actions.py::TestOnIdle::test_suppressed_wake_is_logged_at_debug, which is
pre-existing: a clean upstream/main worktree gives 859 passed and the same single failure. It passes
in isolation and only fails in full-suite order, so it looks like a test-isolation issue in logging
capture rather than anything in this PR.

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.
Copilot AI balanced review requested due to automatic review settings October 10, 2026 23:53

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added the testing Release notes label label Oct 10, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -5.5% [-6.0%, -4.9%] 🔵 +1.3% [+1.1%, +1.5%]
BoltzmannWealth large 🟢 -10.9% [-11.3%, -10.5%] 🔴 +5.3% [+4.4%, +6.4%]
Schelling small 🟢 -10.1% [-10.5%, -9.7%] 🔵 +1.1% [+0.4%, +1.8%]
Schelling large 🟢 -6.0% [-6.8%, -5.2%] 🔴 +9.3% [+5.7%, +13.0%]
WolfSheep small 🟢 -5.6% [-6.2%, -5.0%] 🔵 +1.1% [-3.2%, +5.3%]
WolfSheep large 🟢 -5.3% [-6.3%, -4.1%] 🔵 +1.7% [-0.5%, +3.5%]
SugarscapeG1mt small 🟢 -13.0% [-13.5%, -12.4%] 🔵 -0.1% [-1.7%, +1.6%]
SugarscapeG1mt large 🟢 -11.2% [-12.8%, -9.8%] 🔵 +0.8% [-1.1%, +2.9%]
BoidFlockers small 🔵 +0.1% [-0.4%, +0.6%] 🔵 +1.1% [+0.7%, +1.6%]
BoidFlockers large 🔵 +0.7% [+0.1%, +1.3%] 🔵 +1.0% [+0.4%, +1.7%]
MultiLevelAllianceModel small 🔵 -0.8% [-2.4%, +0.8%] 🔵 +1.6% [+1.1%, +2.1%]
MultiLevelAllianceModel large 🔵 +1.2% [-0.4%, +2.7%] 🔵 +1.5% [-0.0%, +3.0%]

@lahari936 lahari936 left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Self-review, as required by #3536. Four notes below on the parts I think need explaining, plus one limitation I want to flag rather than hide.

The short version: this deletes a cache layer that provably never serves a hit, and the two new tests exist to guard the invalidation path that the deleted cache_clear() call touched.


# FIXME: Revisit caching strategy on methods
@cache # noqa: B019
def _neighborhood(

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removing @cache here is the whole change, so here is why I believe it is safe.

_neighborhood is private and grep -rn "_neighborhood�" over the repo returns only three hits in this file: this definition, the single call site in get_neighborhood above, and the cache_clear() in _clear_cache that I also removed. No tests, docs or examples touch it.

Since get_neighborhood is itself cached with the identical signature, the inner cache can never produce 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. Measured on a 100x100 Moore grid warmed at radius 1 and 2:

inner _neighborhood:   CacheInfo(hits=0, misses=20000, maxsize=None, currsize=20000)
outer get_neighborhood: CacheInfo(hits=40000, misses=800, ...)

Zero hits across 20 000 entries. The entries were not free either, because functools.cache keys on self, so this cache held a second strong reference to every Cell on top of the one the get_neighborhood cache already holds.

@@ -292,4 +290,3 @@ def __getstate__(self):
def _clear_cache(self):
"""Helper function to clear local cache."""
self.get_neighborhood.cache_clear()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The deleted line here was self._neighborhood.cache_clear(). It has to go with the decorator: a plain function has no cache_clear, so leaving it raises AttributeError: 'function' object has no attribute 'cache_clear' on the first connect(). I hit exactly that while benchmarking, which is how I know it is not dead code in the sense of never running.

Invalidation itself is unaffected. _neighborhood no longer holds state, so clearing get_neighborhood is now sufficient: the next call recomputes the dict from self.connections and rebuilds the CellCollection. The two tests I added cover this.

assert cell1 in neighbor.neighborhood


def test_neighborhood_cache_invalidated_on_topology_change():

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Worth being explicit, since a reviewer would otherwise reasonably ask: these two tests also pass on main. That is deliberate. They are not a reproduction of a bug this PR fixes -- the dead cache was a waste, not a correctness problem. They exist because I deleted a cache_clear() call, and I wanted the invalidation behaviour that call was part of to be pinned down by a test before and after, so a future change cannot quietly break it.

I could find no existing test asserting that connect()/disconnect() invalidate a warmed neighborhood, which is partly why I added them.

assert set(cells[0].get_neighborhood(radius=2).cells) == {cells[1]} # warms

cells[1].connect(cells[2], key=(1,))
cells[0]._clear_cache()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Flagging this explicitly rather than leaving it to be discovered: this manual _clear_cache() is load-bearing, and I am not happy about it.

cells[1].connect(cells[2]) clears the cache on cells[1], not on cells[0]. So cells[0]'s warmed radius-2 entry is stale and the assertion below fails without the explicit clear. In other words, a topology change one hop away does not invalidate radius > 1 neighborhoods that span it.

That is pre-existing behaviour on main and this PR does not change it in either direction -- I verified both tests pass unmodified on main. It belongs to the invalidation-scoping discussion in #3445 and the dynamic-grid alignment quaquel asked for there, so I deliberately kept it out of scope here. I would rather the test document the current contract honestly than pretend radius-2 invalidation works. Happy to drop this second test if you would prefer it not encode that behaviour at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Correction: this comment is wrong, and @AshNicolus was right to push back.

The manual _clear_cache() was not load-bearing. functools.cache on a method is a single cache shared by the whole class, so the cache_clear() that cells[1].connect() triggers already drops cells[0]'s cached radius-2 entry. I asserted the opposite here without ever trying the removal, which is exactly the kind of claim a self-review is supposed to catch.

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]}

Fixed in 4855cfb: the manual clear is gone, so the test now asserts the case actually worth asserting -- that a connect() one hop away invalidates a radius-2 neighborhood spanning it. As Ash points out, that is also the case that would regress if invalidation is later scoped per cell for #3445.

@lahari936

Copy link
Copy Markdown
Contributor Author

@AshNicolus would you be up for a peer review on this one, per the process in #3536?

It's a small diff — three deleted lines in cell.py plus two regression tests. get_neighborhood() and _neighborhood() are both decorated with functools.cache and take the same arguments, and _neighborhood() is only ever called from get_neighborhood(), so the inner cache can never serve a hit (measured: hits=0, misses=20000).

My self-review is already posted inline, including one limitation I flagged rather than hid, around radius-2 invalidation.

Happy to return the favour on #3922 or whatever else you have open.

@AshNicolus AshNicolus left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Thanks for the ping. I checked out the branch and ran it locally: tests/discrete_space passes (109) and ruff check / ruff format --check are clean.

The main change looks right to me. _neighborhood is only called from get_neighborhood, both were cached on the same arguments, so the inner cache could never get a hit. And the _neighborhood.cache_clear() line has to go with the decorator, agreed.

One thing I don't agree with though, which is the second test and your inline note on it. The manual cells[0]._clear_cache() is not load-bearing. functools.cache on a method is a single cache shared by the whole class, so cache_clear() called from any cell wipes the cached neighborhoods of every cell (that is exactly what #3445 is about). So when cells[1].connect(cells[2]) runs, it already clears the radius-2 entry for cells[0]. I removed the manual clear on your branch and the assertion still passes:

cells = [Cell((i,), capacity=None, random=random.Random()) for i in range(3)]
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]}

So radius-2 invalidation does work on main today, just because the clear is global instead of scoped. The test as written documents a limitation that isn't there, and it skips the one case it should check. I'd drop the _clear_cache() line so the test actually asserts that a connect one hop away invalidates the radius-2 neighborhood. That's also the case that would quietly break if someone scopes invalidation per cell for #3445, so it's a good test to have. The PR description repeats the same claim, so worth updating that too.

On the benchmark bot: the two red run times (large Boltzmann and Schelling) don't worry me, since nothing here touches the warm path. The init gains might be real, as connect() now does one cache_clear() instead of two while the grid is built, but I didn't measure that.

With the test fixed, this looks good to me.

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.
@lahari936

Copy link
Copy Markdown
Contributor Author

Thanks for the careful read, @AshNicolus — you're right on all of it, and the correction is pushed in 4855cfb.

On the manual _clear_cache(). You're correct and my inline note was wrong. I claimed the assertion failed without it, and I had never actually tried removing it, which is embarrassing in a comment I wrote as a self-review. functools.cache on a method is one cache shared by the whole class, so cache_clear() from any cell wipes every cell's entries, and cells[1].connect(cells[2]) already drops cells[0]'s radius-2 entry. Reproduced exactly as you described:

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]}

The sharing is visible in the cache stats too — cells[0].get_neighborhood.cache_info() and cells[1].get_neighborhood.cache_info() report the same currsize, because there is only one cache.

So the manual clear was hiding the useful assertion behind a limitation that doesn't exist. Dropped it, and your framing is now in the docstring: the test asserts that a connect() one hop away invalidates a radius-2 neighborhood spanning it. Agreed that this is the case that would quietly regress if invalidation gets scoped per cell for #3445, which makes it worth keeping rather than just correcting.

I've also corrected the inline note rather than editing it away, so the exchange stays readable.

One small thing: I went back through the PR description and I don't think the claim is in it — it only says the tests cover radius 1 and 2, which is still true. If you spotted it somewhere I'm missing, point me at it and I'll fix it. I did sharpen that sentence to say what the radius-2 test actually asserts.

On the benchmark bot. Your hypothesis about the init path checks out, and it's nicer than a timing argument because it's deterministic. Building a 100×100 Moore torus makes 80,000 connect() calls, and each one used to run two cache_clear() calls instead of one:

connect() calls building a 100x100 Moore torus: 80000
cache_clear() calls -> main: 160000, this branch: 80000

Wall-clock agrees but weakly — interleaving this branch against a clean main worktree, grid construction minima came out around 41–45 ms versus 47–51 ms, with medians noisy enough that I wouldn't quote a percentage. I've added the call count to the description and left the timing out, since the halved cache_clear() count is the claim that actually holds up.

And agreed on the two red run times: nothing here touches the warm path, which is why the warm 20× pass in my benchmark is flat. That was the control, and it behaved.

Thanks again — this made the test better rather than just fixing it.

@lahari936

lahari936 commented Oct 12, 2026 via email

Copy link
Copy Markdown
Contributor Author

@lahari936

Copy link
Copy Markdown
Contributor Author

Note on the red examples job, so nobody re-investigates it: it is pre-existing on main and unrelated to this PR.

run result
main @ 5451086f 37892641437 FAILED test_model_steps[VirusAntibodyModel] — 1 failed, 24 passed
this PR 38257882247 FAILED test_model_steps[VirusAntibodyModel] — 1 failed, 24 passed

Same test, same error, and 5451086f is the commit this branch is based on:

ValueError: sequence of length 3 does not match the number of agents (20)
  mesa/agentset.py:101

It looks like the strict length validation added in #3824 surfacing a latent bug in the mesa-examples virus_antibody model, which passes a 3-element sequence for 20 agents, rather than anything wrong on the mesa side. Happy to open a PR against mesa-examples for it separately if that would help.

Every other check on this PR is green: all six build matrix jobs, coverage, codecov patch and project, docs, and pre-commit.

@AshNicolus

Copy link
Copy Markdown
Contributor

Thanks @lahari936, the updated test reads well. It now checks the case that matters for #3445.

You're right about the description, I mixed it up with the inline note. The sharpened sentence is good.

Looks good to me. And yes, a second look at #3922 would be great, thanks.

@quaquel quaquel added the bug Release notes label label Oct 28, 2026
@quaquel quaquel added the trigger-benchmarks Special label that triggers the benchmarking CI label Oct 28, 2026
@quaquel

quaquel commented Oct 28, 2026

Copy link
Copy Markdown
Member

I reran the benchmark results, which for reasons that I don't have the time to figure out now won't automatically are posted anymore.

See below:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -4.1% [-4.6%, -3.6%] 🔵 +0.2% [+0.1%, +0.3%]
BoltzmannWealth large 🟢 -7.9% [-8.7%, -7.2%] 🔴 +13.6% [+11.0%, +15.7%]
Schelling small 🟢 -8.2% [-8.6%, -7.8%] 🔵 +1.2% [+0.4%, +2.0%]
Schelling large 🟢 -7.6% [-8.1%, -7.1%] 🔵 +3.8% [+2.0%, +5.4%]
WolfSheep small 🟢 -4.5% [-5.0%, -4.0%] 🔵 +3.0% [-0.8%, +6.8%]
WolfSheep large 🟢 -4.9% [-5.9%, -3.9%] 🔵 +3.8% [+1.2%, +6.4%]
SugarscapeG1mt small 🟢 -10.1% [-10.8%, -9.4%] 🔵 +0.6% [-1.3%, +2.5%]
SugarscapeG1mt large 🟢 -11.7% [-13.0%, -10.4%] 🔵 +0.1% [-1.1%, +1.4%]
BoidFlockers small 🔵 -2.9% [-3.5%, -2.3%] 🔵 -2.3% [-2.8%, -1.7%]
BoidFlockers large 🔵 -2.2% [-2.8%, -1.6%] 🔵 -1.9% [-2.2%, -1.5%]
MultiLevelAllianceModel small 🔵 -1.6% [-2.9%, -0.2%] 🔵 -1.1% [-1.4%, -0.9%]
MultiLevelAllianceModel large 🔵 -0.7% [-1.6%, +0.2%] 🟢 -6.9% [-9.8%, -4.2%]

I still see a loss of performance on Boltzmann, so can you explain why this happens? The minor gain in startup time is already explained.

Also, a friendly request to @lahari936, I have the impression you rely strongly on AI for generating your text. This is fine up to a point, but we strongly encourage you to write your own responses and just use AI to improve the language.

@lahari936

Copy link
Copy Markdown
Contributor Author

The inner cache never gets hit, so it can't be causing the run time difference.

I instrumented both caches on main and ran the benchmarked config (n=10000, 100x100, 10 steps):

Cell.get_neighborhood  CacheInfo(hits=90002, misses=9998, maxsize=None, currsize=9998)
Cell._neighborhood     CacheInfo(hits=0,     misses=9998, maxsize=None, currsize=9998)

_neighborhood has one caller, get_neighborhood at cell.py:218, and both are keyed on the same (self, radius, include_center). Every call into _neighborhood is already a get_neighborhood miss, so the inner lookup can only repeat work the outer cache is about to store. It holds 9998 entries and serves no reads.

On the startup time: connect() calls _clear_cache() at cell.py:124, which on main clears two caches instead of one. Building the 100x100 grid makes 78804 connect calls, so main does 157608 cache_clear() calls during init where this branch does 78804. Every grid-based model does the same thing, which fits the init improvement appearing on all six rows rather than only Boltzmann.

For the run time I could not reproduce the regression. Three alternating rounds of the same config, 10 replications each, medians in seconds:

round main this branch
1 1.418 1.378
2 1.385 1.283
3 1.377 1.336

The branch is faster in all three. Within a single round main's own runs ranged 1.27 to 1.79, so the spread between repeats is wider than the 13.6% in the report.

This is Windows with 10 replications rather than your 10x3 on ubuntu, so treat it as a cross-check and not a reproduction. If it is useful I can push the cache instrumentation as a throwaway commit so the hit counts can be read off a CI run instead.

@quaquel
quaquel merged commit 6cfb252 into mesa:main Nov 7, 2026
16 checks passed
EwoutH pushed a commit that referenced this pull request Nov 22, 2026
* 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 #3445.

Thanks to @AshNicolus for catching this in review.

---------

Co-authored-by: Jan Kwakkel <[email protected]>
(cherry picked from commit 6cfb252)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label testing Release notes label trigger-benchmarks Special label that triggers the benchmarking CI

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants