mesa icon indicating copy to clipboard operation
mesa copied to clipboard

EventGenerator fires once after schedule.end when start is not set

Open RITVIKKAMASETTY opened this issue 2 weeks ago • 0 comments

Describe the bug When a recurring event is scheduled with a Schedule that sets end but leaves start as None, the generator can still fire once after end.

In EventGenerator.start(), the first event time defaults to model.time + interval, but it is never checked against schedule.end. Every later event is checked through _should_stop(), and resume() does the same check before scheduling. Only the first event in start() skips it, so if model.time + interval > end, the event fires anyway and the generator only deactivates afterwards.

Expected behavior If the first event would fall after end, the generator should not schedule it. It should end up inactive without firing, the same way resume() handles this case.

To Reproduce

from mesa import Model
from mesa.time import Schedule

class M(Model):
    def __init__(self):
        super().__init__(rng=1)
        self.calls = []

    def tick(self):
        self.calls.append(self.time)

m = M()
m.run_for(10)  # model.time == 10
gen = m.schedule_recurring(m.tick, Schedule(interval=5, end=12))
m.run_for(20)

print(m.calls)          # [15.0], expected []
print(gen.is_active)    # False

The callback runs at t=15, after the schedule's end of t=12.

Additional context This shows up when a recurring process is started partway through a run with an end time, for example a policy that runs every 5 steps until step 12 but is switched on at step 10. The model gets one extra execution outside the intended window, with no warning, which silently changes the results.

#3321 added validation for an explicit start > end in Schedule.__post_init__, but that doesn't cover this case, because start is computed later in EventGenerator.start().

A possible fix: in start(), call self._should_stop(start_time) before scheduling the first event, and if it returns True, leave the generator inactive (matching resume()). I'm happy to open a PR with this fix and a regression test.

  • Mesa: 4.0.0a0 (current main)
  • Python: 3.13

I thought of a possible fix and used ai to verify if my solution is correct

RITVIKKAMASETTY avatar Nov 13 '26 12:11 RITVIKKAMASETTY