waves
Planning a waved background run: which files go through the DAG, and when.
A background run is normally handed the datasource's entire file list, and each step runs to exhaustion over it before the next one starts. Nothing downstream exists until the slowest step has swept everything, which on a large datasource is days. Waving cuts the sweep into batches that each go through the whole DAG, newest first, so the most recently scanned patients are recruitable in minutes.
The unit is a patient, not a file. A patient's eligibility verdict is reduced from every scan stored for them, so splitting their files across two waves would publish a verdict computed from part of their evidence and correct it silently several waves later. Cutting on patient boundaries removes that class of error entirely: within a sweep, no patient is ever judged on a subset of what the sweep found.
Two preconditions follow from that, and both are checked by WavePlanner
rather than assumed here:
- The scan sweep must be complete.
scan_metadatachunk-commits as it parses, so before it finishes a patient can be partly identified — three of their five scans have rows and two do not — and a wave cut then would split them after all. A patient's file set is only final once the sweep is. - The DAG must have something to narrow. Either a file-scoped step,
whose wave is a set of files, or a step reading
$ehr_patients.cache(ehr_screening_trial_v9: query, match, roll up), whose wave is a set of the EHR patient listing's IDs. The listing is resolved once, in setup, before the run is planned; a wave narrows only what$ehr_patients.cacheserves, so no wave issues a listing of its own. An EHR wave's ledger key isehr:<patient_id>, and it reads no scan identities, so neither the scan sweep gate nor scan coverage applies to it.
A datasource the scan sweep does not identify — anything not ophthalmology — has no patients to cut on, so every one of its files is an orphan, waved by file count in mtime order.
Recency is the patient's most recent acquisition time, from
scan_metadata.scan_datetime, falling back to the file's mtime. The fallback
matters less than the primary: the realistic onboarding case is a customer bulk
-copying a PACS archive, and cp without -p stamps every file with the copy
time, so an mtime-ordered sweep would deliver its waves in essentially arbitrary
order and the whole feature would be pointless on the datasource that needs it
most.
Which files are already finished comes from the dag_wave_ledger, because no
step's own partition answers it: the per-file calculation steps write a row for
every candidate including the ones they failed, and the eligibility steps are
patient-grain and hold no file id at all.
"Finished" is relative to a freshness horizon, which is what puts periodic reruns on this mechanism rather than beside it. A rerun exists to re-pull EHR data for patients whose files have not changed, so on a fully ledgered lineage a planner that only looked for unledgered files would plan nothing and the rerun would do nothing. Given a horizon, a ledger row older than it counts as outstanding again, and the ordinary patient chunking cuts the re-sweep into waves like any other — rather than the single unbounded pass over the whole datasource that a rerun used to get.
Re-swept patients are ordered by staleness, oldest refresh first, where new patients are ordered by recency. The horizon comes from the cron calendar and so moves at every occurrence; under recency ordering a datasource too large to re-sweep within one occurrence would redo its freshest patients every night and never reach its tail. Staleness ordering makes the sweep rotate instead, which is also what lets the horizon stay derived rather than persisted: there is no epoch to carry between runs.
Module
Functions
build_wave_plan
def build_wave_plan( *, dag: BackgroundDAG, cache: CacheProtocol, task_hash: str, project_id: str | None, run_id: str | None, context: FileMetadataContext, datasource: Any = None, rerun_horizon: datetime | None = None, should_yield: Callable[[], Awaitable[bool]] | None = None, update_hold: Callable[[], Awaitable[bool]] | None = None, now: datetime | None = None, ehr_patients: EHRPatientsContext | None = None,) ‑> WavePlan | None:Decide whether this run is waved, and plan its waves if so.
select_candidates then plan_from. Setup calls the two halves itself,
around its commit point; this is the one-call form for everything else.
Returns None — the executor's single pass — in two cases, each logged
once with its reason, because "why is this pod not waving?" is otherwise
unanswerable from the outside:
- Waving is disabled (
background_dag_wave_sizeis zero). - The DAG has nothing to hand a wave of (
is_waveable).
The candidates depend on wave_unit; see select_candidates.
Every other run is waved or does not run at all. The caller stands a run
down before this when the scan sweep is unsettled (sweep_unsettled), and
two outcomes here end the run instead of sweeping its selection unwaved:
- The scan sweep holds no row for any file an ophthalmology run selected:
NoScanCoverageErrorpropagates, after the lineage's uncarried rows are cleared and the error is reported, and the caller stands the run down. - Every selected file is exhausted:
CandidatesExhaustedErrorpropagates, after the error is reported, and the caller stands the run down. - Planning raises anything else:
WavePlanningErroris raised from it and the run fails, which the rerun failure limits bound.
A plan with no waves is not None: it means the run is waved and has
nothing outstanding, which the executor ends cleanly rather than sweeping.
Arguments
dag: The validated background DAG, with its step hashes stamped.cache: The pod's background cache.task_hash: The datasource-level task hash.project_id: The lineage's project, orNone.run_id: The flow run, banked on the ledger rows.context: The run's file-metadata provider.datasource: The datasource the steps share.rerun_horizon: The freshness horizon for a refresh run, orNone. A ledger row older than it is outstanding again, which is what makes a periodic rerun re-carry patients whose files have not changed. Also selects the wave size, since a refresh and a first sweep want different ones, and whether the run is budgeted.should_yield: Awaited between waves; truthy when non-rerun work is live elsewhere on this pod, so a refresh should stand aside.Nonewhen the caller has nothing to yield to.update_hold: Awaited between waves; truthy while an orchestrator update hold is in force, so any run should stop.Nonewhen the caller cannot ask.now: The current time, for the future clamp. Defaults to the wall clock; a parameter so tests need not freeze it.ehr_patients: The run's$ehr_patientsprovider, required for an EHR DAG and ignored otherwise.
Returns
The plan, or None when the run is not waved.
Raises
NoScanCoverageError: If no selected file has a scan row.CandidatesExhaustedError: If every selected file is exhausted.WavePlanningError: If planning failed for any other reason.
candidate_failure_limit
def candidate_failure_limit() ‑> int:Return how many abandoned waves drop a file from the candidate set.
background_dag_wave_retry_limit, floored at one so that a limit of zero
still lets a file be tried once.
Returns The number of abandonments after which a file is no longer planned.
clear_uncarried
def clear_uncarried( cache: CacheProtocol, dag: BackgroundDAG, project_id: str | None, task_hash: str,) ‑> None:Drop the lineage's uncarried rows, for a run whose candidate set is empty.
Called when a run ends with nothing selected, so the rows an earlier plan
left cannot keep the lineage due for an uncarried continuation. Rows at
the failure limit are kept. Raises only FencedOutError.
Arguments
cache: The pod's background cache.dag: The lineage's background DAG, with its step hashes stamped.project_id: The lineage's project, orNone.task_hash: The datasource-level task hash.
coverage_can_hold
def coverage_can_hold(dag: BackgroundDAG, datasource: Any) ‑> bool:Return whether a no_scan_coverage stand-down can hold dag's lineage.
Never for an EHR DAG, nor for a datasource the sweep does not identify: its files wave as orphans, so a stand-down recorded before they did is no reason to hold it.
Arguments
dag: The lineage's background DAG.datasource: The lineage's datasource, orNonewhen unknown.
due_for_wave_continuation
def due_for_wave_continuation( cache: CacheProtocol, dag: BackgroundDAG, task_hash: str, project_id: str | None, refresh_before: datetime | None = None, *, assume_swept: bool = False,) ‑> WaveContinuationReason | None:Return why dag's lineage needs a run scheduled, or None.
COLD_START when the scan sweep has finished and this DAG's ledger is
empty — no run has planned anything for this configuration, so the
sweep has not started. A planned sweep leaves a non-empty ledger. A run
that carried nothing (an empty selection) leaves it empty too, so a lineage
that has completed a run since the last scan sweep is not due: nothing it
could select has changed until the inventory is swept again. An EHR DAG
has no scan sweep: its cold start needs an empty ledger and either no
completed run or a complete listing snapshot, with patients in it, newer
than the one its last completed run read.
UNCARRIED when the ledger is not empty and holds an uncarried candidate:
a pending row, or a failed one under candidate_failure_limit. Those
rows are the planner's own candidate set as of its last plan, so a file the
planner would not plan — filtered out, unidentified, or abandoned too often
— never makes the lineage due. It terminates: every carried wave clears its
rows, and every abandoned one moves its files toward the limit.
REFRESH when the ledger is not empty but holds rows older than
refresh_before. This is what resumes a budgeted refresh across runs, and
it terminates: every carried wave moves its files' completed_at past the
horizon, so the stale count strictly decreases. A lineage whose waves keep
failing is bounded elsewhere — its work stays outstanding, on_success
never fires, and the growth trigger's give-up streak stands it down.
Cold start wins when more than one could apply, then uncarried: a lineage with an empty ledger has no rows to find anyway, and first-carry work goes before re-work.
The last precondition is what keeps this out of recovery's way. A sweep
that crashes after banking a wave is excluded from COLD_START by the
ledger, but one that crashes before its first wave lands leaves the ledger
empty and looks exactly like a cold start. Firing on it starts a fresh
attempt=1 lineage, and recovery decides supersession on start time across
the whole task hash (runtimes.recovery._is_superseded) — so the new run
masks the crashed one, the replay never happens, and the attempt chain
never advances.
Never raises: a cache it cannot read answers "not due", which costs a tick rather than a poller.
Arguments
cache: The pod's background cache.dag: The lineage's background DAG, with its step hashes stamped.task_hash: The datasource-level task hash.project_id: The lineage's project, orNone.refresh_before: The current freshness horizon, orNoneto ask about the cold start only.assume_swept: Answer as if the scan sweep had settled. For a caller that has already found it unsettled and wants to know whether the lineage would otherwise be due.
Returns
The reason a run should be scheduled now, or None.
ehr_ledger_key
def ehr_ledger_key(patient_id: str) ‑> str:Return the ledger key of the EHR listing's patient patient_id.
Arguments
patient_id: The EHR's own patient resource ID.
Returns
ehr:<patient_id>, which cannot collide with a file path.
is_waveable
def is_waveable(dag: BackgroundDAG) ‑> bool:Return whether dag has work to cut into waves.
True when any runnable step computes over the file inventory, or reads the
EHR patient listing through $ehr_patients.cache. A phase made only of
steps reading neither has nothing to hand a wave of, and the scope step does
not count.
Arguments
dag: The parsed background phase.
Returns Whether the DAG is waved.
ledger_shape_key
def ledger_shape_key(dag: BackgroundDAG, project_id: str | None) ‑> str:Return the DAG-configuration half of a lineage's ledger scope.
A digest over every runnable step's stamped Merkle task_hash and the
project. A step with no stamped hash contributes its name; the scope step
contributes neither. partition_key_for combines it with the datasource.
Arguments
dag: The background DAG, ideally with its step hashes stamped.project_id: The lineage's project, orNone.
Returns A 32-character hex digest.
listing_read_tags
def listing_read_tags(listing: EHRPatientListing) ‑> dict[str, str]:Return the run-row tags recording that a run read listing.
Arguments
listing: The snapshot the run's$ehr_patientsserved.
occurrence_bucket
def occurrence_bucket(now: datetime) ‑> datetime.datetime:Return the occurrence the once-per-occurrence reporting is scoped to.
The latest rerun occurrence, or the day when the cron has none or cannot be read.
Arguments
now: The current time.
Returns The bucket's start.
partition_key_for
def partition_key_for(dag: BackgroundDAG, project_id: str | None, task_hash: str) ‑> str:Return the ledger scope of dag's lineage on task_hash under project_id.
Derived from the DAG's shape (ledger_shape_key) and the datasource, so a
config change anywhere in the DAG moves the key and the datasource re-waves,
and each datasource linked to a project keeps its own ledger. The datasource
is needed because the step hashes alone do not tell two datasources of one
type apart: a step keyed per file hashes the datasource type
(bitfount.flows.dag.hashing).
Arguments
dag: The background DAG, ideally with its step hashes stamped.project_id: The lineage's project, orNone.task_hash: The datasource-level task hash.
Returns A 32-character hex digest.
plan_from
def plan_from( selection: WaveSelection, *, dag: BackgroundDAG, task_hash: str, project_id: str | None, rerun_horizon: datetime | None = None, should_yield: Callable[[], Awaitable[bool]] | None = None, update_hold: Callable[[], Awaitable[bool]] | None = None,) ‑> WavePlan:Plan the waves of selection and record what it leaves uncarried.
The second half of build_wave_plan, after the run has committed. Each
wave narrows the selection's provider and datasource.
Arguments
selection: What the run may plan, fromselect_candidates.dag: The DAG being planned.task_hash: The datasource-level task hash.project_id: The lineage's project, orNone.rerun_horizon: The freshness horizon of a refresh, orNone.should_yield: Whether a budgeted refresh should stand aside, orNonewhen the caller has nothing to yield to.update_hold: Whether an orchestrator update hold is in force, orNonewhen the caller cannot ask.
Returns The plan.
Raises
WavePlanningError: If planning failed.
plan_waves
def plan_waves( candidates: Sequence[WaveCandidate], ledgered: Mapping[str, datetime | None], wave_size: int, now: datetime, refresh_before: datetime | None = None,) ‑> list[Wave]:Cut candidates into the waves a run should carry through the DAG.
Patients come first, then orphans — files the scan sweep could not identify,
which are waved rather than skipped: they still settle as missing_data:
rows as they do today, and they are in the published coverage denominator,
so a sweep that never banked them would report itself permanently
incomplete. Within each, work the ledger has never carried comes before
work it carried too long ago.
Four groups, in this order:
- Patients with any unledgered file, newest scan first. This is what makes a newly linked dataset recruitable in minutes, and it is the only group a link, a recovery or a cold-start continuation ever has.
- Patients whose every file is ledgered but whose oldest completion predates refresh_before, oldest refresh first. Empty without a horizon.
- Unledgered orphans, then 4. stale orphans, on the same rule.
- Retry waves: every unit of groups 1 and 3 holding a file an earlier run
abandoned (
WaveCandidate.failure_count), one unit per wave, patients then orphans, in the order they held above. Alone, so that when the wave is abandoned again the count rises on the file that fails and not on the files that merely shared its wave: waves are cut deterministically, so one file that always fails would otherwise take every file around it tocandidate_failure_limitand out of planning. Last, so first-carry work nobody has tried still goes first.
A patient with any outstanding file is re-waved whole. The boundary is the point — a verdict must be computed with the patient's entire scan set in front of it — and the files already done cost almost nothing, since every step skips its own cached work.
Within every group, a unit holding a file with a WaveCandidate.size_cap
keeps its wave to that many units. A wave that timed out caps its files at
half its units, so the next run carries them in smaller waves, in their
usual place, until they are carried.
Group 2 is how a rerun is expressed. It replaces a trailing wave over every candidate, which was unbounded by construction and carried the run's new patients a second time, having already carried them in group 1.
Arguments
candidates: Every file in the run's selection.ledgered: What the ledger holds for this scope: file path to completion time,Nonewhere the stored time could not be read.wave_size: Patients per wave, and files per orphan wave.now: The current time, for the future clamp.refresh_before: The freshness horizon. A file carried earlier is outstanding again, which is what makes a periodic rerun re-carry patients whose files have not changed.Nonefor every trigger that is not a refresh, leaving groups 2 and 4 empty and this function's behaviour exactly what it was before horizons existed.
Returns The waves, indexed from 1. Empty when nothing is outstanding.
Raises
ValueError: If wave_size is not positive. Zero disables waving upstream and must never reach here; waves of no patients would never terminate.
scan_sweep_complete
def scan_sweep_complete(cache: CacheProtocol, task_hash: str) ‑> bool:Return whether scan_metadata has swept a settled inventory.
Waving may not start before it has, for two reasons that are really one: a wave is cut on patient boundaries, and a patient's file set is only final once everything that produces it has finished.
scan_metadata chunk-commits as it parses, so mid-sweep a patient can be
partly identified — three of their five scans have rows and two do not —
and a wave cut then would split them, publishing a verdict computed from
part of their evidence and correcting it silently several waves later.
The inventory underneath moves the same way. file_metadata persists its
walk in chunks, so rows exist long before all of them do, and "the
inventory has rows" is true within seconds of a first index starting. Only
the run finishing says the file set is settled.
Hence the ordering rather than two existence checks: the sweep counts only if it finished after the last index walk to complete. Only completed bookkeeping rows are compared, so this rejects an index never run, a sweep that stood down for a half-built inventory (which completes its bookkeeping row having written nothing, and so predates the index it stood down for), and a re-index that has landed new files no sweep has identified yet. An index still running is not seen: until it completes, the gate answers from the previous walk and the sweep that followed it.
A sweep that ran and wrote nothing still passes here — the datasource may
simply not be ophthalmology. That is a question about this run's own files
against a pod-wide table, so WavePlanner.candidates asks it instead and
raises NoScanCoverageError.
Neither side counts a run that did not touch the inventory: an index pass
that found nothing changed, or a scan that skipped because its inventory
was not current (bitfount.runtimes.metadata_markers). A nightly no-change
pass therefore leaves the gate as the last walk and sweep left it.
Two completions that share a timestamp are not ordered, so they answer
"not swept" as well. Windows stamps datetime.now from a ~15.6ms-grained
clock, and a sweep that stood down writes its bookkeeping row within that
of the index it stood down for — the tie that must not read as a sweep. A
sweep that truly read the inventory parses it first, so it lands ticks
later and keeps its order.
Never raises. A cache it cannot read answers "not swept", which stands the
run down — waving is how every waveable run carries its files, so there is
no single pass to fall back to. The read error is logged and reported as
scan_sweep_gate_unreadable, once per task hash per rerun occurrence, so a
persistent one is visible rather than a silent permanent stand-down.
Arguments
cache: The pod's background cache.task_hash: The datasource-level task hash.
Returns
Whether a scan_metadata run completed strictly after the last
file_metadata run did.
select_candidates
def select_candidates( *, dag: BackgroundDAG, cache: CacheProtocol, task_hash: str, project_id: str | None, run_id: str | None, context: FileMetadataContext, datasource: Any = None, rerun_horizon: datetime | None = None, now: datetime | None = None, ehr_patients: EHRPatientsContext | None = None,) ‑> WaveSelection | None:Decide whether this run is waved and, if so, what it may plan.
The first half of build_wave_plan, up to the point a run commits: the
stand-downs are decided here, and a run that gets past this has work.
The candidates depend on wave_unit. A file DAG's are the selected
inventory files, joined to the scan sweep's patients on an ophthalmology
datasource and all orphans otherwise. An EHR DAG's are the listing
snapshot's patient IDs, keyed ehr:<patient_id>, and its waves narrow
ehr_patients rather than the file provider.
Arguments
dag: The DAG being planned.cache: The pod's background cache.task_hash: The datasource-level task hash.project_id: The lineage's project, orNone.run_id: The run's row, recorded on the rows it plans.context: The run's$file_metadataprovider.datasource: The datasource the steps share.rerun_horizon: The freshness horizon of a refresh, orNone.now: The current time; defaults to the wall clock.ehr_patients: The run's$ehr_patientsprovider, required for an EHR DAG and ignored otherwise.
Returns
The selection, or None when the run is not waved (waving disabled, or
the DAG has nothing to cut into waves).
Raises
NoScanCoverageError: If no selected file has a scan row.CandidatesExhaustedError: If every selected file is exhausted.WavePlanningError: If selecting failed for any other reason.
sweep_unsettled
def sweep_unsettled(cache: CacheProtocol, dag: BackgroundDAG, task_hash: str) ‑> bool:Return whether a run must stand down until the scan sweep settles.
True for a waveable file DAG, with waving enabled, whose scan sweep has not read the current inventory — a first index, or a re-index that has landed files no sweep has identified yet. What the ledger holds does not matter: a wave cut now could split a patient, and the single pass this used to fall back to would compute and publish over an inventory with no settled identities.
The scheduler asks the same question before submitting a run, so this is a backstop for runs that raced the gate or were submitted by something else.
Always false for an EHR DAG, which reads no scan identities.
Never raises: a cache it cannot read answers True, and
scan_sweep_complete reports the read error.
Arguments
cache: The pod's background cache.dag: The lineage's background DAG.task_hash: The datasource-level task hash.
Returns Whether the run should end without running any step.
wave_scope
def wave_scope(context: WaveScopeProvider, datasource: Any, wave: Wave) ‑> Iterator[None]:Scope a run to wave for the duration of the block.
Sets both channels a file scope travels down, from one value:
FileMetadataContext, which serves$file_metadata.cacheand.recordsto every step that reads them; anddatasource.selected_file_names_override, becausemodel_inferencedoes not readfilenamesat all — it iteratesdatasource.selected_file_names_iter(), andselection.select_for_datasourcenever consults the override. Scoping only the context would leave the most expensive step in the DAG running full-sweep on every wave, which is worse than not waving at all.
Both are restored on the way out, on the raising path too. The override in
particular leaks for the lifetime of the process otherwise:
clear_task_specific_configs does not clear it, which is why
bitfount.federated.worker already resets it in a finally.
Arguments
context: The run's file-metadata provider.datasource: The datasource the steps share, orNonewhen there is none. Typed loosely because this probes for the override attribute rather than requiring aBaseSource: a source that cannot be selected by file name simply does not carry it.wave: The wave to scope to.
Raises
ValueError: If wave holds no files. An empty override is falsy, andselected_file_names_iterreads that as "no override" and walks the whole datasource — so an empty wave would silently process everything rather than nothing.
wave_unit
def wave_unit(dag: BackgroundDAG) ‑> WaveUnit | None:Return what dag's waves are cut from, or None when it is not waveable.
EHR when any runnable step reads $ehr_patients.cache; otherwise FILE
when any computes over the file inventory; otherwise None. The EHR case
wins: a DAG reading the listing runs on a NullSource, so it has no
inventory to cut.
Arguments
dag: The parsed background phase.
Returns
The wave unit, or None.
Global variables
CANDIDATES_EXHAUSTED-stop_reasonof a run that stood down because every selected file was abandonedcandidate_failure_limittimes.
DUPLICATE_LINEAGE_RUN-stop_reasonof a run a lock gate turned away before it could look.
EHR_LISTING_KEY_TAG- The run-row tags naming the EHR listing, and the snapshot of it, that a background run's$ehr_patientsserved.
MACHINE_BUSY-stop_reasonof a run no machine slot freed for.
NO_SCAN_COVERAGE-stop_reasonof a run that stood down because no selected file had a scan row.
SLOT_TIMEOUT-stop_reasonof a run no concurrency slot freed for, before the deployment limits were dropped. Read from rows an older build wrote; no run writes it, andStopReasonhas no member for it.
SWEEP_UNSETTLED-stop_reasonof a run that stood down because its scan sweep was unsettled.
WAVE_PLAN_FAILED-stop_reasonof a run whose wave planning raised.
Classes
CandidatesExhaustedError
class CandidatesExhaustedError(*args, **kwargs):Raised when every file a run selected has been abandoned too often.
The run has nothing it may plan, and running it anyway would complete with no waves and bank the inventory cursor as if the sweep were done. It stands down instead, so the lineage stays visibly stuck until a newer index walk changes its selection or a configuration change re-arms the files.
NoScanCoverageError
class NoScanCoverageError(*args, **kwargs):Raised when the scan sweep holds nothing for the files this run selected.
The scan table is pod-wide but a sweep is per-datasource, and the sweep only runs for ophthalmology sources. An ophthalmology run whose own files have no scan rows has no patient identities to wave by, so it stands down without running a step rather than sweeping the whole selection unwaved. Waving those files as orphans would split patients. A datasource that is not ophthalmology never gets here: its files are waved as orphans.
Wave
class Wave( index: int, candidates: tuple[WaveCandidate, ...], is_orphan_wave: bool = False, is_refresh_wave: bool = False, is_retry_wave: bool = False,):One batch of files to carry through the whole DAG.
Attributes
index: The wave's position in its sweep, from 1. Reported in the logs and banked in the ledger.candidates: The files, in a stable order.is_orphan_wave: Whether this wave holds files with no patient identity. They still go through every step and still settle asmissing_data:rows, but a step that logs loudly when nothing loads is expected to do so here, so the loop can downgrade that one line.is_refresh_wave: Whether this wave re-carries files the ledger already holds, rather than carrying them for the first time. What makes the two recoverable by different triggers, and so whatWavePlan.left_work_outstandingturns on: a refresh wave left undone is visible to the scheduler as a stale ledger row, while a first-carry wave left undone is visible only as inventory the growth cursor has not reached.is_retry_wave: Whether this wave holds one unit — a patient's files, or an orphan file — that an earlier run abandoned. Planned alone, so another abandonment counts against the file that fails rather than against every file that happened to share its wave.
Variables
-
candidates : tuple[WaveCandidate, ...]
file_paths : tuple[str, ...]- The wave's files, in the order they were planned.
-
index : int
-
is_orphan_wave : bool
-
is_refresh_wave : bool
-
is_retry_wave : bool
-
unit_count : int- How many units the wave holds: its patients, plus each orphan file.The quantity
wave_sizecounts, so the one a timed-out wave is halved by.
Methods
ledger_records
def ledger_records( self, completed_at: datetime, run_id: str | None,) ‑> list[WaveLedgerRecord]:Build the ledger rows banking this wave as finished.
Arguments
completed_at: When the wave finished.run_id: The flow run that carried it.
Returns One record per file in the wave.
WaveCandidate
class WaveCandidate( file_path: str, bitfount_patient_id: str | None = None, scan_datetime: datetime | None = None, modified_at: datetime | None = None, failure_count: int = 0, size_cap: int | None = None,):One file the sweep may carry through the DAG.
Attributes
file_path: The file, asfile_metadataspells it.bitfount_patient_id: The patient it belongs to, orNonewhen the scan sweep could not identify one — an orphan.scan_datetime: The acquisition time, orNone.modified_at: The file's mtime, used only when there is no acquisition time to order by.failure_count: How many runs abandoned a wave holding this file since it was last carried, from the ledger. A positive count puts the file's unit in a retry wave of its own (plan_waves).size_cap: The most units a wave holding this file may carry, from the ledger, orNonefor no cap. Set when a wave holding the file timed out, so it is planned smaller until it is carried.
Variables
-
bitfount_patient_id : str | None
-
failure_count : int
-
file_path : str
-
modified_at : datetime.datetime | None
-
scan_datetime : datetime.datetime | None
-
size_cap : int | None
WaveContinuationReason
class WaveContinuationReason(*args, **kwds):Why a lineage needs a background run scheduled outside its triggers.
Not collapsed into one boolean, because they are scheduled differently. First-carry work — a cold start or an uncarried candidate — is work nobody has done, so it is not stamped as a rerun; a refresh is discretionary re-work and is.
Attributes
COLD_START: The sweep has never begun. ADATASET_PROJECT_LINKEDrun is scheduled immediately and is gated on neither metadata runtime, so it can arrive before the scan sweep has settled, whensweep_unsettledstands it down without running a step. Without this the lineage would sit idle until the next cron occurrence.UNCARRIED: The sweep has begun and the ledger holds a candidate no wave has carried: a run planned it and stopped, or abandoned its wave fewer thancandidate_failure_limittimes. Nothing else resumes first-carry work on a lineage whose ledger is not empty.REFRESH: The sweep has begun but the lineage still holds ledger rows older than the current freshness horizon. The normal state of a budgeted refresh part way through: the run that carried the last slice ended on purpose, and this is what carries the next.
Ancestors
WaveLedgerWriter
class WaveLedgerWriter(*args, **kwargs):The part of the planner a running sweep drives.
The executor's only dependency on planning is "this wave finished, record it". Naming that one method keeps the loop testable without a cache, and keeps the loop from reaching into the planner for anything else.
Ancestors
Methods
count_uncarried
def count_uncarried(self) ‑> int:Return how many candidates the lineage still has to carry.
mark_complete
def mark_complete(self, wave: Wave, completed_at: datetime) ‑> None:Bank wave as carried through the whole DAG.
mark_failed
def mark_failed(self, wave: Wave, failed_at: datetime) ‑> None:Record that wave was abandoned.
mark_oversized
def mark_oversized(self, wave: Wave) ‑> int:Record that wave ran out of time; return the cap its files now carry.
WavePlan
class WavePlan( waves: list[Wave], planner: WaveLedgerWriter, context: WaveScopeProvider, datasource: Any = None, retry_limit: int = 2, last_error: Exception | None = None, banked_waves: int = 0, waves_started: int = 0, deferred_files: int = 0, wave_budget: int | None = None, should_yield: Callable[[], Awaitable[bool]] | None = None, update_hold: Callable[[], Awaitable[bool]] | None = None, unstarted_waves: list[Wave] = [], uncarried_at_start: int | None = None,):A run's planned waves, plus what it needs to run and bank them.
Carried on DAGRunContext so the executor can loop without knowing how a
wave was chosen or where it is recorded.
Attributes
waves: The waves, in order.planner: Banks a finished wave in the ledger.context: The run's file-metadata provider — one of the two channels a wave's scope travels down, and the holder of the cumulativecoveredlist the published coverage figure reads.datasource: The datasource the steps share, the other channel. Typed loosely becauseDAGRunContextis a pydantic model carrying this, and aBaseSourceannotation would force it to resolve a name this module only imports for type checking.retry_limit: How many times a failing wave is retried before the run gives up on it and moves to the next.last_error: The most recent wave failure, kept so a run in which every wave failed can re-raise something specific rather than a summary.banked_waves: How many waves this run actually finished and recorded. Fewer than it planned means a wave exhausted its retries and its files were not carried.waves_started: How many waves the loop has entered, banked or not. The sweep's position, wherebanked_wavesis its success count: a run that abandoned a wave is still past it, and the coverage figure reporting what is left has to count down from here or it reports the last wave of the sweep as having one still to come.deferred_files: How many selected files the planner left out because the scan sweep had not reached them. They are outstanding work like an abandoned wave's files, and for the same reason: nothing has carried them yet.wave_budget: How many waves this run may carry before it ends and leaves the rest to a later one, orNonefor no bound. What stops a refresh holding the machine for hours; seeconfig.background_dag_rerun_wave_budget.should_yield: Awaited after each banked wave, and truthy when work that is not a rerun is live elsewhere on the pod. The rerun then ends early rather than competing with it. Awaitable because the DAG runs in its own process, so the only thing that can answer it is a Prefect query.Nonewhen nothing can be yielded to.update_hold: Awaited after each banked wave, and truthy while an orchestrator update hold is in force. The run then ends, first sweeps included, so the desktop app can install its update.Nonewhen the caller cannot ask.unstarted_waves: Waves this run deliberately did not begin, having spent its budget, stood aside, stopped for an update hold, or stopped on a failure that retrying cannot fix. Counted apart from failures: they are a scheduling decision, not a fault.uncarried_at_start: How many candidates were left to carry once the run had planned, fromWaveLedgerWriter.count_uncarried, orNonewhen it could not be read.made_progresscompares the same count at the end against it.
Variables
-
abandoned_waves : int- How many waves this run started and could not carry.A wave that exhausted its retries, as distinct from one the run never began: deferring work is a scheduling decision, abandoning it is a fault. The failure streak counts on that distinction — a lineage that abandons a wave has not finished what it started, however much else it got through.
Returns: The count, zero when every started wave was banked.
-
banked_waves : int
-
context : WaveScopeProvider
-
datasource : Any
-
deferred_files : int
-
last_error : Exception | None
-
left_work_outstanding : bool- Whether this run finished with first-carry work it did not carry.What the inventory cursor turns on: it records how much of the datasource a completed run saw, so a run that failed a wave, or left files out for want of a scan row, must not advance it. Banking the whole inventory there would make the files it never reached stop looking new, and the growth trigger — which fires on the inventory growing past the cursor — would never bring them back.
Refresh waves are the exception, and the distinction is load-bearing rather than a nicety. The two kinds of unfinished work are recovered by different triggers: a refresh wave left undone is a stale ledger row, which the scheduler can see and reschedule directly, while a first-carry wave left undone has no ledger row at all and is invisible to that check — its only safety net is the growth trigger, which the cursor disarms. So a budgeted run that carried every first-carry wave has covered the datasource and may bank the cursor, however much refreshing is left; one that stopped short of a first-carry wave has not.
A plan with no waves at all left nothing behind: every file was already carried and fresh, so the run covered the datasource by having nothing to do.
Returns: Whether work this run was meant to carry is still outstanding.
-
planner : WaveLedgerWriter
-
retry_limit : int
-
should_yield : collections.abc.Callable[[], collections.abc.Awaitable[bool]] | None
-
uncarried_at_start : int | None
-
unstarted_waves : list[Wave]
-
update_hold : collections.abc.Callable[[], collections.abc.Awaitable[bool]] | None
-
wave_budget : int | None
-
waves : list[Wave]
-
waves_started : int
Methods
made_progress
def made_progress(self) ‑> bool:Return whether this run moved its lineage's sweep forward.
True when the run carried every wave it planned, or carried at least one and left fewer candidates to carry than it found. A run that stopped short without carrying anything, for whatever reason, did not — nor did one whose waves all failed, nor one whose carried waves were outweighed by new work. Decided on what was carried rather than on why the loop stopped, so a new reason to stop needs no change here.
An end count that cannot be read counts as progress for a run that carried a wave: the counter this feeds stands a lineage down, and a cache read error is not evidence the lineage is stuck.
Returns Whether the run made progress.
WavePlanner
class WavePlanner( cache: CacheProtocol, partition_key: str, project_id: str | None, wave_size: int, run_id: str | None = None, rerun_horizon: datetime | None = None,):Plans a run's waves and scopes the run to one at a time.
Owns the cache reads planning needs — the scan identities, the ledger — and
the two channels a wave's scope has to reach. Built once per run in
bitfount.flows.dag.setup, and None when waving is disabled or the DAG is
not waveable, which is how the executor takes its untouched path.
candidates is the lineage's candidate set, and the ledger's pending and
failed rows are its uncarried part, written by record_uncarried each
time a run plans. The scheduler's uncarried check and the progress count
both read those rows, so all three agree on what "uncarried" means.
Arguments
cache: The pod's background cache.partition_key: The digest over the DAG's stamped step hashes, scoping the ledger so a config change re-waves the datasource.project_id: The lineage's project, orNone.wave_size: Patients per wave.run_id: The flow run, banked on the ledger rows.rerun_horizon: The freshness horizon, orNonewhen this run is not a refresh. Passed toplan_waves, where it decides whether a fully-ledgered patient is outstanding again.
Initialise the planner (see the class docstring).
Methods
candidates
def candidates( self, records: Iterable[FileMetadataRecord],) ‑> list[WaveCandidate]:Build the run's candidates from its inventory rows.
Joins each file to what the scan sweep found for it: the patient it belongs to and when it was acquired. A file whose rows carry no usable name and date of birth becomes an orphan — ordered last and waved by file count rather than by patient.
A file the sweep has produced no row for is left out of the run entirely. It is not an orphan, it is unfinished: the sweep runs on its own schedule and the inventory moves under it, so a file indexed since the last sweep has nothing to identify it yet. Waving it would bank it in the ledger under no patient, and the ledger is what stops a file being waved twice — so a returning patient's new scans would be carried without them and never judged alongside the rest of their evidence. Left out, they wave with the patient on the run after the sweep catches up.
A file whose wave has been abandoned candidate_failure_limit times is
left out as well, so a wave that fails for ever stops being planned. A
file abandoned fewer times carries its count, and is planned in a retry
wave of its own.
Arguments
records: The run's selected inventory rows, from$file_metadata.records.
Returns One candidate per inventory row the scan sweep has reached.
Raises
NoScanCoverageError: If the sweep holds no row for any file this run may plan. The scan table is pod-wide, so another datasource's rows are no evidence that this one was swept: a pod running one ophthalmology datasource alongside one that is not would otherwise wave the second on the first's rows, defer every file for want of an identity, and process nothing at all. Raised ahead ofCandidatesExhaustedError: a deferred file is work the next sweep may identify.CandidatesExhaustedError: If every identified file is exhausted and none is deferred. Running on would plan no waves and complete as if the sweep were done.
count_uncarried
def count_uncarried(self) ‑> int:Return how many candidates this lineage still has to carry.
The uncarried candidates, plus, for a refresh, the carried files older than its horizon.
Returns The count.
ehr_candidates
def ehr_candidates( self, patient_ids: Iterable[str],) ‑> list[WaveCandidate]:Build the run's candidates from the EHR patient listing snapshot.
One candidate per distinct patient ID, keyed ehr:<patient_id> and
standing as its own patient, so wave_size counts listing patients and
a patient is never split. With no recency to order by, waves follow
the keys' sorted order, which is stable from run to run.
Arguments
patient_ids: The snapshot's patient IDs.
Returns The candidates, less the retry-exhausted ones.
Raises
CandidatesExhaustedError: If every listed patient is exhausted. Running on would plan no waves and complete as if the listing were carried.
identities
def identities(self) ‑> ScanIdentitySource:Return per-file identity and recency, from one pass over the scans.
Returns The source the candidates are built from.
ledgered
def ledgered(self) ‑> dict[str, datetime.datetime | None]:Return what the ledger holds as carried for this scope, with its timestamps.
One read answering both of the caller's questions: which files have ever been carried — the cumulative coverage figure's starting point — and when, which is what a refresh measures against its horizon.
Returns
File path to completion time, None where it could not be read.
mark_complete
def mark_complete(self, wave: Wave, completed_at: datetime) ‑> None:Bank wave in the ledger as carried through the whole DAG.
Called only once the wave's steps have all returned.
Arguments
wave: The finished wave.completed_at: When it finished.
mark_failed
def mark_failed(self, wave: Wave, failed_at: datetime) ‑> None:Record in the ledger that wave was abandoned.
Its files stay uncarried and the next run retries them, until a file's
count reaches candidate_failure_limit.
Arguments
wave: The abandoned wave.failed_at: When it was abandoned.
mark_oversized
def mark_oversized(self, wave: Wave) ‑> int:Record in the ledger that wave ran out of time.
A timeout says the wave was too big for this datasource on this machine, not that its files are bad, so it adds to no failure count. Its files are capped at half its units instead, and the next run carries them in waves of at most that many, until they are carried.
Arguments
wave: The timed-out wave.
Returns The cap written: half the wave's units, and never less than one.
orphan_candidates
def orphan_candidates( self, records: Iterable[FileMetadataRecord],) ‑> list[WaveCandidate]:Build the run's candidates for a datasource the scan sweep does not identify.
Every file is an orphan: waved by file count, newest mtime first, through the same orphan path as a file the sweep could not identify.
Arguments
records: The run's selected inventory rows.
Returns One orphan candidate per row, less the retry-exhausted ones.
Raises
CandidatesExhaustedError: If every file is exhausted. Running on would plan no waves and complete as if the sweep were done.
plan
def plan( self, candidates: Sequence[WaveCandidate], now: datetime, ledgered: Mapping[str, datetime | None] | None = None,) ‑> list[Wave]:Plan this run's waves from its candidates.
Arguments
candidates: The run's candidates, fromcandidates.now: The current time, for the future clamp.ledgered: What the ledger holds as carried, when the caller has already read it.build_wave_planhas, because it also seeds the run's coverage figure from it, and the ledger is the largest read planning does.
Returns The waves, indexed from 1.
record_uncarried
def record_uncarried( self, candidates: Sequence[WaveCandidate], ledgered: Mapping[str, datetime | None], *, planned_at: datetime,) ‑> None:Write the candidates no wave has carried to the ledger as pending.
Also drops uncarried rows for files that are no longer candidates, so the ledger's uncarried rows are exactly this plan's.
Arguments
candidates: The run's candidates, fromcandidates.ledgered: What the ledger holds as carried.planned_at: When the run planned.
waves
def waves( self, records: Iterable[FileMetadataRecord], now: datetime, ledgered: Mapping[str, datetime | None] | None = None,) ‑> list[Wave]:Plan this run's waves from its inventory rows.
Arguments
records: The run's selected inventory rows.now: The current time, for the future clamp.ledgered: What the ledger holds as carried, when the caller has already read it.
Returns The waves, indexed from 1.
WavePlanningError
class WavePlanningError(*args, **kwargs):Raised when planning a run's waves fails, ending the run Failed.
Wraps what planning raised, so the flow can tell this failure from any other
in setup and report stop_reason="wave_plan_failed".
WaveScopeProvider
class WaveScopeProvider(*args, **kwargs):The part of the file-metadata provider a wave scope drives.
Runtime-checkable because WavePlan carries one and rides on
DAGRunContext, a pydantic model, which validates an arbitrary type with
isinstance — and isinstance refuses a Protocol that is not.
Narrower than FileMetadataContext on purpose: a scope sets and clears a
wave's file list and records what a finished wave covered, and nothing
else. Naming that surface lets a caller be tested against it without
standing up a provider over a real cache.
Ancestors
Methods
mark_covered
def mark_covered(self, file_paths: Collection[str]) ‑> None:Record file_paths as carried through the whole DAG.
narrow_to
def narrow_to(self, file_paths: Collection[str] | None) ‑> None:Scope the provider to file_paths, or clear the scope with None.
WaveSelection
class WaveSelection( planner: WavePlanner, candidates: list[WaveCandidate], planned_at: datetime, context: WaveScopeProvider, datasource: Any = None,):What a run may plan: its planner and the candidates it selected.
Attributes
planner: The run's planner, holding the ledger scope.candidates: The candidates the run may carry, in selection order.planned_at: When the selection was made.context: The provider each wave narrows: the file provider, or an EHR DAG's$ehr_patients.datasource: The datasource each wave narrows, orNonefor an EHR DAG.
Variables
-
candidates : list[WaveCandidate]
-
context : WaveScopeProvider
-
datasource : Any
-
planned_at : datetime.datetime
-
planner : WavePlanner
WaveUnit
class WaveUnit(*args, **kwds):What one wave of a DAG is a set of.
Attributes
FILE: Inventory files, grouped by patient where the scan sweep identifies them.EHR: Patient IDs from the EHR patient listing snapshot.