Skip to main content

executor

Executor: runs a RunnableDAG inside a Prefect flow.

This is the runtime heart of the DAG system. It takes a fully parsed and validated RunnableDAG (a BackgroundDAG or InteractiveDAG) and executes every step in declaration order, wiring inputs from prior step results or context providers.

Step execution​

Every step runs off the event loop on a daemon thread, which keeps the (synchronous) task function clear of the loop's default thread-pool executor - whose non-daemon workers would hold the process open at shutdown. Results stay in-process — no Prefect serialisation boundary is crossed — so private attributes such as _accessor on cache-backed result types are preserved for downstream steps.

Nodes marked parallel=True are additionally run concurrently: they are tracked as asyncio.Task objects in a pending dict and awaited lazily when a downstream step declares a FromRef dependency, or flushed at the end of the loop. Sequential nodes are awaited immediately, so declaration order holds.

Sequential steps used to be called directly on the event loop. Because the pod runs its background DAGs in-process, on the same loop that supervises the mailbox listener and dispatches its handlers, a long step — an hour has been observed — left the pod unable to see listener failures or run queued message handlers until it finished.

A background run's context assembly is off the loop for the same reason, and on the same kind of thread: build_background_flow awaits open_run rather than calling it, because materialising the datasource and planning the waves is work of that same order.

Time bounds​

A background run is bounded three ways (bitfount.flows.dag.time_bounds): its setup, each wave's execution, and its wave loop, which also stops between waves at a soft cap. A daemon thread cannot be stopped, so an expired bound sets the run's bitfount.utils.cancellation.RunCancellation — checked before every step, inside the long steps' chunk loops, and between the stages of setup — and waits for the thread to end. The flow body returns only once every thread it started has, so whatever is held around it is released after the last of them.

Setup is the exception. A read that never returns — a network share that has gone away mid-stat — cannot be cancelled by anything in the process, and waiting it out holds the lineage lock and the machine slot for as long as the pod is up. So a setup bound that expires gives the thread background_dag_setup_abandon_wait seconds to stop and then gives up on it: the run fails setup_timeout, its locks are released here, and the thread is left running with what it opened. Whatever takes the lineage next fences its writes out (bitfount.cache.types.lock_fences), so the abandoned setup can account for nothing the next run does.

Runtime parameters​

Steps often require runtime objects (datasource, cache, task_hash, …) that are not declared in the YAML. Pass them via DAGRunContext.runtime_params; they are merged into every step's kwargs before YAML-resolved inputs, so YAML refs can override them when needed.

Public API​

execute_dag(dag, run_ctx) Runs the DAG. Caller must already be inside a Prefect @flow context; raises RuntimeError otherwise.

run_dag(dag, run_ctx) Ensures a Prefect flow context exists, then delegates to execute_dag. Safe to call from anywhere.

build_flow(dag, run_ctx) Returns a named Prefect @flow callable for deployment scenarios.

execute_background_dag(dag, *, task_hash, project_id, open_run, ...) Runs one background DAG from inside whichever flow run already owns the work — the served background_dag_runtime deployment, which must not nest a second tagged flow run inside its own.

build_background_flow(dag, *, task_hash, project_id, open_run, on_slot_acquired=None, fence_cache=None) Returns a @flow callable that opens the run inside the flow body, so a background run's flow run is the outermost boundary of its work, with an on_slot_acquired hook that fires only once the run's locks are held.

Locks​

A background run holds, in this order and never the other way round: its lineage's lock (background_lineage:<project_id>:<task_hash>, one run of a lineage at a time), a machine slot (background_dag_max_concurrent_runs), and, around each step that declares one, at most one step resource (bitfount.flows.dag.step_resources). A wait for the first two is outside every time bound. A wait for a step resource is taken out of them while no other step of the run is running, is counted beside a running step, and ends once the run is cancelled. A lineage holder takes a fencing token on acquire, and its ledger and cutover writes commit only while it is still the latest holder.

Module​

Functions​

build_background_flow​

def build_background_flow(    dag: BackgroundDAG,    *,    task_hash: str,    project_id: str,    open_run: Callable[[], DAGRunContext | None],    on_slot_acquired: Callable[[], None] | None = None,    on_success: Callable[[], None] | None = None,    outcome: BackgroundRunOutcome | None = None,    fence_cache: CacheProtocol | None = None,    update_hold: Callable[[], Awaitable[bool]] | None = None,) ‑> Callable[[], Coroutine[typing.Any, typing.Any, dict[str, typing.Any] | prefect.client.schemas.objects.State]]:

Return a @flow callable that opens its own run, inside the flow.

The background counterpart to build_flow, and the shape that makes "a Prefect flow run exists" a total invariant for background work. build_flow needs a DAGRunContext in hand, which means the run row, the datasource materialisation and the model resolution all happen before anything is observable; a crash in that window leaves a running cache row and no flow run to explain it. Here open_run is deferred into the flow body, so all of it is inside the boundary: a setup failure is a failed flow run rather than a log line and a dropped trigger.

