Skip to content

perf:lazy KDTree rebuild + tests - #3701

Merged
quaquel merged 4 commits into
mesa:mainfrom
Krishsharma179:fix-kdtree
Apr 10, 2026
Merged

quaquel merged 4 commits into
mesa:mainfrom
Krishsharma179:fix-kdtree

Conversation

@Krishsharma179

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

Primary: fixes stale/redundant rebuild behavior in remove_cell .
Secondary: lazy rebuild is the implementation strategy to avoid repeated unnecessary rebuilds.

Fixes a stale/redundant KDTree rebuild issue in NetworkGrid where remove_cell() could trigger an eager rebuild on outdated _kdtree_cells data. As part of the fix, KDTree rebuilds are now deferred (lazy) until find_nearest_cell() is actually called, eliminating redundant work during bulk mutations.

Bug / Issue

#3700 In the previous implementation, add_cell() and remove_cell() both triggered eager KDTree rebuilds. In remove_cell(), this could result in a rebuild on stale or already-modified _kdtree_cells data, causing a double/redundant rebuild.

Implementation

1.Added self._kdtree_dirty = False flag in __init__.
2._rebuild_kdtree() now resets _kdtree_dirty = False after every rebuild.
3.remove_cell(): Removes from _kdtree_cells and sets _kdtree_dirty = True. Eager rebuild removed, eliminating the previous stale/redundant rebuild on already-modified _kdtree_cells data.
4.add_cell(): For spatial cells, appends to _kdtree_cells and sets _kdtree_dirty = True .
5.find_nearest_cell() checks the dirty flag and triggers a rebuild on demand before querying.

Testing

tests/discrete_space/test_spatial_lookups.py
Three new tests added using unittest.mock.patch.object(..., wraps=...) to spy on _rebuild_kdtree call count:

test_network_lazy_rebuild_deferred_until_query verifies no rebuild occurs during mutation-only phase; rebuild triggered only on firstfind_nearest_cell( call.
test_network_lazy_rebuild_batches_mutations_to_single_rebuild verifies multiple mutations result in exactly one rebuild on query, not one per mutation.
test_network_non_spatial_cell_mutation_does_not_dirty_kdtree verifies that adding/removing non-spatial cells does not set the dirty flag or trigger any rebuild

Additional Notes

This change is purely a fix to rebuild timing. No public API changes. Graph topology updates remain eager and unaffected. The lazy rebuild is an internal optimization that emerges naturally from fixing the stale rebuild path in remove_cell().

@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 -0.1% [-0.5%, +0.3%] 🔵 +0.7% [+0.5%, +1.0%]
BoltzmannWealth large 🔵 -0.3% [-0.7%, +0.1%] 🔵 +0.6% [+0.1%, +1.1%]
Schelling small 🔵 +2.2% [+1.8%, +2.6%] 🔵 +0.6% [-0.1%, +1.3%]
Schelling large 🔵 +0.9% [+0.3%, +1.5%] 🔵 +0.0% [-0.6%, +0.7%]
WolfSheep small 🔵 -0.7% [-1.2%, -0.3%] 🔵 +1.4% [-3.3%, +6.2%]
WolfSheep large 🔵 +1.1% [+0.2%, +1.8%] 🔵 -0.7% [-1.7%, +0.2%]
SugarscapeG1mt small 🔵 +0.9% [+0.5%, +1.2%] 🔵 -0.6% [-2.1%, +0.9%]
SugarscapeG1mt large 🔵 +0.2% [-0.3%, +0.7%] 🔵 -0.6% [-2.2%, +1.1%]
BoidFlockers small 🔵 +0.1% [-0.2%, +0.3%] 🔵 -0.5% [-0.9%, -0.2%]
BoidFlockers large 🔵 -0.3% [-0.6%, +0.0%] 🔵 -0.8% [-1.0%, -0.5%]

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

This is the self review of my PR It Introduces lazy KDTree rebuild via _kdtree_dirty flag. Removes eager _rebuild_kdtree() calls from add_cell() and remove_cell() , fixing stale rebuild risk in the remove flow. Rebuild now deferred until find_nearest_cell() is called. Three new tests added. All 14 CI checks passin

Comment on lines 157 to 165
def remove_cell(self, cell: Cell):
"""Remove a cell from the space."""
super().remove_cell(cell)
self.G.remove_node(cell.coordinate)
self._rebuild_kdtree()

if cell._position is not None:
if cell._position is not None and cell in self._kdtree_cells:
self._kdtree_cells.remove(cell)
self._rebuild_kdtree()
self._kdtree_dirty = True

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.

Removed the eager self._rebuild_kdtree() call here. Previously, _rebuild_kdtree() was called before removing the cell from _kdtree_cells, causing it to rebuild on stale data. Now we mark _kdtree_dirty = True and defer the rebuild until find_nearest_cell() is actually called.

Comment on lines +138 to +141

if self._kdtree_dirty:
self._rebuild_kdtree()

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.

This is the core of the lazy rebuild strategy. Instead of rebuilding KDTree on every add_cell() or remove_cell() , we defer the rebuild here only when find_nearest_cell() is actually called and _kdtree_dirty is True. This ensures at most one rebuild per query, regardless of how many mutations happened before it.

)

self._kdtree_cells = []
self._kdtree_dirty = False # True when KDTree needs a rebuild.

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.

Dirty flag initialized as False at construction no mutations have occurred yet. Set to True on any spatial add_cell() or remove_cell() call, and reset to False after _rebuild_kdtree() completes.

self._kdtree = KDTree(positions)
else:
self._kdtree = None
self._kdtree_dirty = False # set to false after rebuilding every time

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.

_kdtree_dirty reset to False after rebuild completes, so subsequent calls to find_nearest_cell() skip the rebuild until the next mutation occur

@EwoutH
EwoutH requested a review from codebreaker32 April 10, 2026 13:26

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thanks for this optimisation. LGTM!

@Krishsharma179

Copy link
Copy Markdown
Contributor Author

@codebreaker32 Thank you for the review!

@quaquel quaquel added the performance Release notes label label Apr 10, 2026
@quaquel
quaquel merged commit 5312e71 into mesa:main Apr 10, 2026
12 checks passed
EwoutH pushed a commit that referenced this pull request Oct 28, 2026
@EwoutH EwoutH mentioned this pull request Nov 15, 2026
53 of 65 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants