rejected actions can leave an agent busy or interrupt its current action
#3805 was merged, but this case from its additional notes is still reproducible on main, so it isn't fully fixed yet. i'd like to work on it.
Describe the bug
the additional notes in #3805 already mention that an invalid incoming action can interrupt the current action before raising. that follow-up is still reproducible on main after #3805 was merged.
there is also an idle-agent case: HasActions.start_action() sets current_action before lifecycle and duration validation in Action.start(). a completed action or negative callable duration raises but leaves the slot occupied, so a valid follow-up is rejected.
with interrupt_for(), an incoming action belonging to another agent raises ValueError, but only after the current action has been interrupted and its completion event cancelled.
Expected behavior
rejecting an action for invalid ownership, lifecycle state or duration should leave an idle agent usable, or keep its current action running. this is separate from a failed start requirement, which is documented to leave the old action interrupted.
To Reproduce
from mesa import Agent, Model
from mesa.experimental.actions import Action, HasActions
class Worker(HasActions, Agent):
pass
model = Model(rng=42)
worker = Worker(model)
bad = Action(worker, duration=lambda agent: -1)
try:
worker.start_action(bad)
except ValueError:
pass
print(worker.is_busy, bad.state.name) # True PENDING
try:
worker.start_action(Action(worker, duration=1))
except ValueError as error:
print(error) # already performing an action
model = Model(rng=42)
worker = Worker(model)
other = Worker(model)
active = Action(worker, duration=5)
worker.start_action(active)
try:
worker.interrupt_for(Action(other, duration=1))
except ValueError:
pass
model.run_until(5)
print(active.state.name) # INTERRUPTED, not COMPLETED
Additional context
related tracking issue: #3798. this is a follow-up to the known limitation in #3805, not a new preemption feature. the examples reproduce on main at f6f7e53f261adc2f2ab1d230e6327a52bec7cb1e, with Python 3.13.
i'd like to work on this if nobody has started the follow-up from #3805. the plan is to validate ownership, lifecycle state and duration before changing the slot or interrupting the current action, with regression tests for both paths. could this be assigned to me?
Thanks and Yes, the interrupt_for half is known.
The start_action case is new though, and it is the worse of the two. The agent ends up holding a PENDING action and stays busy for the rest of the run, so every later start is rejected, whereas the interrupt_for one at least leaves it idle. Good catch, and thanks for separating it from the start requirement behaviour, that distinction matters.
Two things before you write code, because this is less mechanical than it looks.
The obvious fix, calling action.start() first and assigning current_action only once it succeeds, breaks instantaneous actions. A duration=0 action completes inside start(), so _release_agent() checks agent.current_action is self, finds the slot still empty and leaves it alone. The slot is then filled with an already COMPLETED action and the agent is stuck busy, which is worse than the bug. So validation has to come out of start(), the two statements cannot just be swapped.
Also duration is resolved exactly once today, inside start(). You cannot check the sign without invoking the callable, so validating early needs the same treatment priority got in #3805, a resolve once helper, otherwise a user's duration callable runs twice.
Let me settle how the validation should be split first, since it touches the lifecycle contract from #3801 and #3805. Meanwhile could you please hold off on opening a PR until then?
thanks @codebreaker32. #4063 was already opened earlier today. it keeps the slot assignment before start(), and duration still resolves in start() rather than being checked twice. it only checks ownership/state before interruption and clears the slot if startup raises before activation; duration errors after interruption are left outside its scope. i'll hold further changes while the validation split is settled. would you prefer the existing PR kept as a draft or closed for now?
Thanks for looking into this.
bad = Action(worker, duration=lambda agent: -1) try: worker.start_action(bad) except ValueError: pass print(worker.is_busy, bad.state.name) # True PENDING
This is clearly a bug and should be prevented by start_action I think
active = Action(worker, duration=5) worker.start_action(active) try: worker.interrupt_for(Action(other, duration=1)) except ValueError: pass model.run_until(5) print(active.state.name) # INTERRUPTED, not COMPLETED
It will only complete at duration 6, right? 1 waiting + 5 doing?
The sate should probably be updated somewhere in the process.
@EwoutH thanks, agreed on the start_action bug. in the second example, the incoming action belongs to another agent, so it raises before that 1-unit action starts. the old action's completion event has already been cancelled, and it stays INTERRUPTED at t=6 too unless explicitly resumed.
#4063 is already open and covers these two cases. i'll keep further changes on hold until the validation split with @codebreaker32 is settled.
Sounds good @atul-upadhyay-7 no need to close #4063. I will review it there.
I looked at this more broadly, and I think both cases here are symptoms of one underlying problem: the agent's slot and the action's state are two separate records of the same fact, and both HasActions and Action write to them by hand. The rule that should always hold is:
agent.current_action is aif and only ifa.state is ACTIVE
Nothing enforces that today. start_action and remove() fill or clear the slot from the agent side, Action._release_agent clears it from the action side, and _release_agent explicitly tolerates actions that never held the slot. On current main the rule breaks in (at least) four ways:
| # | How | Result |
|---|---|---|
| 1 | action.start() called directly (it's public) |
Action is ACTIVE but not in the slot; the agent can start a second action, so two run at once |
| 2 | on_start() raises |
Action is ACTIVE with no completion event; it never ends and the agent stays busy for good |
| 3 | start() raises before activating (this issue) |
A PENDING action sits in the slot; the agent stays busy for good |
| 4 | agent.current_action = x |
Any action in any state can be put in the slot |
Reproducer
from mesa import Agent, Model
from mesa.experimental.actions import Action, HasActions
class W(HasActions, Agent):
pass
# 1. direct start(): action runs outside the slot, agent can run a second one
m = Model(rng=1); w = W(m)
a = Action(w, duration=5).start()
b = w.start_action(Action(w, duration=5))
print(a.state.name, b.state.name) # ACTIVE ACTIVE
# 2. on_start raises: ACTIVE, no event, stuck
class Boom(Action):
def on_start(self):
raise RuntimeError
m = Model(rng=1); w = W(m); x = Boom(w, duration=2)
try:
w.start_action(x)
except RuntimeError:
pass
m.run_until(10)
print(x.state.name, x._event, w.is_busy) # ACTIVE None True
# 4. the slot can be assigned directly
m = Model(rng=1); w = W(m)
w.current_action = Action(w, duration=1)
print(w.is_busy) # True, with a PENDING action
So instead of rolling back after the fact, I'd fix it at the root:
- Validate first, then claim the slot when the action becomes ACTIVE.
start()becomes: validate (state, ownership, agent not busy) → check start requirements → resolve → claim the slot and set ACTIVE →on_start/on_resume→ schedule the completion event, or complete synchronously forduration=0as today.start_actionbecomes a thin wrapper. This fixes 1 and 3, and also handles theduration=0concern raised above: the slot is claimed before_do_completeruns, so_release_agentfinds it and clears it. - Wake explicitly on a failed start. Since the slot is no longer held when a start requirement fails,
start()schedules the wake itself after_fail()rather than relying on_release_agent. (Not in_fail(), since that also runs on completion, when the slot is held.) Because the busy check runs before the requirements, a failed start only happens on an idle agent, so the wake is always correct. (Claiming before the requirement check would bring back case 3 whenever a requirement predicate raises.) - Validate before interrupting. A resolve-once helper for duration, as #3805 added for priority, lets
interrupt_forcheck ownership, state and duration before interrupting the current action. That covers theinterrupt_forhalf of this issue. A failed start requirement after the interruption would still leave the agent idle, as currently documented, sinceon_interruptmay change the state that requirement depends on.
Case 2 (a hook raising) is out of scope for now. It only matters when user code catches the exception and carries on, and it can't be guaranteed for instant actions without changing when they complete.
Making current_action a read-only property (4) is related but separate. It ties into the open slot cardinality decision in #3798, so I'd handle it there rather than in this issue.
@codebreaker32 since this changes the lifecycle contract from #3801 and #3805, does this direction work for you? If so, I'd suggest implementing it as two small PRs: first 1+2, then 3. @atul-upadhyay-7 if you'd like to take this on, #4063 could be reworked into the first one.
Edit: revised after @atul-upadhyay-7's comment below: added the explicit wake on a failed start, kept duration=0 synchronous, and dropped the earlier "hooks run last" rule. Later: the wake on a failed start moved from _fail() to start(), matching #4111.
+1 on the direction. two things i hit when trying rules 1+2 locally: (1) a failed start requirement wakes the agent via _release_agent, which only fires if the slot is held, so if start() claims the slot after the requirement check, on_idle no longer fires after a failed start (test_wake_fires_for_start_failure breaks). so either claim before the requirement check or have _fail() wake explicitly. (2) with hooks last, duration=0 should run on_start and then _do_complete, instead of scheduling at 0, so the instant case stays instant.
@codebreaker32 when you get a moment, could you look at the two points above (failed-start wake and duration=0)? they affect how the first step gets shaped.
@atul-upadhyay-7 good catches, both are right. I updated the proposal above:
- For the failed-start wake I'd go with an explicit wake in
_fail(), with the busy check before the requirement check. Claiming the slot before the requirement check would leave a PENDING action in the slot again if a requirement predicate raises. - Agreed that
duration=0should stay synchronous. That also means "hooks run last" can't hold for instant actions, so I dropped it. A hook raising is out of scope for this issue.
thanks, that covers both. i'd like to take the first step (claim the slot in start(), explicit wake in _fail()). i'll rework #4063 into it once codebreaker32 is ok with the direction.
I opened draft PRs for both while my Claude Code cache was still warm. I also wanted to try GitHub new stacked PRs. I added you as co-author for #4111.
You can review both already if you want, while we'll see if @codebreaker32 agrees on this direction.
Yes, the direction works for me. Claiming the slot when the action goes ACTIVE takes care of both things I was worried about. Will try to review both PRs in detail