Skip to main content

prefect_bootstrap

Idempotent Prefect bootstrapping for the metadata runtimes.

Every process that serves and triggers the file_metadata/scan_metadata deployments against a Prefect server must first ensure three things: a tag-based concurrency limit serialising cache writes, the zombie-flow-run reaper automation (self-hosted Prefect ships neither by default), and a heartbeat cadence fine enough for that automation to be accurate.

This is shared by the orchestrator (its embedded desktop-app server) and bitfount.scripts.run_pod (the sidecar server used in Docker), so the policy — and any future tuning of it — has one source of truth. The heartbeat frequency and the reaper's detection window are coupled (a window shorter than the cadence reaps healthy runs), which is exactly why they live in the same module.

What this module cannot ensure is that the reaper ever fires. Its pending detection window lives in Prefect's automation_bucket table and is swept on server restart, and it cannot witness a crash that took the server down in the same instant as the run — which is the normal shape of a laptop reboot or power cut here, since the server is a child of the same application as the pod. The client-side complement is bitfount.runtimes.recovery, which each process runs once at start-up: it judges liveness from the heartbeat stream rather than waiting to witness a transition, ends the runs that are provably gone, and resubmits them. The two are not redundant — the reaper handles the common case promptly while the process is up; recovery handles the case the reaper structurally cannot see.

Module​

Functions​

background_dag_silence_window​

def background_dag_silence_window() ‑> datetime.timedelta:

How long a background DAG run may go silent before it's presumed dead.

check_server_lease_storage​

async def check_server_lease_storage() ‑> str | None:

Report a Prefect server that keeps its concurrency leases in memory.

Reads the server's own settings (/admin/settings). In-memory storage is logged as an error and reported as prefect_lease_storage_in_memory: a server restart then strands every slot held, and nothing repairs them. Never raises.

Returns The server's lease storage module, or None when it cannot be read.

configured_limit_keys_from_pod_caches​

def configured_limit_keys_from_pod_caches(    pods_root: Path | None = None,) ‑> ConfiguredLimitKeys:

Read what every pod with a background cache under pods_root configures.

One Prefect server serves every pod on the machine, so a limit is stale only when no pod still configures what it is named for. A cache that cannot be opened or read, or no cache at all, leaves every prefix unjudged. Each cache is read without being written to (see _read_pod_cache).

Arguments

  • pods_root: The directory holding one directory per pod; defaults to the pods cache root.

Returns The union across pods.

ensure_background_dag_concurrency​

async def ensure_background_dag_concurrency(    ,) ‑> BackgroundDAGMigration:

Run migrate_background_dag_concurrency and report it as prefect_migration.

The start-up entry point for the orchestrator and run_pod.

Returns What changed.

ensure_filesystem_lease_storage​

def ensure_filesystem_lease_storage() ‑> None:

Keep the concurrency leases of a server this process starts on disk.

Sets PREFECT_SERVER_CONCURRENCY_LEASE_STORAGE unless already set, so a Prefect server started from this process (an ephemeral one included) inherits it. Has no effect on a server started elsewhere; see check_server_lease_storage.

ensure_heartbeat_frequency​

def ensure_heartbeat_frequency() ‑> None:

Pin PREFECT_FLOWS_HEARTBEAT_FREQUENCY before any serve() call.

Liveness detection is only as good as the heartbeat cadence underneath it. Prefect's default is 180 s (prefect.settings.models.flows), so a process that leaves it unset emits heartbeats less often than the zombie window below — and every long-running flow gets reaped mid-flight as a false positive.

Must be called before the deployments are served, because serve() runs each flow in a subprocess that inherits this environment. Uses setdefault, so an explicit operator override still wins.

ensure_zombie_automation​

async def ensure_zombie_automation() ‑> None:

Idempotently register — and reconcile — the zombie-reaper automation.

A killed flow run (e.g. a Windows Update reboot mid-walk, or a Docker container recycle) would otherwise sit at Running forever — nothing flips it. This registers a Proactive EventTrigger that fires when a flow run has gone silent for _zombie_window() and moves it to Crashed. See _desired_zombie_automation for why the trigger is shaped the way it is.

