Skip to content

Add requirements and a FAILED state to Action - #3801

Merged
quaquel merged 7 commits into
mesa:mainfrom
codebreaker32:feat/actions/requirements
Aug 26, 2026
Merged

quaquel merged 7 commits into
mesa:mainfrom
codebreaker32:feat/actions/requirements

Conversation

@codebreaker32

@codebreaker32 codebreaker32 commented Aug 14, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Action gains two requirement lists and a failure path. requirements gates the start, completion_requirements gates the effect, and a predicate that does not hold moves the action to ActionState.FAILED and fires on_fail() instead of letting it complete.

Motive

An action can only succeed today. Forage schedules its completion the moment it starts, and five time units later on_complete() fires and the sheep gains energy whether or not the conditions still hold. The workaround is to re-check inside on_complete() and return early, which repeats the same guard in every action and still leaves the action COMPLETED with nothing accomplished.

Declaring the condition moves the check into the framework and gives the failure its own state, so a model can tell "ate" from "got there and could not".

Implementation

Both lists accept a single callable(agent) -> bool or an iterable of them, mirroring the way duration and priority already accept callables resolved against the agent, and each is normalised into a list the action owns. Subclasses can assign to either after super().__init__() instead of passing them in.

requirements is checked at start(), before duration and priority are resolved, so a failing action never fires on_start() or on_resume() and never schedules a completion event.

completion_requirements is checked in _do_complete() before the effect is applied, and is empty by default. Nothing is checked at completion unless a model asks for it, which makes claim-at-start the default path.

They are separate lists rather than one list checked twice because the two questions are different, and separating them leaves the choice to the model developer. A rival resource should be claimed at the start, and the decisions that follow, take what remains, go elsewhere, or wait, belong to the agent rather than to a boolean gate. What the completion list is for is conditions nobody can reserve: a market still open when a trade lands, a counterparty still solvent at settlement.

