Available state change hooks
Note that the
on_rollback hook for tasks is not a proper state change hook but instead
is a transaction lifecycle hook.
Rollback hooks accept one argument representing the transaction for the task.Send a notification when a workflow run fails
To send a notification when a flow or task run fails, you can specify aon_failure hook.
on_failure hook will not run until all retries have completed and the flow run enters a Failed state.
Execute code when a task starts running
Theon_running hook executes when a task enters a Running state, before the task body executes. This is useful for logging, metrics, or setting up runtime state:
on_running hooks execute synchronously before the task body runs. If your hook takes 10 seconds, the task waits 10 seconds before starting.
When retries are configured, on_running hooks fire on each retry attempt, including the initial run. For example, a task configured with retries=2 will trigger its on_running hooks up to three times: once on the initial run and once for each retry attempt.
Log from state change hooks
State change hooks run outside the active flow or task run context. This meansget_run_logger() will raise a MissingContextError if called inside a hook.
To emit logs from a hook that appear in the Prefect UI, use flow_run_logger (or
task_run_logger for task hooks) from prefect.logging.loggers. These functions
create a logger tied to the run using the parameters your hook already receives:
Emit events from state change hooks
A common use of hooks is to emit a custom event when a run reaches a state—for example, a failure event that other automations react to. Because the hook runs a fraction of a second after the state change, your custom event and Prefect’s own state change event (likeprefect.flow-run.Failed) occur within a second or
two of each other, and Prefect does not guarantee the
order they arrive at the automation system. If a
trigger uses the state change event in after and your custom event in expect, that
race can cause missed or spurious firings.
To make the order deterministic, emit your event with follows referencing the state
change event. The state argument your hook receives carries what you need: state.id
is the ID of the state change event, and state.timestamp is when it occurred.
Event passed to follows is a stub. emit_event reads only its id and occurred
fields—to fill in the follows field of the emitted event and to check that the two
events occurred within five minutes of each other. The stub is not emitted: Prefect
already emitted the real prefect.flow-run.Failed event server-side, and the stub only
identifies it.
With follows declared, the automation system always processes your custom event after
the state change event it follows.
Pass kwargs to state change hooks
You can compose the with_options method to effectively pass arbitrary **kwargs to your hooks: