Repository navigation
Rework the action lifecycle: final cancel, completion wins, on_progress/on_stop, removal - #4172
Conversation
bf3a5b0 to
1fec52c
Compare
|
Thanks @EwoutH for documenting the lifecycle contract and its migration examples. #4173 is now merged, while this diff still includes its completion and scheduling changes alongside the fixes in #4112 and #4121. @quaquel, should the remaining contract proceed here after #4171? I recommend that route, reconciling the merged work and preserving the smaller fixes’ regression cases, with #4176 following separately. The 12 cancelled checks also need successful runs before merging. Automated note by an AI model; it can be wrong, and maintainers make the decisions. About this bot. |
|
there's a progress double-count inside on_progress when an attempt is interrupted. _freeze_progress() stores the live value in _progress while the action is still ACTIVE, so reading self.progress in the hook adds the same elapsed time again. for a duration-10 action interrupted at t=2, the hook gets delta=0.2 but self.progress is 0.4. cancel() and agent.remove() take the same path. this also makes the nonlinear payment formula from #4120 overpay. from mesa import Agent, Model
from mesa.experimental.actions import Action, HasActions
class Worker(HasActions, Agent):
pass
class Work(Action):
def on_progress(self, delta):
print(delta, self.progress)
model = Model(rng=1)
worker = Worker(model)
action = worker.start_action(Work(worker, duration=10))
model.run_for(2)
action.interrupt() # 0.2 0.4, expected 0.2 0.2could the frozen progress stay consistent while the hook runs, with a regression that reads progress from inside on_progress? |
7d11283 to
130af20
Compare
|
@atul-upadhyay-7 good catch, reproduced and fixed in 130af20: freezing now also restarts the attempt clock, so |
atul-upadhyay-7
left a comment
There was a problem hiding this comment.
checked 130af20 with the original example. progress inside on_progress now matches the reported delta for interrupt, cancel and removal. the action, scheduler and model tests pass locally, and the checks are green. lgtm
codebreaker32
left a comment
There was a problem hiding this comment.
Thanks, this resolves my points from #4120.
|
i reproduced the pickling issue with a HasActions + HasEmitters agent that has a bound-method subscriber. pickle and deepcopy work on current main, but both raise TypeError with this branch's actions.py. both saving and restoring need to preserve the other mixin's state handling. for the instant action, i get on_complete at duration=0 and on_cancel at duration=1e-9. the pr body and test explicitly choose the zero-duration behavior, so this looks like a contract decision rather than an accidental regression. should cancellation from the action's own start/resume hook be an exception to completion-wins? |
cancel() now ends an action for good, in the new CANCELED state, and fires on_cancel(). The old resumable cancel is interrupt(force=True). An INTERRUPTED action continues with resume(); start() is private and agents start PENDING actions with start_action(). state and current_action are read-only. interrupt_for() validates the new action before interrupting, takes a PENDING or INTERRUPTED action, returns True without changes for the current action, and asks whether the slot is free afterwards rather than what interrupt() returned. Resolved durations must be finite and >= 0, priorities not NaN. Supersedes #4112. Refs #4120 Assisted-by: Claude Opus 5.5
Each attempt now has a deadline. interrupt(), cancel() and interrupt_for() complete an action that has reached it instead of interrupting it, so an interrupt at the completion time no longer leaves a resumable action that pays twice. progress is exactly 1.0 from the deadline on. The completion event is scheduled before on_start()/on_resume() run, so a hook that interrupts, cancels or resumes its own action goes through the normal methods and leaves no stale completion behind. Supersedes #4121; its tests are carried over. Refs #4120 Co-authored-by: atul-upadhyay-7 <[email protected]> Assisted-by: Claude Opus 5.5
Partial credit moves from on_interrupt(progress) to on_progress(delta), which reports the work done since the last report, so an action that is interrupted and resumed pays exactly what one run pays. on_stop() fires once at every attempt end, after the completion requirements are checked, so what on_start() acquires is released in one place. on_interrupt() loses its argument. Lifecycle calls for the same agent raise RuntimeError inside on_progress(), on_stop() and the decision callables. The module docstring documents the hook order, the ways to model work and the completion-wins and one-wake-per-time policies. Refs #4120 Assisted-by: Claude Opus 5.5
remove() used to abandon an active action without any hook, leaving it ACTIVE forever. It now closes the agent, cancels the active action with on_progress(), on_stop() and on_cancel(), and cancels every interrupted action it started that is still referenced, in start order. Removal never completes an action and queues no wake. The agent tracks the actions it started weakly, so an interrupted action the model dropped isn't kept alive; pickling still works. Refs #4120 Assisted-by: Claude Opus 5.5
The module docstring keeps the hook rule and the ways to model work; the hook list and policies are in the hook docstrings and the decisions log. Started actions are keyed by id, the pickling hooks only handle a dict state, and the attempt check after on_start, which never decided anything, is gone. Tests covered elsewhere are removed. Assisted-by: Claude Opus 5.5
_freeze_progress() stored the live progress while the action was still ACTIVE, so the progress property added the attempt's elapsed time a second time while on_progress() ran on interrupt, cancel or removal. Restart the attempt clock when freezing. Assisted-by: Claude Code
130af20 to
e7a6971
Compare
HasActions copied __dict__ in __getstate__, so the hooks of another mixin such as HasEmitters were skipped, and with HasEmitters first its __setstate__ skipped ours. The tracking dict now pickles and deep-copies itself, so HasActions needs neither hook. Assisted-by: Claude Code
Assisted-by: Claude Code
|
@atul-upadhyay-7 thanks for reproducing both. The pickling issue is fixed in 53a00ef, for both mixin orders (details in the review thread). For the instant action I kept completion wins for now and replied in the thread; happy to hear your view there. |
Replace the "pay" wording in the actions docstrings and tests with what it means: applying the action's effect. Assisted-by: Claude Code
Assisted-by: Claude Code
|
thanks, the pickling fix works in both mixin orders now, with pickle and deepcopy. i also checked the subscriber still works after the copy. on the instant action, i'd keep completion-wins for now. the action is already at its deadline, and start_requirements cover refusing entry. canceling from on_start does mean on_complete can run before on_start returns, though, so that part is worth stating clearly. if a model needs to abort after trying to acquire something in on_start, that would be a concrete reason to revisit the exception. |
quaquel
left a comment
There was a problem hiding this comment.
A few clarifying questions at the docstring level. I don't fully comprehend the code at face value. I would need to work true it locally for that. I am fine with merging this once @codebreaker32 is also happy with it.
|
Thanks for all the reviews. @codebreaker32 your comment on ending an instant action is the final one unresolved, let me know what you think. Everyone fully happy with the API and behavior? |
|
@codebreaker32 would love your (final) review |
codebreaker32
left a comment
There was a problem hiding this comment.
Thanks for this and LGTM with some docstring suggestions
Assisted-by: Claude Opus 5.5
Merge main, which brings the action lifecycle rework (mesa#4172). The module docstring conflict resolves to main's version, which already drops the double-paying on_interrupt example; the HasActions example from this branch is kept. Tutorial updates for mesa#4172: - Resume with resuming.resume(); start_action() now only starts a PENDING action and raised ValueError in the thirsty-sheep example. - is_resumable means INTERRUPTED, and resume() on a final action raises. - List the current hooks, including on_progress, on_stop and on_cancel. Review fixes: - interrupt_for() leaves the new action in current_action, it doesn't clear it. - The recipe resumes the remaining third, not 20%. - Drop the CellAgent sentence, which has Agent first. - INTERRUPTED isn't final, and on_idle doesn't fire when interrupt_for() refills the slot. - Rename "Interruption, Priority and Resumption" and point to the recipe. - State that the tutorial needs Mesa 4.0, or main until it's released.
Pre-PR Checklist
Approval Link
#4120: the opening post is the spec. The shared vocabulary, a final
cancel(), no publicstart()and bool returns were agreed there (@quaquel, @codebreaker32). Defining "completion wins" on time came from @codebreaker32 and @atul-upadhyay-7, andon_progress(delta)with a delta only from @codebreaker32.Summary
Implements the actions part of #4120 (section 3) as one contract: a final
cancel(), separateinterrupt()/resume(), completion wins on time,on_progress(delta)andon_stop(), re-entry guards, and removal that cancels an agent's actions with their hooks. It sits between #4171 (dropped-wake warning, below) and #4176 (randomized invariant test, above).The four commits follow the spec's sections and can be reviewed one at a time: vocabulary and state, completion wins and scheduling, hooks and guards, removal. Or read the final
actions.pyagainst the spec.Motive
All of these reproduce on
main(section 1 of #4120):start()still schedules the completion (Don't schedule a completion for an action its own hook ended #4121), and a hook that interrupts and resumes its own action leaves two completion events.stateandcurrent_actioncan be assigned freely.Implementation
Vocabulary and state
ActionState.CANCELEDandon_cancel().cancel()is final from ACTIVE, INTERRUPTED and PENDING, and ignoresinterruptible. The old resumable cancel isinterrupt(force=True);agent.cancel_action()is final too, andagent.interrupt_action(*, force=False)is new.resume()continues an INTERRUPTED action.start()is private;agent.start_action()only takes PENDING actions.stateandcurrent_actionare read-only.is_resumableisstate is INTERRUPTED.interrupt_for()follows section 3.3: ownership and state are checked before anything changes (supersedes Check the new action's agent and state before interrupting the current one #4112), an INTERRUPTEDnew_actionis resumed, passing the current action is a no-op returning True, and afterwards it asks whether the slot is free, not whatinterrupt()returned. Hooks that startnew_action, fill the slot, remove the agent or endnew_actionare accounted for.Completion wins on time
interrupt(),cancel()andinterrupt_for()complete an action whose deadline has been reached, checked beforeinterruptible, so a due action never blocks its successor.progressis exactly 1.0 from the deadline on; accumulated progress can sit at 0.9999999999999999 there (duration=7, interrupts at 0.7 and 1.4), and a test pins that case.on_start()/on_resume(), so a hook that interrupts, cancels or resumes its own action goes through the normal methods. A zero-duration action completes after the hook only if it is still ACTIVE.Hooks and guards
on_progress(delta)fires when an attempt ends with work done, while still ACTIVE and before the completion requirements are checked; the deltas add up toprogress.on_stop()fires once at every attempt end, after the check, in the new state.on_interrupt()loses its argument. Every exit fires its hooks in the order of section 3.5.RuntimeErrorinsideon_progress(),on_stop()and the decision callables (requirements, duration, priority,should_interrupt()).Removal
remove()closes the agent (no new attempts, no wakes), cancels a pending wake, cancels an ACTIVE action withon_progress,on_stop,on_cancel(never completing it, even when due), then cancels every INTERRUPTED action it started that is still referenced, in start order. Hooks run while the agent is still in the model.WeakValueDictionarykeyed by id, in start order, so a dropped interrupted action isn't kept alive. Models with action agents pickle onmain, and a weak mapping can't be pickled, soHasActionsgets__getstate__/__setstate__; the spec didn't cover this.docs/development/decisions.mdgets an "API design" section: the shared vocabulary, completion wins, and one wake per time.Usage Examples
Interrupt and resume; the partial credit adds up to one full payment:
Cancel is final:
Preempt, then come back from
on_idle:Completion wins: at t=10, before the completion event of a duration-10 action:
Removing an agent cancels what it started, so a reservation held through an interruption is released:
Lifecycle calls from
on_progress(),on_stop()or a decision callable are refused:action.start()(first start)agent.start_action(action)action.start()/agent.start_action(action)on an INTERRUPTED actionaction.resume()action.cancel(),agent.cancel_action()(resumable)action.interrupt(force=True),agent.interrupt_action(force=True)action.cancel(),agent.cancel_action()(final)on_interrupt(self, progress)paying partial crediton_progress(self, delta)on_interrupt(self, progress)releasing resourceson_stop(self)if not self.interruptible:inon_interruptto detect a cancelon_cancel(self)remove()to callcancel_action()action.state = ...,agent.current_action = ...Additional Notes
ValueErrorfrominterrupt_for()even when the current action isn't interruptible, wheremainreturned False (pointed out by @atul-upadhyay-7 on Check the new action's agent and state before interrupting the current one #4112). That follows step 1 of the spec: a call that can't mean anything raises, whatever the policy says.cancel()from its ownon_start()completes it. Refusing to start is whatstart_requirementsare for (Claim the action slot when the action becomes active #4111). A test documents this.on_progress, to the last bit.on_complete,on_fail,on_cancel), as in theShiftexample. That may deserve a follow-up, such as anon_end()that fires once with the final state.on_stop()is still an open question in Lifecycle conventions for Event, EventGenerator and Action #4120.interrupt()/resume(), with @atul-upadhyay-7 as co-author of that commit. Thanks!Written with help from Claude Code (Claude Opus 5.5).