Repository navigation
Remove the dead inner cache on Cell._neighborhood - #3934
Conversation
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.
|
Performance benchmarks:
|
lahari936
left a comment
There was a problem hiding this comment.
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( |
There was a problem hiding this comment.
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() | |||
There was a problem hiding this comment.
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(): |
There was a problem hiding this comment.
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() |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
@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 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
left a comment
There was a problem hiding this comment.
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.
|
Thanks for the careful read, @AshNicolus — you're right on all of it, and the correction is pushed in 4855cfb. On the manual 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 — 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 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 Wall-clock agrees but weakly — interleaving this branch against a clean 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. |
|
Hi Ash,
Thanks for taking the time on mesa/mesa#3934
<#3934> — that was a genuinely useful
review, not a rubber stamp.
You were right about the manual _clear_cache(), and I’d got it wrong in a
comment I wrote as a self-review, which is the worst place to be wrong. I’d
claimed the assertion failed without it and never actually tried removing
it. Your point that functools.cache on a method is one cache for the whole
class is the bit I hadn’t internalised — cache_clear() from any cell wipes
every cell’s entries, so the clear cells[1].connect() triggers already
covers cells[0]. I reproduced it exactly as you described and pushed the
fix in 4855cfb.
Your framing made the test better rather than just correct: without the
manual clear it now asserts that a connect() one hop away invalidates a
radius-2 neighbourhood spanning it, which is the case that would regress if
invalidation gets scoped per cell for #3445. That’s in the docstring now.
I also checked your hunch about the init path, since it was nicer than a
timing argument. Building a 100×100 Moore torus makes 80,000 connect()
calls, each of which used to run two cache_clear() calls instead of one —
160,000 against 80,000. Wall-clock agrees but too noisily to quote, so I
put the call count in the description and left the timing out.
Happy to return the favour properly — send me anything you’d like a second
pair of eyes on, mesa/mesa#3922 <#3922> or
otherwise.
Thanks again,
…On Mon, Oct 12, 2026 at 11:31 AM AshNicolus ***@***.***> wrote:
***@***.**** commented on this pull request.
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
<#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 clearcells[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
<#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.
—
Reply to this email directly, view it on GitHub
<#3934?email_source=notifications&email_token=BL3P7AG53YDYJKIR3FFVYID5TRXUHA5CNFSNUABKM5UWIORPF5TWS5BNNB2WEL2QOVWGYUTFOF2WK43UKJSXM2LFO4XTKNBYGY4TSMRWGIZ2M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KYZTPN52GK4S7MNWGSY3L#pullrequestreview-5486992623>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/BL3P7ACNNVBZA4PAVEENL4L5TRXUHAVCNFSNUABEKJSXA33TNF2G64TZHMZDIMRUGU3TGNZ3JFZXG5LFHM2TOOJWGM3TAOJVG2QXMAQ>
.
You are receiving this because you authored the thread.Message ID:
<mesa/mesa/pull/3934/review/5486992623 ***@***.***>
|
|
Note on the red
Same test, same error, and It looks like the strict length validation added in #3824 surfacing a latent bug in the mesa-examples Every other check on this PR is green: all six build matrix jobs, coverage, codecov patch and project, docs, and pre-commit. |
|
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. |
|
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:
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. |
|
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):
On the startup time: For the run time I could not reproduce the regression. Three alternating rounds of the same config, 10 replications each, medians in seconds:
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. |
* 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)
Pre-PR Checklist
Summary
Cell.get_neighborhood()andCell._neighborhood()are both decorated withfunctools.cacheand take the same arguments, and_neighborhood()is onlycalled from
get_neighborhood(). The inner cache therefore never serves a hit —it only accumulates entries, and because
functools.cachekeys onself, itholds 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:
Zero hits across 20 000 entries, on every workload, by construction.
Implementation
Removed
@cachefrom_neighborhoodand the correspondingself._neighborhood.cache_clear()from_clear_cache.get_neighborhoodstays cached; no API changes,
_neighborhoodis private and has no externalcallers.
Testing
pytest tests --ignore=tests/examples→ 837 passed.pytest tests/discrete_space→ 109 passed.
ruff checkandruff format --checkclean. (tests/exampleshas9 pre-existing
fixture 'solara_test' not founderrors, identical on main.)Added two regression tests covering what the deleted
cache_clear()call couldhave been protecting: that
connect()anddisconnect()invalidate a cell's owncached neighborhood, and that a
connect()one hop away invalidates a radius-2neighborhood 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:
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
Cellreferences pinned by the class-levelcaches, 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, sinceconnect()now clears one cache instead of two. That one is deterministic ratherthan a timing claim:
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
mesa/discrete_space/cell.py.get_neighborhood()and_neighborhood()usefunctools.cache, but_neighborhood()is only ever called throughget_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
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.cacheholds references to its arguments, includingself, and how a redundant cache can cost memory without giving anything back. TracingCell.get_neighborhood()andCell._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
functools.cachekeys results on arguments, and that caching a method keeps a reference toself, so objects can live longer than they should.What was harder than I expected
solara_testfixture, which went away once I installedsolara[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_spacerather than from a modelReadiness checks
pytest --cov=mesa tests/)ruff check . --fix)_neighborhoodis private and no public behaviour changesTest run:
pytest --cov=mesa tests/→ 861 passed, 1 failed, 86% coverage. The failure istests/experimental/test_actions.py::TestOnIdle::test_suppressed_wake_is_logged_at_debug, which ispre-existing: a clean
upstream/mainworktree gives 859 passed and the same single failure. It passesin 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.