Unlike create_concurrency_limit, create_automation is not itself idempotent — calling it twice would create duplicate automations — so this is guarded by a name lookup (read_automations_by_name).

That guard cannot merely skip when a match is found, though: the automation lives in the Prefect server's DB and outlives any deploy, so a definition registered by an older version would otherwise persist forever and no fix to the spec above would ever reach an existing install. Instead we compare against the desired spec and update in place when it differs, which makes every startup self-healing.

leased_slots_in​

def leased_slots_in(    directory: Path, *, now: datetime | None = None,) ‑> dict[str, int] | None:

Count the slots each limit's leases hold, from Prefect's lease files.

Reads the files of Prefect's filesystem lease storage directly rather than through its API: listing expired leases there also repairs the expiration index, and this process must not write a store the server is writing. A lease file is replaced whole on every write, so each read sees one whole version. A lease revoked between the listing and the read is skipped, as it holds nothing.

Some lease files hold nothing Prefect will ever give back, and are not counted:

  • One Prefect cannot parse, such as a file a hard stop left empty. Renewing or releasing it deletes the file and decrements nothing, so the slot it was taken for stays taken whether or not its holder is alive.
  • One that has expired and that the expiration index no longer lists, as when a hard stop emptied the index. The repossessor finds expired leases only through the index, so it never revokes this one. An expired lease the index does list is counted: the repossessor will revoke it, and its revocation decrements the slot.

Arguments

  • directory: The lease storage directory.
  • now: The time to judge expiry against; defaults to the current time.

Returns Each limit id's leased slots, or None when the directory does not exist or a lease file or the index could not be opened (a live holder's lease may then be among them, so no limit can be judged unleased).

liveness_silence_window​

def liveness_silence_window() ‑> datetime.timedelta:

The longest a flow run may go silent before anything may presume it dead.

The public name for the window the reaper automation uses (the longer of the metadata and background-DAG windows). It is the upper bound on every client-side window: a client window longer than this would refuse to act on a run Prefect had already marked Crashed, while shorter ones (the metadata window) are safe because the reaper then only backstops them.

This matters because the reaper is not sufficient on its own: its pending detection window is swept on server restart, so after a machine-wide outage a dead run is never marked Crashed and a client must reach the same verdict from the heartbeat stream itself

metadata_silence_window​

def metadata_silence_window() ‑> datetime.timedelta:

How long a metadata flow run may go silent before it's presumed dead.

migrate_background_dag_concurrency​

async def migrate_background_dag_concurrency(    client: PrefectClient,) ‑> BackgroundDAGMigration:

Move the server from deployment-level background limits to scoped locks.

Idempotent, and run at every process start. In order:

  1. For each background DAG deployment with a concurrency limit, collapse its queued backlog (collapse_background_dag_backlog), then remove the limit. Collapse first: removing a limit with a queue behind it starts the whole queue at once.
  2. Delete deployment:<id> limits whose deployment is gone.
  3. Delete the retired background_dag_rerun limit.
  4. Upsert the pod-wide limits (background_dag_max_concurrent_runs, background_gpu_inference, background_ehr_connections) to the sizes the settings give, so a changed setting applies on the next start.

Each step is independent: one that raises is logged and recorded, and the rest still run.

Arguments

  • client: An open PrefectClient.

Returns What changed.

migrate_background_dag_deployment​

async def migrate_background_dag_deployment(handle: str) ‑> int:

Collapse and clear one project's background deployment before it is served.

Registering a deployment without a concurrency limit removes the one an earlier version gave it, and with it the queue held behind it; collapsing first is what stops that queue starting at once. Idempotent: a deployment without a limit, or not yet registered, is left alone.

Arguments

  • handle: The deployment's "<flow>/<deployment>" handle.

Returns How many queued runs were cancelled.

read_server_leased_slots​

async def read_server_leased_slots() ‑> dict[str, int] | None:

Read the slots the Prefect server's leases hold, when this process can.

