Skip to content

Explain a full space instead of leaking IndexError from random.choice - #4026

Merged
quaquel merged 1 commit into
mesa:mainfrom
lahari936:fix-raw-indexerror-empty-space
Nov 2, 2026
Merged

quaquel merged 1 commit into
mesa:mainfrom
lahari936:fix-raw-indexerror-empty-space

Conversation

@lahari936

Copy link
Copy Markdown
Contributor

Pre-PR Checklist

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

Summary

select_random_empty_cell() on a full space tells you what went wrong on OrthogonalMooreGrid, OrthogonalVonNeumannGrid and HexGrid, and leaks a stdlib IndexError on Network and VoronoiGrid.

Bug / Issue

Grid.select_random_empty_cell (grid.py:322) wraps the failure:

except IndexError as e:
    raise ValueError(
        "Grid is completely full. No empty cells available. "
        "Cannot select a random empty cell."
    ) from e

DiscreteSpace.select_random_empty_cell (discrete_space.py:190), which Network and VoronoiGrid inherit unchanged, does not:

return self.random.choice(list(self.empties))

So the same call on a full space gives:

space on a full space
OrthogonalMooreGrid ValueError: Grid is completely full. No empty cells available.
OrthogonalVonNeumannGrid ValueError: Grid is completely full. ...
HexGrid ValueError: Grid is completely full. ...
Network IndexError: Cannot choose from an empty sequence
VoronoiGrid IndexError: Cannot choose from an empty sequence

The 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 a Network hits this the moment the last cell fills, which is exactly when a clear message matters.

Reproducer:

import networkx as nx
from mesa import Model
from mesa.discrete_space import CellAgent, Network

model = Model()
space = Network(nx.cycle_graph(4), random=model.random)
for cell in space.all_cells:
    CellAgent(model).cell = cell
space.select_random_empty_cell()
# IndexError: Cannot choose from an empty sequence

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 SpaceException with an actionable message. The list is materialised anyway, so this costs a len check and needs no try/except.

On the exception type: docs/development/standards.md says to use a MesaException subclass "when it adds domain context or hides internals" and to "pick the most specific existing one". The raw IndexError leaks an internal, namely that the lookup is a random.choice over a materialised list. SpaceException already exists for discrete-space errors, so no new type is introduced.

What this deliberately does not change

Grid.select_random_empty_cell still raises ValueError for the identical condition. Three reasons to leave it:

  1. It is a breaking change for anyone catching ValueError; SpaceException does not subclass it.
  2. It is pinned by test_infinite_loop_on_full_grid.
  3. In Moving an unplaced agent in discrete space raises raw AttributeError instead of ValueError #4001 @quaquel ruled that ValueError is the wrong type for methods that receive no value, and the thread settled on SpaceException for those cases, with @Dilraj07 already moving FixedAgent.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 over Network and VoronoiGrid, 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:

tests/discrete_space/            140 passed
pytest tests/ (less the playwright viz tests)   1014 passed
ruff check / ruff format         clean

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.

`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]>
Copilot AI balanced review requested due to automatic review settings November 1, 2026 02:33

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 insufficient remaining quota. Try requesting a review at a lower effort level.

@github-actions github-actions Bot added the testing Release notes label label Nov 1, 2026

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

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.

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.

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.

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)

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 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 "

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.

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():

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

@quaquel quaquel added the enhancement Release notes label label Nov 2, 2026
@quaquel
quaquel merged commit 106bec9 into mesa:main Nov 2, 2026
17 of 18 checks passed
quaquel pushed a commit that referenced this pull request Nov 4, 2026
…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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants