mesa icon indicating copy to clipboard operation
mesa copied to clipboard

EventList: adding one Event twice corrupts the canceled count, so len(), is_empty() and pop_event() disagree

Open lahari936 opened this issue 1 month ago • 0 comments

Describe the bug

Adding the same Event object twice to the same EventList puts one object in several heap slots. Event.cancel() is idempotent, so it increments _n_canceled once, while pop_event() decrements it once per tombstone it discards. The two counts drift, and len(), is_empty() and pop_event() stop agreeing with each other.

To Reproduce

from mesa.time.events import Event, EventList, Priority


def noop():
    pass


event_list = EventList()
events = [Event(float(i), noop, Priority.DEFAULT) for i in range(4)]
for event in events:
    event_list.add_event(event)
event_list.add_event(events[0])        # the only unusual step

print("heap entries :", len(event_list._events))
events[0].cancel()
live = sum(1 for e in event_list._events if not e.CANCELED)
print(f"after cancel  : len()={len(event_list)}  actually live={live}  _n_canceled={event_list._n_canceled}")

popped = 0
while not event_list.is_empty():
    try:
        event_list.pop_event()
        popped += 1
    except IndexError as exc:
        print(f"  IndexError after {popped} pops, while is_empty() said {event_list.is_empty()}")
        break
print(f"  len()={len(event_list)}  _n_canceled={event_list._n_canceled}")

On current main (949dc8c5):

heap entries : 5
after cancel  : len()=4  actually live=3  _n_canceled=1
  IndexError after 3 pops, while is_empty() said False
  len()=1  _n_canceled=-1

Three consequences, escalating

  1. len() overcounts by the number of extra slots.
  2. pop_event() raises IndexError while is_empty() returns False, which breaks the ordinary while not event_list.is_empty(): event_list.pop_event() drain loop.
  3. _n_canceled ends up negative and stays negative. Since compaction triggers on self._n_canceled > len(self._events) * self.COMPACTION_RATIO, a negative count can never exceed the threshold, so the heap-growth protection the class is built around is silently switched off for the rest of the run.

Worth knowing: the small case does not reproduce

With two events, cancelling one trips the compaction threshold, which clears both tombstones and hides the problem. It needs four or more events on the heap, which is the normal case in a real model, so a minimal two-event test reports "works fine".

How I found it

Random operation sequences (add, cancel, pop, compact, clear, re-add) with an assertion after every operation that len() equals the live events actually on the heap, that _n_canceled >= 0, and that is_empty() matches reality. Every violation involved re-adding an event that was still queued.

Expected behavior

len(), is_empty() and pop_event() should stay consistent, and the canceled total should never go negative.

Additional context

Mesa 4.0.0a0 at 949dc8c5. The class documents the related two-list case in its Notes — "An event belongs to one event list at a time. Adding the same event to a second list hands ownership over, and the first list's count goes stale" — but says nothing about adding to the same list twice, which fails silently and corruptingly rather than loudly.

I have a fix and tests ready: refuse the duplicate in add_event, the same way it already refuses a canceled event, while leaving the documented ownership transfer and re-adding after pop_event() working. Happy to open it if this reads as a bug worth guarding rather than caller error to be documented.

lahari936 avatar Oct 23 '26 07:10 lahari936