The lineage lock lives here too, for the same reason: a second run of the lineage waits for it inside its own flow run, and one that does not get it in time ends as an immediately-terminal SKIPPED_STATE_NAME run, which is visible in the Prefect UI where an early return None was visible nowhere. The lock is held on a lease, so a dead holder cannot wedge the lineage for longer than the lease. Every trigger takes the same locks (execute_background_dag).

Arguments

  • dag: The validated background DAG to execute.
  • task_hash: The (pod, datasource) task hash, naming the lineage lock.
  • project_id: Project the run belongs to, naming the lineage lock.
  • open_run: Deferred run-context assembly — typically functools.partial(build_background_run_context, ...). Called once, inside the flow body, after the locks are held. None means the caller declined the run for its own reasons, and is reported the same way a duplicate is.
  • on_slot_acquired: Called once, from inside the flow body, after the lineage lock and a machine slot are held and before open_run. Not where a rerun commits: that waits for setup's gates (commit_background_run in build_background_run_context), so a run that stands down is not recorded as having run.

Raising from it fails the flow run and nothing executes.

  • on_success: Called once, from inside the flow body, after the DAG has executed without raising. Its counterpart to on_slot_acquired: that one records that a lineage started, this one records what a lineage covered, and the two must not be collapsed. A caller banking "the inventory was this big when I finished" from the start of a run would bank it for files the run never reached if it then died, and those files would stop looking outstanding.

Not called on either Skipped exit — a duplicate and a declined run both covered nothing — nor on a raising one, which propagates and fails the flow run as before.

  • outcome: Filled in with why the run ended without executing its DAG, when it does, and whether it made progress when it did (WavePlan.made_progress): an unwaved run, an empty selection, a plan carried to the end, or at least one carried wave that left fewer candidates to carry. The run's row records it, and the scheduler's one give-up bound counts the runs that did not.
  • fence_cache: The cache holding the lineage's fence; see execute_background_dag.
  • update_hold: Whether an orchestrator update hold is in force; see execute_background_dag.

Returns An async Prefect @flow callable with no required arguments. It returns the step results, or a terminal State when nothing ran.

build_flow​

def build_flow(    dag: RunnableDAG, run_ctx: DAGRunContext,) ‑> Callable[[], Coroutine[typing.Any, typing.Any, dict[str, typing.Any]]]:

Return a named Prefect @flow callable for dag.

Useful for deployment scenarios where a first-class flow object is needed. For most runtime cases prefer run_dag.

Note that the flow's name is dag.name, which is shared by every project and datasource using the same template — it does not identify a run. Flow runs that need to be findable again are tagged at call time by _run_dag_flow_and_flush; see bitfount.runtimes.dedup.background_dag_tags.

Arguments

  • dag: A validated RunnableDAG (BackgroundDAG or InteractiveDAG).
  • run_ctx: Runtime context passed through to execute_dag.

Returns An async Prefect @flow callable with no required arguments.

execute_background_dag​

async def execute_background_dag(    dag: BackgroundDAG,    *,    task_hash: str,    project_id: str,    open_run: Callable[[], DAGRunContext | None],    on_slot_acquired: Callable[[], None] | None = None,    on_success: Callable[[], None] | None = None,    outcome: BackgroundRunOutcome | None = None,    fence_cache: CacheProtocol | None = None,    update_hold: Callable[[], Awaitable[bool]] | None = None,) ‑> dict[str, typing.Any] | prefect.client.schemas.objects.State:

Run one background DAG, from inside whichever flow run owns the work.

The body build_background_flow wraps, factored out so that a caller which already is the flow run can use it without nesting a second one. That caller is the served background_dag_runtime deployment: its own flow run carries this lineage's tags, and a subflow carrying them too would read to the schedulers as a second live run of the lineage.

Takes the lineage lock, fences the lineage, takes a machine slot, opens the run, then executes the DAG. In that order, and the order is the contract: nothing expensive is assembled until both locks are held, and on_slot_acquired fires only once they are — so a run that never got them recorded nothing either. A run that waits out background_lineage_lock_wait for its lineage ends Skipped (duplicate_lineage_run); one that waits out background_machine_slot_wait for a machine slot ends Skipped (machine_busy); one that gets its slot while an orchestrator update hold is in force gives it back and ends Skipped (update_hold_refused). Neither wait counts against any time bound.

Before any of that, the run waits for a free machine slot, reading the machine's slots rather than taking one. A run that arrives on a full machine has nothing ahead of it but the machine slot it cannot get, so waiting before the lineage is taken costs nothing it would not have spent: a run that is turned away ends without holding the lineage its own replay would then have to wait for, and a run that is admitted is admitted on the same chance it always had — a slot freeing anywhere inside background_machine_slot_wait is still caught. What the wait spends comes out of that one budget, so the acquire that follows (with the lineage held) only waits for what is left. The read reserves nothing, so the acquire still decides the last slot.

Every argument means what it means on build_background_flow; see there.

