<@ULVA73B9P> - should there be an active flow run ...
# ask-marvin
k
@Marvin - should there be an active flow run context in a
on_running
hook?
m
thought for 129.7 seconds
No —
on_running
hooks do not run with an active
FlowRunContext
in Prefect 3.x. That means inside an
on_running
hook: -
get_run_logger()
will not work -
FlowRunContext.get()
will not give you an active flow context - you should not expect the same context that exists inside the flow body What is available is the hook’s arguments: -
flow
-
flow_run
-
state
So this is the supported pattern:
Copy code
python
from prefect import flow
from prefect.logging.loggers import flow_run_logger

def my_on_running(flow, flow_run, state):
    logger = flow_run_logger(flow_run=flow_run, flow=flow)
    <http://logger.info|logger.info>(f"Flow run {flow_run.name} entered running state")

@flow(on_running=[my_on_running])
def my_flow():
    pass
This is documented here: - State change hooks guide Key detail from the docs: state change hooks run outside the active flow/task run context. So if your question is “should there be one?” from a user-expectation perspective, maybe arguably yes — but today, by design, there isn’t. If you want, I can also show where in the engine lifecycle
on_running
fires relative to flow context setup.
k
@Marvin is there access to anything related to the flow? Are environment variables set? I just need the flow run id in a hook
m
thought for 6.2 seconds
Yes — in an
on_running
hook you do get access to the
flow_run
object that’s passed into the hook, and that includes the flow run ID. Use:
Copy code
python
def my_on_running(flow, flow_run, state):
    flow_run_id = flow_run.id
    print(flow_run_id)
So if all you need is the run ID, you do not need active
FlowRunContext
. You also have access to things like: -
flow
— the flow object -
flow_run
— the API model for the run -
state
— the new state Typical useful fields on
flow_run
include: -
flow_run.id
-
flow_run.name
-
flow_run.flow_id
-
flow_run.deployment_id
-
flow_run.tags
-
flow_run.parameters
(if populated on the run object) About environment variables: normal process environment variables should still be available via
os.environ
, because the hook runs in the same Python process. But Prefect run context-backed accessors are the thing that won’t be available. Example:
Copy code
python
import os

def my_on_running(flow, flow_run, state):
    print("flow run id:", flow_run.id)
    print("MY_ENV_VAR:", os.environ.get("MY_ENV_VAR"))
So the short answer is: - Flow context? No - Hook args with flow metadata? Yes - Environment variables? Yes, regular OS env vars - Need flow run id? Use
flow_run.id
If you want, I can give you a tiny hook example that writes the flow run ID to a file / external service / log.