background_handler
Background-DAG execution on behalf of a Pod.
Owns everything a background DAG run needs after the Hub says a dataset was linked to a project — or that the project's task definition changed: parsing and persisting the replay material, submitting the run to this pod's Prefect deployment, holding the strong references to the in-flight submissions, keeping schema generation off a datasource a run is reading, the grants a run authenticates with, and the recovery poller that replays a run whose process is provably gone.
This lives in the flows.dag package rather than federated.pod for the reason
_InteractiveDAGHandler does: the Pod routes a DATASET_PROJECT_LINKED
message here and otherwise stays agnostic to how a background DAG is driven. It
reads the pod state a run is assembled from (name, key path, hub, identifier,
datasources, EHR config) off the pod's PodContext, so it never imports
bitfount.federated.pod.pod (pod already imports this package).
Periodic reruns are a reason to start a background run, not a different way
of running it, so they schedule through schedule_from_record, the single path
both take, and open the cache through open_cache, which owns the stand-down
both share.
Classes
BackgroundDAGHandler
class BackgroundDAGHandler(ctx: PodContext, *, pod_control_url: Callable[[], str | None]):Runs a pod's background DAGs: trigger, schedule, recover, drain.
Arguments
ctx: The pod's identity and services.pod_control_url: Returns where a run fetches its credentials from, orNoneon a pod with no control server.
Variables
-
cache_unusable : bool- True once the background cache has been found unusable by this build.The cache cannot become usable while the pod runs: the fix is to delete the file with the app closed.
run_grants : RunGrantRegistry- The nonces the pod's control server honours, one per lineage.
Methods
drain
async def drain(self, timeout: float = 10.0) ‑> None:Stop the background DAG runner and close the rows its runs left open.
The runs execute in subprocesses the runner launched, so stopping the
runner is what stops the work: Runner.astop cancels every run it is
executing and unwinds their subprocesses. Left alone they would be
killed by the interpreter exiting, and Prefect would report only
"Execution was cancelled by the runtime environment" — accurate but
useless to whoever reads the log.
A cancelled run may not reach its own finally, so closing the run rows
here is what keeps them from sticking at running and leaving the
lineage looking busy for ever. The start-up sweep in
_adopt_background_dag_runs closes whatever this misses, which is
anything left by a pod that did not shut down.
Arguments
timeout: Seconds to wait for the runner and the pending submissions to unwind.
handle_dataset_project_linked
async def handle_dataset_project_linked(self, message: _BitfountMessage) ‑> None:Handle a DATASET_PROJECT_LINKED message from the Hub.
Deserialises the payload, builds the background DAG for the project's v9 FlowSpec and fires it off as a background asyncio task so that this handler returns immediately and does not block the message-polling loop.
Completion (success or failure) is recorded on the cache Run row by
the DAG executor's LifecycleNotifier. Background triggers have no
modeller mailbox, so no lifecycle messages are sent; setup failures
before a run context exists are logged and dropped.
The replay material is written under the project's definition lock, and the Hub's last answer for the project is dropped there, as an update does: the link's definition is newer than that answer, so the next task-definition check asks the Hub again rather than switching this lineage back. A checked submission of this lineage that started waiting for the lock before the link released it stands down, because the link's run is submitted in its place.
Arguments
message: The incoming DATASET_PROJECT_LINKED message. Itsbodymust be a JSON-encoded_DatasetProjectLinkedPayload.
handle_rerun_requested
async def handle_rerun_requested(self, message: _BitfountMessage) ‑> None:Handle a RERUN_REQUESTED message from the Hub.
Records the rerun the message names against the pod's background cache; the pod decides the scope and cooldown, the message only names the kind.
The request is signed by a Hub signing key and encrypted to the pod's public key, and the pod acts only on what the signature covers. Any authenticated user can queue this message type into a pod's mailbox, and the signature covers neither the envelope's sender nor its timestamp; the Hub is what applies the owner and feature-flag checks, so only a request it signed is trusted.
Checked in this order, each failure dropping the request with a
warning: the body parses; the signed payload verifies against the Hub's
published keys and opens with the pod's private key; the signed request
parses; its datasource matches the body's and is served by this pod;
its signed requested_at is fresh; its kind is one this pod performs;
its params are valid for that kind; and the background cache is
usable.
Arguments
message: The incoming RERUN_REQUESTED message. Itsbodymust be a JSON-encodedRerunRequestedBody.
handle_task_definition_updated
async def handle_task_definition_updated(self, message: _BitfountMessage) ‑> None:Handle a TASK_DEFINITION_UPDATED message from the Hub.
The Hub sends this on every save of a project's task definition,
carrying the definition rendered for one linked dataset. The handler
parses it, checks that this pod serves the dataset, and applies it
through _apply_task_definition under the project's definition lock:
the path a definition fetched from the Hub takes too. That method
says what applying does and what it leaves alone.
The message is newer than whatever the Hub last answered a fetch for the project, so that answer is dropped once the lock is held, and the next check asks again. Dropped under the lock, not before it: a fetch in flight when the message arrived holds the lock, and may cache the definition from before the save as it finishes. When the update replaces the lineage, a checked submission of it that started waiting for the lock before the update released it stands down, because the replacement is submitted in its place.
Applied with source="message", because only the message says that
this dataset is linked: it records the link, and records a version
refusal as a failed Run row every time one arrives.
Never raises: nothing on the mailbox side catches a handler's exception — the listener re-raises it, and the supervisor reconnects only for message-service errors — so an exception out of here would stop the pod serving.
Arguments
message: The incoming TASK_DEFINITION_UPDATED message. Itsbodymust be a JSON-encoded_DatasetProjectLinkedPayload— the same shape a dataset-project link carries, because it carries the same thing: the rendered definition.
hold_schema_generation
def hold_schema_generation(self) ‑> None:Suspend background schema generation; see the datasource manager.
lineage_live
async def lineage_live(self, task_hash: str, project_id: str) ‑> bool:Whether a run of this lineage is live, here or as Prefect sees it.
Prefect's state can say Crashed for a run this pod is still executing,
because the zombie reaper flips a run that froze longer than the
silence window. So a run of the lineage with a live subprocess here is
asked about first, by its own flow run id, and counts as live while it
still holds its lineage (_runs_holding_their_lineage): until it has
reported its own end, or for a bounded time once Crashed. Otherwise
Prefect is asked whether any run of the lineage is submitted.
When the runner cannot say what is in flight, a lineage this pod has submitted counts as live. When Prefect cannot be asked, every lineage does: the cost of that answer is a grant that is not rotated, or a rerun that is not submitted, this once.
Arguments
task_hash: The(pod, datasource)task hash.project_id: The project the run belongs to.
Returns Whether a run of the lineage is, or may be, live.
open_cache
def open_cache( self, *, take_backup: bool = True, phase_seconds: dict[str, float] | None = None,) ‑> CacheProtocol | None:Open the background cache, standing down for good if it is unusable.
Shared by background-DAG recovery and periodic reruns. The flag it sets is read by both, which is why the warning names both features.
Arguments
take_backup: Seeopen_background_cache. The periodic rerun sweep passesFalse— it opens the cache every minute only to read it, and the snapshot is left to the openers that write, to the recovery poller (which opens on every poll, so arun_poddeployment that serves no cron deployments is still covered), and to the scheduledcache_backup_runtimeflow.phase_seconds: When given,open_background_cacheadds the timing of each blocking step of the open to it.
Returns
The open cache, which the caller must close, or None once the
cache has been found unusable.
prepare_ehr_listing
async def prepare_ehr_listing( self, *, refresh: ListingRefresh | None = None,) ‑> str | None:Serve this pod's EHR patient listing, grant it, and refresh it if due.
Registers the listing deployment on the pod's runner and leaves a grant in the cache under the listing key, as a background DAG submission does for its lineage. The grant is rotated unless a listing is live, which keeps the nonce it holds; it is renewed instead.
With refresh, also submits a listing when the newest complete
snapshot is missing or stale and no listing is live. The caller decides
whether any flow reads $ehr_patients.
Never raises: a pod that cannot serve listings still serves everything else.
Arguments
refresh: Why a refresh is wanted, if one is;Nonenever refreshes.
Returns
The listing key, or None when this pod has no EHR configured or
the listing could not be prepared.
reconcile_tick
async def reconcile_tick(self) ‑> None:Match the pod's holds, cache rows and grants to the runs it has.
release_schema_generation
def release_schema_generation(self) ‑> None:Release one suspension; see the datasource manager.
schedule_from_record
def schedule_from_record( self, record: FlowSpecRecord, *, trigger: BackgroundTrigger, attempt: int, monitor_task_id: str, is_rerun: bool | None = None,) ‑> None:Rebuild and schedule a background run from a persisted spec.
Shared by recovery's replay and the periodic-rerun check, which differ only in their trigger, their position in the lineage and the Hub monitor task they report under. Routing both through here is what keeps a rerun identical to the run it repeats.
Reads nothing out of the spec beyond the lineage it names: the run loads the spec from the cache itself, in the process that executes it, so the pod and the run cannot disagree about what was stored. The datasource lookup below is therefore a check rather than an input — this pod refuses to submit work for a datasource it no longer serves. The stored spec may be older than the Hub's definition, so the submission goes through the task-definition check whatever its trigger, an owed link or update included.
Arguments
record: The stored spec to run.trigger: Why this run is being started.attempt: This run's position in the recovery lineage.monitor_task_id: Hub monitor task id this run reports under.is_rerun: Whether the run stamps the lineage as a rerun;Nonereads it off trigger.
Raises
KeyError: If the datasource is no longer configured on this pod — the caller logs it and moves on.
start_recovery
def start_recovery(self) ‑> None:Start the recovery poller, unless it is already running.
Not switchable. The duplicate guard asks whether a lineage has already been submitted, not whether its run is alive, so a run whose process is gone is not detected anywhere else: this poller is what ends it. A switch here would be a switch that silently wedges a lineage.
start_runner
async def start_runner(self) ‑> None:Serve this pod's background DAG deployments, and reconcile them.
Five steps, in order. The runner comes up first because everything after it needs somewhere to register against. The deployments of every project this pod still holds replay material for are re-registered next, which is what lets a run submitted before a restart be picked up rather than replayed. Only then is it safe to cancel the scheduled runs of the projects that were not re-registered, and to delete their deployments — an order the other way round would cancel work this pod was about to resume. The surviving runs are adopted, and last, each served deployment's slot counter is zeroed if no run can be holding it: a project whose only slot is stranded would otherwise queue every run, a link included, for ever.
Never raises: a pod whose runner did not come up still serves tasks, it just cannot execute background DAGs, and saying so beats failing start-up.
stop_recovery
async def stop_recovery(self) ‑> None:Cancel the recovery poller and wait for it to unwind.
DatasourceUnreachableError
class DatasourceUnreachableError(*args, **kwargs):A background run was held back because its datasource cannot be reached.
Never raised: it is what the pod reports, through the hook a failed run
reports through, when it declines to submit a run whose indexed root is
offline. It is reported under error_code, so the desktop app can show
the runs as paused rather than as a failure.
Attributes
error_code: The stable code it is reported under.
Variables
- static
error_code : ClassVar[str]