The run is bounded by the settings background_dag_setup_timeout, background_dag_wave_timeout and background_dag_max_run_seconds (see bitfount.flows.dag.time_bounds), and returns only once every thread it started has ended — but for a setup that outlived its bound by background_dag_setup_abandon_wait, whose thread is given up on so that the locks held here return to the machine. An expired bound fails the run with a TimeBoundExceededError, except the soft cap, which ends it completed; each records its stop_reason on outcome.

Arguments

  • dag: The validated background DAG to execute.
  • task_hash: The (pod, datasource) task hash, naming the lineage lock.
  • project_id: Project the run belongs to, naming the lineage lock.
  • open_run: Deferred run-context assembly, called once the locks are held.
  • on_slot_acquired: Called once the locks are held, before open_run.
  • on_success: Called after the DAG executed without raising and covered the datasource.
  • outcome: Filled in with why the run ended without executing its DAG, when it does or which bound ended it, and whether it made progress when it did.
  • fence_cache: The cache holding the lineage's fence, which the run's ledger and cutover writes are checked against; None fences nothing. It must be the run context's own cache, which is checked once setup returns.
  • update_hold: Awaited once the machine slot is held, and truthy while an orchestrator update hold is in force; None never holds.

Returns The step results, or a terminal State when nothing ran.

Raises

  • TimeBoundExceededError: If setup, the run's only waves, or its wave loop outlived their bound, once every thread has ended — or, for setup, once the run has given up waiting for it (TimeBoundExceededError.threads_abandoned).
  • FencedOutError: If a later run of the lineage took its fence; the run fails with stop_reason "fenced_out".

execute_dag​

async def execute_dag(    dag: RunnableDAG, run_ctx: DAGRunContext, bounds: RunBounds | None = None,) ‑> dict[str, typing.Any]:

Run dag inside an already-active Prefect flow context.

Raises RuntimeError if no flow context is active — use run_dag when you cannot guarantee one.

With bounds, the wave loop is timed from here: the soft cap stops it between waves, and the hard cap stops it outright, failing the run.

Arguments

  • dag: A validated RunnableDAG (BackgroundDAG or InteractiveDAG).
  • run_ctx: Runtime context: providers, runtime params, reporter.
  • bounds: The run's time bounds, or None for none.

Returns Mapping of step name → step result for every executed step.

Raises

  • RuntimeError: If called outside a Prefect flow context.
  • Exception: Re-raises any step exception after calling run_ctx.lifecycle_notifier.on_failure.

run_dag​

async def run_dag(dag: RunnableDAG, run_ctx: DAGRunContext) ‑> dict[str, typing.Any]:

Run dag, creating a Prefect flow context if one is not already active.

Safe to call from anywhere — no existing flow context required.

Arguments

  • dag: A validated RunnableDAG (BackgroundDAG or InteractiveDAG).
  • run_ctx: Runtime context: providers, runtime params, reporter.

Returns Mapping of step name → step result for every executed step.

run_flow_resiliently​

async def run_flow_resiliently(flow_fn: Callable[[], Awaitable[Any]]) ‑> Any:

Run a Prefect flow, retrying the transient Windows start-time 409.

Guards against the Windows-only flow_run_state timestamp collision (see the module note above): a bounded retry re-creates the flow run a clock-tick later so its Pending/Running state timestamps differ. Only a 409 is retried; any other error — and the final 409 after exhausting retries — is re-raised unchanged. Safe against re-running work: the collision happens at begin_run before any step executes (a real DAG does far more than one clock tick of work, so the Running->Completed transition never shares a tick).

Each retry creates a new flow run, so the run it gave up on is left behind at PENDING, carrying this run's lineage tags. Two consequences, handled separately because they need different remedies:

  • The retry must not defer to the run it just abandoned. It cannot: the abandoned run never entered its body, so it never took the lineage lock the retry's body waits for. That is correctness, and it does not depend on the cleanup below succeeding.
  • The abandoned run is ended as CANCELLED here (_abandon_flow_run), so it does not sit PENDING forever misrepresenting the pod's history. That is tidiness, and it is best-effort.

Global variables​

  • DUPLICATE_LINEAGE_RUN - stop_reason of a run that found its lineage already held for the whole wait.
  • EHR_UNAVAILABLE - stop_reason of a run that stood down because a pass over EHR patients could not reach the EHR.
  • FENCED_OUT - stop_reason of a run whose fence a later run of its lineage took.
  • MACHINE_BUSY - stop_reason of a run that found no machine slot for the whole wait.

Classes​

BackgroundRunOutcome​

class BackgroundRunOutcome(stop_reason: str | None = None, made_progress: bool = False):

What a background run's body reports back to the flow that ran it.

Filled in by execute_background_dag for the caller's own telemetry; a returned State names the exit but not always the reason, since several exits share SKIPPED_STATE_NAME.

Attributes

  • stop_reason: Why the run ended without executing its DAG, as carried on BackgroundDAGRunEvent.stop_reason; None when it executed it.
  • made_progress: Whether the run moved its lineage's sweep forward (WavePlan.made_progress), for the run's row.

Variables​

  • made_progress : bool
  • stop_reason : str | None