Only a server keeping its leases on disk, under a home this machine can see, can be read: in-memory leases live in the server's own process. The directory is the one the server reports (/admin/settings), not this process's PREFECT_HOME, which the orchestrator does not share with the server it starts. The expiration index must exist beside the lease files, so a path that only happens to exist here (a server in another container) is not mistaken for the server's store. Never raises.

Returns Each limit id's leased slots, or None when they cannot be read.

release_unleased_concurrency_slots​

async def release_unleased_concurrency_slots(    read_leased_slots: LeasedSlotsReader | None = None,) ‑> list[UnleasedSlots]:

Release the slots of Bitfount's limits that no lease holds.

Every holder of a slot renews a lease on it, and Prefect frees a slot only by revoking its expired lease. The slot counter is in SQLite, but the lease files and their expiration index are written without being flushed, so a hard stop can lose a lease file, leave it empty, or empty the index. The repossessor then has no lease it can revoke, and the slot stays taken for ever: a background_publish:<project> limit left like that stops every run of the project at its publish step. This sets each counter back to what the leases Prefect can still release account for (leased_slots_in), and reports it.

Safe because it runs at start-up, before this process serves a run: a live holder elsewhere has its lease, so its slots are counted and kept, and no run here can take a slot between the read and the write. The leases are read before the counters, so a lease the repossessor revokes in between was already counted and its decrement is not repeated. An expired lease the index still lists counts too, since the repossessor will revoke it. Only the limits Bitfount's runs take are touched: the per-key metadata:*, background_lineage:* and background_publish:* limits, and the pod-wide ones. When the leases cannot be judged, nothing is released and that is reported (prefect_slots_unjudged). Never raises.

Arguments

  • read_leased_slots: Reads each limit id's leased slots; defaults to the server's own lease files (read_server_leased_slots).

Returns The limits whose slots were released.

remove_scan_chain_automation​

async def remove_scan_chain_automation() ‑> int:

Delete the retired file_metadata -> scan_metadata chain automation.

An index pass now submits its own scan, so a chain left registered by an older build would submit a second one on every Completed index run. Idempotent: nothing registered is a no-op.

Returns How many registrations were deleted.

Raises

  • Exception: Whatever the Prefect client raises. Callers treat a failure here as non-fatal and log it.

sweep_stale_keyed_concurrency_limits​

async def sweep_stale_keyed_concurrency_limits(    configured: ConfiguredLimitKeys,    prefixes: Iterable[str] = ('metadata:', 'background_lineage:', 'background_publish:'),) ‑> list[str]:

Delete per-key limits whose entity is gone and that hold no slot.

A per-key limit is created the first time it is acquired, so one is left behind for every datasource, lineage and project the pod has ever run. Stale means both: what the name is for is no longer configured on any pod (ConfiguredLimitKeys.is_configured), and the limit has no active slots. Deleting an idle limit loses nothing, since the next acquisition creates it again. A prefix configured cannot judge is skipped, with a warning.

Arguments

  • configured: What the pods still configure.
  • prefixes: The per-key prefixes to sweep.

Returns The names of the limits deleted.

sweep_stale_keyed_concurrency_limits_at_startup​

async def sweep_stale_keyed_concurrency_limits_at_startup(    pods_root: Path | None = None,) ‑> list[str]:

Release unleased slots, read every pod's configuration, then sweep.

Called once at start-up, by both processes that serve background runs, before either serves one. The slots no lease holds are released first (release_unleased_concurrency_slots): that is what a hard stop strands, and a stale limit stranded that way is then idle for the sweep. An unswept limit is harmless: it is one idle row, and the next acquisition of its key upserts it back to the right size (ensure_concurrency_limit), so a stale limit never blocks anything — it is only one more row to page through at the next start. A process that lives long enough to collect many is therefore a tidiness problem, not a correctness one.

Arguments

  • pods_root: The directory holding one directory per pod; defaults to the pods cache root.

Returns The names of the limits deleted.