Neither list is re-checked in between. Continuous revalidation would mean rescanning every active action whenever the world changes, which is activity scanning by another name. An action that must abort the moment a condition breaks belongs to a Threshold (#3766) calling agent.cancel_action().

Failure moves the action to FAILED and fires on_fail() in place of on_start() or on_complete(). _fail() clears agent.current_action before firing, so the agent is already idle when the hook runs and can start something else from inside it. On a completion failure progress still reads 1.0, because the full duration did elapse and only the effect is withheld.

interrupt_for() changes behaviour. It returned True unconditionally once the interruption succeeded; it now returns not new_action.has_failed. It deliberately does not roll the interruption back: the old action is already INTERRUPTED and the agent is left idle, since whether to resume it is the model's decision. The two False cases therefore differ in what they leave behind, a refused interruption changes nothing and a failed requirement does not.

Usage Examples

Claiming a rival resource at the start, which is where contention belongs:

class Graze(Action):
    def __init__(self, sheep, patch):
        super().__init__(sheep, duration=3.0, requirements=lambda a: patch.servings > 0)
        self.patch = patch

    def on_start(self):
        self.patch.servings -= 1  # claimed, so nobody else can take it

    def on_complete(self):
        self.agent.energy += 30

    def on_fail(self):
        self.agent.energy -= 2  # walked there for nothing
        self.agent.look_elsewhere()

Two sheep starting on a patch with one serving: the first claims it and grazes unimpeded, the second never starts and decides what to do next from on_fail().

Gating an effect on something nobody can reserve:

Trade(trader, duration=5.0, completion_requirements=lambda a: market.open)

A trade that starts at 15:58 and lands at 16:03 ends FAILED. Checking at the start would have reported the market open, which is true and useless, and there is no claim to take at 15:58 that would keep it open.

Additional Notes

A requirement that fails on resume is terminal. An action interrupted at 40% whose requirement then breaks moves to FAILED, keeps its 0.4 progress, and cannot be restarted even once the condition is repaired; the model has to build a fresh action and lose the partial work. The alternative, sending a failed resume back to INTERRUPTED so it stays resumable, was rejected because start() would then have to accept FAILED, and resuming = self.state is ActionState.INTERRUPTED would misclassify it, calling on_start() instead of on_resume() and re-resolving duration. If transient requirements turn out to be the common case, this is the piece to revisit.

Requirements are callables, so a lambda makes a model unpicklable. That is not new, duration=lambda a: ... already has the same effect; named functions and bound methods pickle fine.

The third item of section 2 in #3798, giving priority an effect, is not here. It is #3805, which adds Agent.should_interrupt(current, incoming) and rewrites the same three lines of interrupt_for().

@codebreaker32 codebreaker32 added experimental Release notes label enhancement Release notes label labels Aug 14, 2026
Three tests at start and three at completion drove identical setups and
asserted one fact each. Merge each triple into the one scenario it exercises
and regroup the rest into TestRequirements and TestActionFailure, matching
how the surrounding file bundles related assertions.

Co-Authored-By: Claude Opus 5 <[email protected]>
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🔵 +1.3% [+0.9%, +1.7%] 🔵 +1.3% [+1.1%, +1.4%]
BoltzmannWealth large 🔵 +2.1% [+1.4%, +2.7%] 🔵 +1.8% [+0.7%, +2.8%]
Schelling small 🔵 -0.0% [-0.6%, +0.5%] 🔵 -0.2% [-0.9%, +0.6%]
Schelling large 🔵 -0.6% [-1.2%, +0.2%] 🔵 -2.7% [-3.6%, -1.6%]
WolfSheep small 🔵 -0.3% [-0.7%, +0.2%] 🔵 +4.5% [-0.0%, +9.4%]
WolfSheep large 🔵 -0.5% [-0.9%, -0.0%] 🔵 +0.8% [-0.4%, +2.2%]
SugarscapeG1mt small 🔵 -1.1% [-1.6%, -0.4%] 🔵 +0.5% [-1.1%, +2.1%]
SugarscapeG1mt large 🔵 -0.1% [-1.5%, +1.3%] 🔵 +0.3% [-2.3%, +2.7%]
BoidFlockers small 🔵 -0.4% [-0.7%, -0.1%] 🔵 -0.2% [-0.5%, +0.1%]
BoidFlockers large 🔵 -0.6% [-0.9%, -0.3%] 🔵 +0.5% [+0.2%, +0.7%]

@quaquel

quaquel commented Aug 17, 2026

Copy link
Copy Markdown
Member

They are checked in exactly two places. At start() the check gates entry before duration and priority are resolved, so a failing action never fires on_start() or on_resume() and never schedules a completion event. At _do_complete() the check runs again before the effect is applied.

I am not sure about this and I am not convinced by the grazing example. Typically, you would claim the resource at the start of the action, rather than check at the end if the resource is still available. So, if you arive at a station and there is not enough resource remaining, the action would be to claim just the remaining resource, move to another station, or wait until enough of the resource is again available.

Also, requirements at start need not be the same as requirements on completion. Can this be handled?

@codebreaker32

codebreaker32 commented Aug 18, 2026 •

Copy link
Copy Markdown
Collaborator Author

Sorry, I missed it yesterday and apologies for the wrong example.

Your three responses, take what remains, go elsewhere, or wait, all need to know how much is there. A requirement returns True or False, so it cannot express "ten were wanted, three are left, take the three". In writing that example I presented requirements as a way to acquire a resource. It is not one, and it should not become one. Acquisition needs a quantity and a decision, and both belong to the agent, in on_start or before it, where it can query the station, take what is actually there, and choose between your three outcomes.

What a boolean gate is good for is preconditions that are genuinely binary, where the only sensible response is not to start at all: the agent holds a permit, the vehicle has a driver, the door is unlocked. Nothing to claim, no quantity to negotiate.
That also leaves the completion check with much less to justify it, since the grazing example was the justification.
What I think still needs it is state that nobody can reserve. A trade takes five minutes and starts at 15:58, the market closes at 16:00, and the trade lands at 16:03. Checking at the start says the market is open, which is true and useless, and there is no claim to take at 15:58 that would keep it open, because opening hours are not a resource. A settlement that requires the counterparty still solvent when the money moves has the same shape. In those cases the start check answers the wrong question.
If you would rather handle that with a Threshold that cancels the action the moment the condition breaks, then the completion check has nothing left to do.

On your second question, yes:

Action(agent, requirements=[...], completion_requirements=[...])

Independent lists rather than one list checked twice, with the completion list empty by default so nothing is checked at the end unless a model asks for it.

I will replace the example with a claim-based one either way. It makes the boundary obvious, and the current one teaches the wrong pattern.

@quaquel

quaquel commented Aug 18, 2026

Copy link
Copy Markdown
Member

If we separate on_start requirements and on_completion requirements, it leaves it to the model developer to decide and gives them also a lot more flexibility.

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

Yes and using Threshold for other cases you mentioned. I will try to build an example demonstrating it

Separating the two, as quaquel suggested, leaves the choice to the model
developer instead of checking one list at both ends.

requirements gates start(); completion_requirements gates the effect and is
empty by default, so nothing is checked at completion unless a model asks
for it. That makes claim-at-start the default path.

Replace the contested-grass example, which taught re-checking a rival
resource at the end, with one that claims the serving in on_start and
decides what to do next from on_fail. Add a market-hours test for the case
the completion list exists for: a condition nobody can reserve, where the
start check answers the wrong question.

Co-Authored-By: Claude Opus 5 <[email protected]>
Comment thread mesa/experimental/actions/actions.py Resolved
Comment thread mesa/experimental/actions/actions.py Resolved

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

I have a few minor points at the code level.

Also, we now have start and completion requirements. But what about an interrupt? How would that work?

@codebreaker32

codebreaker32 commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator Author

Renamed, they are start_requirements and completion_requirements now.

On interrupt:

  1. start() checks start_requirements. They hold, so the action goes ACTIVE, on_start() fires, and a completion event is scheduled for the full duration.
  2. interrupt() freezes progress, cancels that completion event, moves the action to INTERRUPTED and fires on_interrupt(progress). Nothing is checked. The action is not deciding anything here, it is being stopped.
  3. start() again re-checks start_requirements, because resume goes through the same entry point rather than a separate one. If they hold, the action goes ACTIVE, on_resume() fires, and a completion event is scheduled for the remaining duration only. If they do not, the action moves to FAILED and on_fail() fires, with on_resume() never called.
  4. When that event lands, completion_requirements decide whether the effect applies: COMPLETED and on_complete(), or FAILED and on_fail().

completion_requirements are never consulted at step 2 or 3. They gate the effect, and an interrupted action has no effect to gate yet.

For eg. A technician on a eight hour shift. The technician has to be on shift to work on it, and the overhaul only counts if the machine is still in service when it lands:

class Repair(Action):
    def __init__(self, tech, machine):
        super().__init__(
            tech,
            duration=8.0,
            start_requirements=lambda a: a.on_shift,
            completion_requirements=lambda a: machine.in_service,
        )

An emergency callout preempts it three hours in, and runs an hour past the end of the shift:

t=0.0  repair started
t=3.0  repair paused at 38%
t=3.0  emergency callout
t=9.0  repair failed (38% done)      # resume re-checks on_shift, shift ended at 8

And separately, the same overhaul running undisturbed while the machine is written off on the bench:

t=0.0  repair started
t=8.0  repair failed (100% done)     # completion requirement withheld the effect

One consequence worth noting from that first trace. The 38% is lost: FAILED is terminal, and there is no public way to construct an Action that starts part-done, so a model wanting to pick the overhaul up next morning starts from zero. I am inclined to leave that as is, though. By the same argument as before, an agent should not be attempting a resume it cannot perform, the gate is a safety net, not control flow, so the stranded progress is a model deciding badly rather than the framework losing information it should have kept. Thoughts?

Separately, I also have had a question. cancel_action() from #3461 does not cancel: it force-interrupts, ignoring the interruptible flag, and leaves the action INTERRUPTED and resumable. There is no CANCELLED state. That read fine when there was no terminal state to confuse it with, but FAILED gives us one.
Is that worth renaming? The obvious candidate, interrupt_action(), matches the state but hides the thing that makes the method useful: interrupt_for() is refused by a non-interruptible action while this one overrides it, so two methods called "interrupt" would behave differently on the same flag, force_interrupt() keeps both halves.

@quaquel
quaquel merged commit 395227c into mesa:main Aug 26, 2026
11 checks passed
@EwoutH

EwoutH commented Sep 22, 2026

Copy link
Copy Markdown
Member

Thanks for working on this. Interesting stuff.

Actions do get more powerful but also more complicated this way. A documentation/tutorial effort might be useful.

@codebreaker32

Copy link
Copy Markdown
Collaborator Author

Right, and that is indeed point 5 of #3798. I am a bit preoccupied currently but I will land it by the end of this week.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement Release notes label experimental Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants