Skip to content

Rework the action lifecycle: final cancel, completion wins, on_progress/on_stop, removal - #4172

Merged
EwoutH merged 11 commits into
mainfrom
lifecycle-actions-vocabulary
Nov 26, 2026
Merged

EwoutH merged 11 commits into
mainfrom
lifecycle-actions-vocabulary

Conversation

@EwoutH

@EwoutH EwoutH commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Pre-PR Checklist

  • I linked an issue/discussion where a maintainer approved this enhancement/feature for implementation.

Approval Link

#4120: the opening post is the spec. The shared vocabulary, a final cancel(), no public start() and bool returns were agreed there (@quaquel, @codebreaker32). Defining "completion wins" on time came from @codebreaker32 and @atul-upadhyay-7, and on_progress(delta) with a delta only from @codebreaker32.

Summary

Implements the actions part of #4120 (section 3) as one contract: a final cancel(), separate interrupt()/resume(), completion wins on time, on_progress(delta) and on_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.py against the spec.

Motive

All of these reproduce on main (section 1 of #4120):

  • Partial credit is paid twice: the module's own example gives 45 energy for one forage interrupted halfway and resumed, instead of 30.
  • An interrupt at the exact completion time leaves the action INTERRUPTED with progress 1.0; resuming it completes it and pays again.
  • Interrupt and cancel are indistinguishable, and "cancel" can be resumed.
  • A hook that ends its own action is overwritten: 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.
  • A removed agent leaves its action ACTIVE forever, and state and current_action can be assigned freely.

Implementation

Vocabulary and state

  • New ActionState.CANCELED and on_cancel(). cancel() is final from ACTIVE, INTERRUPTED and PENDING, and ignores interruptible. The old resumable cancel is interrupt(force=True); agent.cancel_action() is final too, and agent.interrupt_action(*, force=False) is new.
  • resume() continues an INTERRUPTED action. start() is private; agent.start_action() only takes PENDING actions.
  • state and current_action are read-only. is_resumable is state is INTERRUPTED.
  • Resolved durations must be finite and >= 0, priorities not NaN (±inf allowed).
  • 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 INTERRUPTED new_action is resumed, passing the current action is a no-op returning True, and afterwards it asks whether the slot is free, not what interrupt() returned. Hooks that start new_action, fill the slot, remove the agent or end new_action are accounted for.

Completion wins on time

  • Each attempt has a deadline. interrupt(), cancel() and interrupt_for() complete an action whose deadline has been reached, checked before interruptible, so a due action never blocks its successor. progress is 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.
  • The completion event is scheduled before 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 to progress. 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.
  • Lifecycle calls for the same agent raise RuntimeError inside on_progress(), on_stop() and the decision callables (requirements, duration, priority, should_interrupt()).
  • The module docstring documents the hooks, the ways to model work (only on finish, per attempt as partial credit, accrued live) and the completion-wins, one-wake-per-time, re-entry and exception policies.

Removal

  • remove() closes the agent (no new attempts, no wakes), cancels a pending wake, cancels an ACTIVE action with on_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.
  • Started actions are tracked in a WeakValueDictionary keyed by id, in start order, so a dropped interrupted action isn't kept alive. Models with action agents pickle on main, and a weak mapping can't be pickled, so HasActions gets __getstate__/__setstate__; the spec didn't cover this.

docs/development/decisions.md gets an "API design" section: the shared vocabulary, completion wins, and one wake per time.

Usage Examples

class Forage(Action):
    def on_progress(self, delta):      # pays exactly once in total
        self.agent.energy += 30 * delta

class UseMachine(Action):
    def on_start(self):                # also runs on resume
        self.machine.claim(self.agent)

    def on_stop(self):                 # every attempt end, after the requirement check
        self.machine.release()

Interrupt and resume; the partial credit adds up to one full payment:

forage = sheep.start_action(Forage(sheep))  # duration 10, pays 30 * delta
model.run_for(4)
sheep.interrupt_action()  # True; INTERRUPTED, energy 12.0
model.run_for(3)
forage.resume()           # True; 6.0 time left
model.run_for(6)          # COMPLETED, energy 30.0

Cancel is final:

sheep.cancel_action()     # True; CANCELED, on_progress and on_cancel fired
forage.resume()           # ValueError: Cannot resume an action in CANCELED state. ...

Preempt, then come back from on_idle:

class Sheep(HasActions, Agent):
    def spot_wolf(self):
        current = self.current_action
        if self.interrupt_for(Flee(self, duration=2, priority=10)):
            self.unfinished = current

    def on_idle(self, previous):
        unfinished, self.unfinished = self.unfinished, None
        if unfinished is not None and unfinished.is_resumable and unfinished.resume():
            return
        self.start_action(Forage(self))

Completion wins: at t=10, before the completion event of a duration-10 action:

forage.interrupt()        # False: it completed instead, and paid once

Removing an agent cancels what it started, so a reservation held through an interruption is released:

class Shift(Action):
    def on_start(self):
        self.station.reserve(self.agent)

    def on_cancel(self):          # also when the agent is removed mid-break
        self.station.unreserve()

shift.interrupt()
worker.remove()                   # shift is CANCELED, on_cancel() fired

Lifecycle calls from on_progress(), on_stop() or a decision callable are refused:

class Meddle(Action):
    def on_stop(self):
        self.agent.start_action(Forage(self.agent))
# RuntimeError: Can't start, interrupt, resume or cancel actions of agent 1,
# or remove it, from on_stop(): ...
Today New
action.start() (first start) agent.start_action(action)
action.start() / agent.start_action(action) on an INTERRUPTED action action.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 credit on_progress(self, delta)
on_interrupt(self, progress) releasing resources on_stop(self)
if not self.interruptible: in on_interrupt to detect a cancel on_cancel(self)
overriding remove() to call cancel_action() not needed; the override still works
action.state = ..., agent.current_action = ... not allowed

Additional Notes

Written with help from Claude Code (Claude Opus 5.5).

@EwoutH EwoutH added the breaking Release notes label label Nov 22, 2026
@EwoutH
EwoutH added this pull request to stack #4178 November 22, 2026 09:40
@github-actions github-actions Bot added ci Release notes label docs Release notes label experimental Release notes label testing Release notes label labels Nov 22, 2026
@EwoutH
EwoutH removed this pull request from stack #4178 November 22, 2026 09:43
@EwoutH EwoutH changed the title Give actions a final cancel and a separate interrupt and resume Rework the action lifecycle: final cancel, completion wins, on_progress/on_stop, removal Nov 22, 2026
@EwoutH
EwoutH added this pull request to stack #4179 November 22, 2026 09:44
@EwoutH
EwoutH force-pushed the lifecycle-actions-vocabulary branch from bf3a5b0 to 1fec52c Compare November 22, 2026 09:54
@mesa-triage-bot

Copy link
Copy Markdown

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.

@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

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

could the frozen progress stay consistent while the hook runs, with a regression that reads progress from inside on_progress?

@EwoutH
EwoutH force-pushed the lifecycle-actions-vocabulary branch from 7d11283 to 130af20 Compare November 24, 2026 16:11
@EwoutH

EwoutH commented Nov 24, 2026

Copy link
Copy Markdown
Member Author

@atul-upadhyay-7 good catch, reproduced and fixed in 130af20: freezing now also restarts the attempt clock, so progress inside on_progress matches the frozen value. Regression test covers interrupt, cancel and removal.

@atul-upadhyay-7 atul-upadhyay-7 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, this resolves my points from #4120.

Comment thread mesa/experimental/actions/actions.py Resolved
Comment thread mesa/experimental/actions/actions.py Resolved
Comment thread mesa/experimental/actions/actions.py Resolved
@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

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?

Base automatically changed from lifecycle-wake-warning to main November 25, 2026 18:52
EwoutH and others added 6 commits November 25, 2026 19:52
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
@EwoutH
EwoutH force-pushed the lifecycle-actions-vocabulary branch from 130af20 to e7a6971 Compare November 25, 2026 18:52
@EwoutH
EwoutH requested a review from quaquel November 25, 2026 19:06
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
Comment thread mesa/experimental/actions/actions.py Resolved
@EwoutH

EwoutH commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

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

Comment thread mesa/experimental/actions/actions.py Resolved
Comment thread mesa/experimental/actions/actions.py Resolved
Replace the "pay" wording in the actions docstrings and tests with
what it means: applying the action's effect.

Assisted-by: Claude Code
Comment thread mesa/experimental/actions/actions.py Resolved
@atul-upadhyay-7

Copy link
Copy Markdown
Contributor

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 quaquel left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@EwoutH

EwoutH commented Nov 25, 2026

Copy link
Copy Markdown
Member Author

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?

@EwoutH

EwoutH commented Nov 26, 2026

Copy link
Copy Markdown
Member Author

@codebreaker32 would love your (final) review

@codebreaker32 codebreaker32 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for this and LGTM with some docstring suggestions

Comment thread mesa/experimental/actions/actions.py Resolved
Comment thread mesa/experimental/actions/actions.py Resolved
@EwoutH
EwoutH merged commit 0605c4e into main Nov 26, 2026
3 of 4 checks passed
codebreaker32 added a commit to codebreaker32/mesa that referenced this pull request Nov 30, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

breaking Release notes label ci Release notes label docs Release notes label experimental Release notes label testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants