recovery
Recovery for metadata-runtime flow runs that died or whose process is gone.
The sibling of bitfount.flows.dag.recovery, separate from it not because of how
a run executes — both are deployment runs — but because of what replaying one
means. These runs are found by deployment_id, replayed verbatim from their own
parameters, and need their Prefect state and bookkeeping rows reconciled. A
background DAG run is found by its lineage tags — its deployment is per project
and is pruned when that project is no longer served — and is rebuilt by the pod
from a stored flow spec under an attempt bound. What the two share — the
candidate query, the ordering rule, the supersession verdict — lives in
bitfount.runtimes.discovery.
The submitters are one-shot — the orchestrator fires
_trigger_file_metadata_runtime once per pod start, run_pod once at startup —
and a dead index run submits no scan (bitfount.runtimes.metadata_convergence),
so without this sweep a run reaped mid-walk leaves its datasource unindexed and
unscanned until the nightly refresh. The sweep runs at process start and then
every metadata_recovery_interval seconds (PeriodicMetadataRecovery), judges
liveness itself, and resubmits.
A run is dead when Prefect has it Crashed, Failed or Cancelled, or when it
sits RUNNING (or Submitting) with its process gone. Per dead run:
- Establish there is nothing live. Per
(task_hash, run_type), a run genuinely executing means this pod is looking at its own healthy work and must not touch it. On a periodic sweep, aRUNNINGorSubmittingrun is acted on only once it was already judged dead on the sweep before: a laptop that slept through a tick wakes with every healthy run's heartbeat stale. - Reconcile. End a run still reading as live at
Crashedand fail itsrunningbookkeeping row. A permanently-RUNNINGrow is read by people as "still working", and the reaper cannot be relied on to fix it: it cannot observe a crash that took the Prefect server down with it, and its pending window is swept fromautomation_bucketon server restart. - Resubmit, on the ladder. A dead index is replayed unless another index run
for the task_hash is live; a dead scan is replayed only when no index is
expected and the inventory is current, since otherwise the index submits it.
Each replay is delayed per
TRANSIENT_RETRY_DELAYSand carries the dead run'stransient_retry:tag plus one, the ladder a partial pass climbs too. A run at the end of the ladder is not replayed;metadata_sweep_abandonedreports it and the nightly refresh starts the datasource again.
Replays, the ones made at process start included, are delayed per
TRANSIENT_RETRY_DELAYS. A run cancelled by anyone but the pod is not replayed.
Separately, a completed full index pass that no scan followed (its submission failed) gets its scan here, when the cache says the last scan predates it; and a partial scan that scheduled no follow-up (its submission failed) gets it here, on its ladder.
Module
Functions
collapse_background_dag_backlog
async def collapse_background_dag_backlog( client: PrefectClient, deployments: Iterable[Any],) ‑> int:Cancel every superseded SCHEDULED run of the given background deployments.
TODO: [BIT-8975] Migration only — delete once no project deployment registered with a concurrency limit can still hold a queued run. This is the bridge across the change ADR 0014 made; it has no job afterwards.
The background counterpart of collapse_scheduled_backlog, for a project
deployment that an earlier version registered with a concurrency limit:
its runs queued behind it as Scheduled(AwaitingConcurrencySlot), and
clearing the limit would start the whole queue at once. Grouped per
(deployment, task_hash, _background_work_key), keeping the newest run
of each group.
Arguments
client: An openPrefectClient.deployments: The deployments, asread_deploymentsreturns them.
Returns How many runs were cancelled.
collapse_scheduled_backlog
async def collapse_scheduled_backlog(client: PrefectClient) ‑> int:Cancel every superseded SCHEDULED run of the metadata deployments.
TODO: [BIT-8975] Migration only — delete when the metadata runtimes take
their metadata:<task_hash> lock inside the flow body and the
metadata_machine limit replaces the deployment limit (ADR 0014's
follow-up), which stops the backlog being created at all.
Runs once per process start, beside recover_lost_metadata_runs, which
discovers no SCHEDULED run — so nothing else collects one.
A backlog forms because a deployment's global_limit enqueues on collision:
when the slots are taken the server returns the run to
Scheduled(AwaitingConcurrencySlot), timed 30s out, and the runner logs
"Server returned a non-pending state 'SCHEDULED'" and leaves it. That much
is by design. What is not is that nothing drains it: ACTIVE_STATE_TYPES
counts SCHEDULED as live and is_flow_run_lost will not judge anything
pre-RUNNING, so a wedged run reads as live forever and permanently
suppresses resubmission for its task_hash — one more orphan per day under a
cron.
Keeps the newest of each group rather than ageing runs out. Every threshold
available here is wrong: a run waiting its turn is indistinguishable by age
from a wedged one, and liveness_silence_window() (300s) is orders of
magnitude shorter than the daily cron it would judge, so sizing from it would
cancel healthy queued work on every start.
Grouped per (deployment, task_hash, _work_key). Dropping any of the
three loses work: per deployment alone would cancel datasource B's queued
index because A had a newer one, and without the work key a scoped watcher
run would cancel a queued full walk.
Cancelling needs no bound, unlike the resubmission in
recover_lost_metadata_runs: it is terminal, so a collapsed group has one
run left and a second pass finds nothing. force is left off, matching
_end_run_as_crashed.
Arguments
client: An openPrefectClient.
Returns How many runs were cancelled.
end_stuck_refresh_runs
async def end_stuck_refresh_runs( client: PrefectClient, *, dead_before: datetime | None = None, own_pod_name: str | None = None,) ‑> int:End every stuck Submitting run of the daily refresh deployment.
This one's cron-scheduled and pod-wide rather than per-datasource, so it falls outside the usual recovery and slot-repair sweeps. Nothing needs resubmitting here, though — Prefect will create the next occurrence on its own schedule regardless, so all we need to do is end the stuck run and free up the slot it's holding.
Arguments
client: An openPrefectClient.dead_before: This process's own start time, so a stuck run left by our own recent restart is caught immediately. Only usable when own_pod_name isNone— see there for why.own_pod_name: Set by a caller that might be sharing this Prefect server with other pods. A refresh run has no per-pod identity to check it against (it refreshes every pod's stale datasources in one pass), so there's no way to tell "our" run from someone else's — the safe choice is to fall back to age alone rather than risk ending a run another pod's process still owns.
Returns How many runs were ended.
reconcile_metadata_runs_at_startup
async def reconcile_metadata_runs_at_startup( client: PrefectClient, *, dead_before: datetime | None = None, own_pod_name: str | None = None,) ‑> int:Run this module's whole start-of-process sweep, in order.
One entrypoint so that every process that recovers metadata runs recovers them the same way. The order is what makes each step useful:
collapse_scheduled_backlog— a queued run reads as live tois_flow_run_active, so a backlog suppresses the resubmission step 2 would otherwise make.recover_lost_metadata_runs— end and replay every per-datasource run that is dead. It also runs on its own between starts (PeriodicMetadataRecovery); the other steps do not. Ending a run is also what releases the concurrency slot it still held, so most of what step 4 exists for is gone by the time it runs.end_stuck_refresh_runs— the same idea, for the one deployment step 2 doesn't cover: the daily refresh run. Without this, a stuck refresh run would go unnoticed by every other step too.release_orphaned_deployment_slots— zero any slot counter that no surviving run can account for. Last, because a crash's runs sit atRUNNINGuntil step 2 ends them and aRUNNINGrun has to be read as holding its slot.
Putting step 4 last costs nothing even when a replacement run is submitted
while a counter is still stranded: such a run parks at
AwaitingConcurrencySlot with a 30-second scheduled retry rather than
failing, so it starts on its own once the counter is repaired.
Each step is independent of the others' success: one failing is logged and the rest still run.
Arguments
client: An openPrefectClient.dead_before: Passed torecover_lost_metadata_runsandend_stuck_refresh_runs.own_pod_name: Passed torecover_lost_metadata_runsandend_stuck_refresh_runs.
Returns How many replacement runs were submitted.
recover_lost_metadata_runs
async def recover_lost_metadata_runs( client: PrefectClient, *, dead_before: datetime | None = None, own_pod_name: str | None = None, suspects: set[uuid.UUID] | None = None,) ‑> int:Reconcile and replay every metadata run that is dead.
Runs at process start (reconcile_metadata_runs_at_startup) and on a timer
(PeriodicMetadataRecovery). Callers must treat a failure here as non-fatal
— indexing recovery is worth attempting, never worth blocking for.
A suspended laptop's healthy run looks exactly as dead as a crashed one,
because its heartbeat thread was suspended too. At process start that cannot
happen — a suspended machine is not starting processes. On a timer it can,
which is what suspects is for: a run is acted on only if it already looked
dead on the sweep before, and a run that resumed has heartbeats again by then.
generate_prefect_task_hash is per-pod, so this only ever touches runs of
this pod's datasources, and dead_before only ever raises the cutoff.
Arguments
client: An openPrefectClient.dead_before: This process's own start time. Without it the sweep cannot act on a fast restart: a run killed seconds before the restart has a heartbeat well inside the liveness window, so it reads as healthy, the sweep leaves it, the reaperCrashedes it moments later, and nothing re-indexes that datasource until the next sweep. A last heartbeat predating this process settles it — that run cannot be executing in a process that did not exist yet.own_pod_name: The pod this process serves, when it serves exactly one. dead_before is applied only to that pod's runs. Omitting it asserts this process owns every metadata run on this Prefect server — true of the orchestrator, whose Prefect server is its own child on a private port, and untrue of several pods sharing one sidecar server, where one pod starting would otherwise judge another's live runs dead.suspects: The periodic sweep's memory of runs that looked dead last time; see_find_lost_runs.Noneacts on every dead run at once.
Returns How many replacement runs were submitted.
release_orphaned_deployment_slots
async def release_orphaned_deployment_slots( client: PrefectClient, handles: Iterable[str] | None = None,) ‑> int:Zero each deployment's slot counter when no run can hold one.
Runs last in the start-of-process sweep, and that is load-bearing. The
crash this repairs leaves its runs sitting at RUNNING in the database, and
a RUNNING run is indistinguishable here from one that is really executing —
so run before recover_lost_metadata_runs this would find a slot-holder for
every stranded slot and refuse to touch a single one. Ending those runs is
what recover_lost_metadata_runs does, and Prefect releases each slot as it
goes: ReleaseFlowConcurrencySlots fires on the way out of RUNNING, and
when the run's lease is gone it decrements the deployment's counter directly
instead. So by the time this runs, the ordinary case has already healed and
what is left is the residue.
A deployment concurrency slot is two things that can disagree: an
active_slots counter in the Prefect database, and a lease the running flow
renews. A counter can therefore outlive every run that could account for it —
a lease store lost with the server, a PENDING run that died before it ever
reached RUNNING and so never transitions again, rows aged out from under
the counter. The repossessor service revokes expired leases, so with no
lease left there is nothing to expire and nothing ever decrements, and the
deployment reads as permanently full: every run submitted after it parks in
Scheduled(AwaitingConcurrencySlot). Cancelling that queue does not help,
because a queued run holds no slot — it was refused one.
Safe because of what it checks, not because of any threshold: the counter is
only zeroed when Prefect reports no run in a slot-holding state at all, so
anything recover_lost_metadata_runs judged live and left alone protects its
own slot. A lease that outlives this and expires later decrements from zero,
which the server floors rather than taking negative.
Also safe against a runner already serving the deployment, provided the counter is at its limit: a full counter refuses every new run a slot, so no run can take one between the holder check and the reset. A per-project background DAG deployment has a limit of 1, so any stranded counter is full.
Never raises: a failure here must not stop the sweep it belongs to.
Arguments
client: An openPrefectClient.handles: The"<flow>/<deployment>"handles to repair. Defaults to the metadata deployments.
Returns How many deployments had their counter reset.
start_periodic_metadata_recovery
def start_periodic_metadata_recovery( *, dead_before: datetime | None = None, own_pod_name: str | None = None,) ‑> PeriodicMetadataRecovery | None:Start periodic metadata recovery at metadata_recovery_interval.
Call once per process, after its start-up sweep. Never raises.
Arguments
dead_before: Passed torecover_lost_metadata_runs.own_pod_name: Passed torecover_lost_metadata_runs.
Returns
The running timer, or None when disabled or it could not start.
Classes
PeriodicMetadataRecovery
class PeriodicMetadataRecovery( *, interval: float, dead_before: datetime | None = None, own_pod_name: str | None = None,):Runs recover_lost_metadata_runs every interval seconds, on a thread.
One sweep at a time: a tick that comes due while the last sweep is still running is skipped, not queued. Started after the process's start-up sweep, beside it.
Arguments
interval: Seconds between sweeps;<= 0disables the timer.dead_before: Passed torecover_lost_metadata_runs.own_pod_name: Passed torecover_lost_metadata_runs.
Methods
run_once
def run_once(self) ‑> int | None:Run one sweep now, unless one is already running. Never raises.
Returns
How many replacement runs were submitted, or None when skipped or
failed.
start
def start(self) ‑> bool:Start the timer thread, unless disabled or already started.
Returns Whether a thread was started.
stop
def stop(self, timeout: float | None = None) ‑> None:Stop the timer, waiting up to timeout for a sweep in progress.
Arguments
timeout: Seconds to wait for the thread;Nonewaits indefinitely.