Global variables​

  • LeasedSlotsReader - Reads, for each concurrency limit id, the slots the server's leases hold on it. None means they could not be read, which is not the same as none.

Classes​

BackgroundDAGMigration​

class BackgroundDAGMigration(    deployments_cleared: list[str] = [],    backlog_cancelled: int = 0,    orphan_limits_deleted: list[str] = [],    rerun_limit_deleted: bool = False,    limits_ensured: dict[str, int] = {},    failed_steps: list[str] = [],):

What migrate_background_dag_concurrency changed on the server.

Attributes

  • deployments_cleared: Background deployments whose concurrency limit was removed.
  • backlog_cancelled: Superseded queued runs cancelled before that.
  • orphan_limits_deleted: deployment:<id> limits whose deployment is gone.
  • rerun_limit_deleted: Whether the retired background_dag_rerun limit was deleted.
  • limits_ensured: The pod-wide limits upserted, with their sizes.
  • failed_steps: Steps that raised; each was logged and the rest still ran.

Variables​

  • backlog_cancelled : int
  • deployments_cleared : list[str]
  • failed_steps : list[str]
  • limits_ensured : dict[str, int]
  • orphan_limits_deleted : list[str]
  • rerun_limit_deleted : bool

ConfiguredLimitKeys​

class ConfiguredLimitKeys(    task_hashes: set[str] = set(),    lineages: set[tuple[str, str]] = set(),    projects: set[str] = set(),    unjudged: dict[str, set[str]] = {},    lineage_limit_names: set[str] = set(),):

What the pods on this Prefect server still have configured.

The per-key limits are named for these, and a limit naming none of them is stale.

Attributes

  • task_hashes: Task hashes of the datasources configured on a pod.
  • lineages: (project_id, task_hash) of every linked lineage whose datasource is still configured.
  • projects: Projects with at least one such lineage.
  • lineage_limit_names: The lineage limit name of each of lineages.
  • unjudged: The per-key prefixes some pod's configuration could not be read for, each with why. A sweep of such a prefix would delete the limits of the pod it missed, so the sweep skips it.

Variables​

  • complete : bool - Whether every per-key prefix can be judged.
  • lineage_limit_names : set[str]
  • lineages : set[tuple[str, str]]
  • projects : set[str]
  • task_hashes : set[str]
  • unjudged : dict[str, set[str]]

Methods​


add_pod​

def add_pod(    self,    configured: Iterable[tuple[str, str]],    links: Iterable[tuple[str, str]],    *,    snapshot_written: bool,    pod: str,) ‑> None:

Add what one pod's background cache has configured.

A pod that never wrote a datasource snapshot cannot say which datasources it configures, so the metadata prefix cannot be judged; nor can the lineage and publish prefixes if it has links. A pod whose snapshot has every datasource deconfigured configures nothing.

Arguments

  • configured: (datasource_name, task_hash) of each datasource still configured on the pod.
  • links: (project_id, datasource_name) of each linked lineage.
  • snapshot_written: Whether the pod has ever written a datasource snapshot, tombstoned rows included.
  • pod: The pod's name, for the skip report.

is_configured​

def is_configured(self, limit_name: str) ‑> bool | None:

Whether the entity limit_name is named for is still configured.

A lineage limit is matched on its whole name rather than split, since a project id could itself contain a colon.

Arguments

  • limit_name: A global concurrency limit's name.

Returns True or False for a per-key limit, None for any other limit.

mark_unjudged​

def mark_unjudged(self, prefixes: Iterable[str], why: str) ‑> None:

Record that prefixes cannot be judged, and why.

Arguments

  • prefixes: The per-key prefixes.
  • why: What could not be read.

UnleasedSlots​

class UnleasedSlots(limit_name: str, active_slots: int, leased_slots: int):

A concurrency limit whose taken slots outnumbered the leases on it.

Attributes

  • limit_name: The concurrency limit.
  • active_slots: The slots it read as taken.
  • leased_slots: The slots the server's leases account for, which it was set to.

Variables​

  • active_slots : int
  • leased_slots : int
  • limit_name : str