Repository navigation
Explain a full space instead of leaking IndexError from random.choice - #4026
Conversation
`Grid.select_random_empty_cell` catches the `IndexError` from
`random.choice` on a full grid and re-raises it with a message naming the
real problem. `DiscreteSpace.select_random_empty_cell`, which `Network` and
`VoronoiGrid` inherit unchanged, does not:
return self.random.choice(list(self.empties))
On a full space that surfaces the stdlib
IndexError: Cannot choose from an empty sequence
from inside `random.py`, which says nothing about the space being full and
points at a line the user never wrote. A Schelling-style model moving agents
on a `Network` hits this as soon as the last cell fills.
Guard the empty case and raise `SpaceException` with an actionable message.
The list is materialised anyway, so the check costs a `len` and replaces the
try/except the grid path needs.
`SpaceException` rather than a built-in because the raw `IndexError` leaks an
internal (that the lookup is a `random.choice` over a materialised list) and
`mesa/exceptions.py` already carries `SpaceException` for discrete-space
errors, which is what `docs/development/standards.md` asks for. No new
exception type is added.
Deliberately not touching `Grid.select_random_empty_cell`, which raises
`ValueError` for the same condition. Changing it is a breaking change, it is
pinned by `test_infinite_loop_on_full_grid`, and in mesa#4001 @quaquel ruled that
`ValueError` is wrong for methods that receive no value, with the outcome
there being to move such cases to `SpaceException`. Aligning the grid path
belongs with that migration, not here.
Tests cover `Network` and `VoronoiGrid` on a full space, and a space with one
cell left so the guard cannot fire early. Both new cases fail on main with
the stdlib `IndexError`.
Co-Authored-By: Claude Opus 5 <[email protected]>
lahari936
left a comment
There was a problem hiding this comment.
Self-review. Walked the diff as a reviewer and left notes on the four decisions that are not obvious from the code, plus one on the second test. The open question for you is on the Raises: block: this leaves the base class and Grid raising different types for the same condition, and I would rather you tell me which way to resolve it than guess.
| from mesa.discrete_space.cell import Cell | ||
| from mesa.discrete_space.cell_collection import CellCollection | ||
| from mesa.exceptions import CellMissingException | ||
| from mesa.exceptions import CellMissingException, SpaceException |
There was a problem hiding this comment.
Chose SpaceException over a built-in here. docs/development/standards.md says to use the most fitting built-in for ordinary validation, and a MesaException subclass only when it "adds domain context or hides internals". This is the second case: the raw IndexError leaks the fact that the lookup is a random.choice over a materialised list, which is an implementation detail the caller should not have to know. SpaceException already exists in mesa/exceptions.py as the base for discrete-space errors, so no new type is introduced.
| """Select random empty cell. | ||
|
|
||
| Raises: | ||
| SpaceException: if the space holds no empty cell. |
There was a problem hiding this comment.
Added because the method now has a documented failure mode.
Worth flagging for review rather than hiding: after this change the base class and Grid.select_random_empty_cell raise different types for the identical condition, SpaceException here and ValueError there. I left that gap open deliberately, for the three reasons in the PR description, the main one being that in #4001 you ruled ValueError is wrong for a method that receives no value and that thread is already moving such cases to SpaceException.
If you would rather not merge an inconsistency even temporarily, say so and I will bring the grid path over in this PR, with the test_infinite_loop_on_full_grid assertion updated and a migration guide entry for the breaking change.
| SpaceException: if the space holds no empty cell. | ||
|
|
||
| """ | ||
| empties = list(self.empties) |
There was a problem hiding this comment.
The original line was self.random.choice(list(self.empties)), so the list was already being materialised. Checking it costs a len and nothing more.
I used an explicit guard rather than mirroring the try/except IndexError that Grid.select_random_empty_cell uses, because the grid path cannot avoid the try: it calls random.choice on a numpy array from np.flatnonzero and has no cheap emptiness check at that point. Here the list is already in hand, so the guard reads more directly than catching an exception we can see coming.
| empties = list(self.empties) | ||
| if not empties: | ||
| raise SpaceException( | ||
| f"{type(self).__name__} is completely full. No empty cells " |
There was a problem hiding this comment.
type(self).__name__ rather than a fixed word, because this method serves Network, VoronoiGrid and anything else subclassing DiscreteSpace without overriding it. The grid path hardcodes "Grid" since it only ever runs on grids.
The wording is deliberately close to the grid message so the two read as the same error. That matters more than usual while the exception types still differ.
| space.select_random_empty_cell() | ||
|
|
||
|
|
||
| def test_select_random_empty_cell_still_works_when_space_has_room(): |
There was a problem hiding this comment.
This second test exists because the first one alone would still pass if the guard were wrong in the other direction, for example an inverted condition or a truthiness bug on CellCollection. It asserts the identity of the one remaining cell, so it fails if the guard fires early or if the wrong cell comes back.
Both new tests were checked against current main before the fix was written: they fail there with IndexError: Cannot choose from an empty sequence.
…grid (#4032) * Raise SpaceException when Grid.select_random_empty_cell finds a full grid Grid overrides select_random_empty_cell and still raised ValueError on a full grid, while DiscreteSpace (Network, VoronoiGrid) raises SpaceException since #4026. Raise SpaceException from Grid too, with the same message, and add a Mesa 4.0 migration guide entry. * Link the migration guide entry to its PR
Pre-PR Checklist
Summary
select_random_empty_cell()on a full space tells you what went wrong onOrthogonalMooreGrid,OrthogonalVonNeumannGridandHexGrid, and leaks a stdlibIndexErroronNetworkandVoronoiGrid.Bug / Issue
Grid.select_random_empty_cell(grid.py:322) wraps the failure:DiscreteSpace.select_random_empty_cell(discrete_space.py:190), whichNetworkandVoronoiGridinherit unchanged, does not:So the same call on a full space gives:
ValueError: Grid is completely full. No empty cells available.ValueError: Grid is completely full. ...ValueError: Grid is completely full. ...IndexError: Cannot choose from an empty sequenceIndexError: Cannot choose from an empty sequenceThe traceback points into
C:\Python314\Lib\random.py:353, a line the user never wrote, and the message never mentions the space. A Schelling-style model relocating agents on aNetworkhits this the moment the last cell fills, which is exactly when a clear message matters.Reproducer:
I found this by running the same probes across all five space types and diffing the results; this was the only behaviour where they disagreed.
Implementation
Guard the empty case in the base method and raise
SpaceExceptionwith an actionable message. The list is materialised anyway, so this costs alencheck and needs no try/except.On the exception type:
docs/development/standards.mdsays to use aMesaExceptionsubclass "when it adds domain context or hides internals" and to "pick the most specific existing one". The rawIndexErrorleaks an internal, namely that the lookup is arandom.choiceover a materialised list.SpaceExceptionalready exists for discrete-space errors, so no new type is introduced.What this deliberately does not change
Grid.select_random_empty_cellstill raisesValueErrorfor the identical condition. Three reasons to leave it:ValueError;SpaceExceptiondoes not subclass it.test_infinite_loop_on_full_grid.ValueErroris the wrong type for methods that receive no value, and the thread settled onSpaceExceptionfor those cases, with @Dilraj07 already movingFixedAgent.remove()over.select_random_empty_cell()takes no argument either, so the grid path belongs in that migration rather than in this PR.Happy to fold the grid path in here instead if you would rather have both move together.
Testing
Two new tests in
tests/discrete_space/test_discrete_space.py:test_select_random_empty_cell_on_full_space_raises, parametrised overNetworkandVoronoiGrid, asserting type and message.test_select_random_empty_cell_still_works_when_space_has_room, so the guard cannot fire while a cell is free.Both new cases fail on current main with the stdlib
IndexError. Results:The one unrelated failure in the full run,
test_actions.py::TestOnIdle::test_suppressed_wake_is_logged_at_debug, is pre-existing and tracked in #3935.Additional Notes
AI assistance was used for the differential probing that surfaced this, and for drafting. The behaviour, the reproducer and the test results above were all run and checked locally.