time_bounds
Time bounds on a background DAG run: setup, each wave, and the wave loop.
Work runs on daemon threads, which nothing can stop, so a bound that expires
does not abandon the work. It cancels it cooperatively, reports the threads
still running as abandoned_thread, and then waits for them: everything the
run holds — its concurrency slots and, through them, the machine — stays held
until the last thread has ended. That wait is unbounded but logged; a process
that dies stops renewing its leases, which is what releases them in the end.
Setup is the one exception, because it is the one bound a whole machine can be
lost to: a share that never answers blocks the read open_run is in and
nothing in the process can end it, so the run would hold its lineage lock and
its machine slot for as long as the machine is up. A setup bound that expires
gives the work abandon_after seconds to stop and then walks away from it:
the run fails, the locks are released, and the thread is left to the process
(await_bounded). Its writes are fenced out by whatever run takes the lineage
next (flows.dag.executor).
Every bound logs a warning at half its length, so a slow setup is visible before it expires.
Three bounds, each with its own stop_reason:
background_dag_setup_timeoutaroundopen_run—"setup_timeout".background_dag_wave_timeoutaround one wave's execution —"wave_timeout".- The hard cap,
background_dag_max_run_secondsplus the wave timeout, around the wave loop —"run_hard_timeout".
The soft cap, background_dag_max_run_seconds itself, is not a bound in this
sense: the wave loop checks it between waves and ends the run as completed,
"run_time_cap". Both caps time the wave loop only, never setup and never a
wait for a lock taken outside it.
A step's wait for its resource lock happens inside the wave and the loop, so it
is taken out of both bounds instead, but only while no step of the run is
running: each bound binds an ExcludedTime, excluded_from_bounds stops its
clock for a wait, and running_in_bounds marks a step as running, which keeps
the clock going. A bound can therefore expire during a wait beside a running
step; the wait then ends on the run's cancellation
(bitfount.flows.dag.step_resources).
Module
Functions
await_bounded
async def await_bounded( work: Awaitable[_T], *, timeout: float | None, cancellation: RunCancellation, stop_reason: str, fields: Mapping[str, str | None], on_expiry: Callable[[], Awaitable[None]] | None = None, excluded: ExcludedTime | None = None, abandon_after: float | None = None, clock: Callable[[], float] = <built-in function monotonic>, wait: _Waiter = <function wait>,) ‑> ~_T:Await work for at most timeout seconds, then stop it cooperatively.
On expiry: sets cancellation, awaits on_expiry, reports the threads
that were running under it as abandoned_thread, and waits for work and
those threads to finish — however long that takes — before raising.
Everything up to the wait happens at expiry, so a thread that never stops
still leaves the run marked as ending and its threads reported. The
report names the threads as they were when the bound expired, not as they
are when it is written, so a thread that stops in between is recorded too.
abandon_after bounds that wait, for the one bound whose thread may never
stop at all: after it, the threads still running are reported at ERROR as
given up on and the error is raised without them. The caller must then not
wait for them either, which is what makes the locks held around this return
to the machine while the thread carries on. The work itself is cancelled at
the asyncio level, so nothing it returns late is ever seen.
Work that finishes just after the bound, before it saw the flag, still
raises: the bound expired. The bound itself never cancels work at the
asyncio level, so its own cleanup runs as written; the only cancellation
it sees is a run cancellation that hold_step_resource turns into
RunCancelledError while the work waits for its resource lock.
If the awaiting coroutine is itself cancelled, cancellation is set and work is cancelled with it, without waiting: that is a shutdown.
A bound long enough to reach logs a warning at half of it, once, so work that is merely slow is visible before it expires.
Arguments
work: What to bound.timeout: The bound in seconds, orNonefor none.cancellation: The flag the work's threads check.stop_reason: The bound'sstop_reason, also the cancel reason.fields:task_hashandproject_id, for telemetry.on_expiry: Awaited once at expiry, before the wait, to record that the run is ending. What it raises is logged and ignored.excluded: Time not counted against timeout; the bound does not expire while a wait it covers is in progress and no step is running. A wait beside a running step is counted, so a hung parallel step still expires the bound.abandon_after: How long to wait for the work to stop after the bound expired before giving up on it, orNoneto wait as long as it takes.clock: Returns the current time in seconds; counts the time elapsed against timeout.wait: Waits for work for at most a timeout, asasyncio.waitdoes.
Returns What work returned, when it finished in time.
Raises
TimeBoundExceededError: If the bound expired, once the work has stopped, or once the run has given up waiting for it when abandon_after is set; chained from what the work raised, if it raised.
counting_excluded_time
def counting_excluded_time( excluded: ExcludedTime,) ‑> Iterator[ExcludedTime]:Make excluded_from_bounds in this block exclude time from excluded.
Arguments
excluded: The bound's excluded time.
excluded_from_bounds
def excluded_from_bounds() ‑> Iterator[None]:Stop the clock of every bound enclosing this block while no step runs.
For the part of the block during which a step marked by running_in_bounds
is running, the clock keeps going. A no-op outside any bound.
hold_until_threads_exit
async def hold_until_threads_exit( cancellation: RunCancellation, *, reason: str, fields: Mapping[str, str | None],) ‑> None:Wait for any thread still running under cancellation, cancelling it.
For a run ending while a thread it started still runs — a parallel step left behind by a failure — so that the run's locks outlive it. Returns at once when none is running.
Arguments
cancellation: The run's cancel flag.reason: Why the run is ending, used as the cancel reason.fields:task_hashandproject_id, for telemetry.
running_in_bounds
def running_in_bounds() ‑> Iterator[None]:Mark a step as running in every bound enclosing this block.
While one runs, a wait for a resource lock beside it does not stop the bound's clock. A no-op outside any bound.
Global variables
RUN_HARD_TIMEOUT-stop_reasonof a run whose wave loop outlived the hard cap.
RUN_TIME_CAP-stop_reasonof a run that stopped between waves at the soft cap.
SETUP_TIMEOUT-stop_reasonof a run whose setup outlivedbackground_dag_setup_timeout.
WAVE_TIMEOUT-stop_reasonof a run that ended because a wave outlived its timeout.
Classes
ExcludedTime
class ExcludedTime(*, clock: Callable[[], float] = <built-in function monotonic>):Time a bound does not count: the waits for step resources inside it.
Entered and left on the event loop that awaits the bound. Overlapping waits, as parallel steps make, count once.
The clock is the bound's, not a step's, and it is stopped only while every running step is waiting: a wait in progress with no step running pauses the bound, but a wait beside a running step does not, so a sibling that hangs meanwhile still expires the wave timeout.
Start with nothing excluded.
Arguments
clock: Returns the current time in seconds.
Variables
-
active : bool- Whether a wait is in progress and no step is running.While it is, the bound's clock is stopped.
Methods
excluding
def excluding(self) ‑> Iterator[None]:Exclude the block's duration from the bound, while no step runs.
running
def running(self) ‑> Iterator[None]:Mark a step as running for the block: waits beside it are counted.
seconds
def seconds(self) ‑> float:Return the excluded time so far, including a pause in progress.
RunBounds
class RunBounds( cancellation: RunCancellation, setup_timeout: float | None = None, wave_timeout: float | None = None, soft_cap: float | None = None, hard_cap: float | None = None, fields: Mapping[str, str | None] = {}, loop_started: float | None = None, stop_reason: str | None = None, clock: Callable[[], float] = <built-in function monotonic>, wait: _Waiter = <function wait>,):The time bounds of one background run, and how its wave loop stopped.
Attributes
cancellation: The run's cancel flag, which every bound sets and every thread the run starts is registered with.setup_timeout: Secondsopen_runmay take, orNonefor no bound.wave_timeout: Seconds one wave's execution may take, orNone.soft_cap: Seconds of wave loop after which no new wave starts, orNone.hard_cap: Seconds the wave loop may take in all, orNone.fields:task_hashandproject_id, for telemetry.loop_started: When the wave loop began, inclockseconds;Noneuntil it has.stop_reason: Set when a bound or the soft cap ended the run.clock: Returns the current time in seconds; times the soft cap and the excluded waits.wait: Waits for the bounded work for at most a timeout, asasyncio.waitdoes; expires each bound.
Variables
-
cancellation : RunCancellation
-
fields : Mapping[str, str | None]
-
hard_cap : float | None
-
loop_started : float | None
-
setup_timeout : float | None
-
soft_cap : float | None
-
stop_reason : str | None
-
wave_timeout : float | None
Static methods
from_settings
def from_settings( *, task_hash: str | None = None, project_id: str | None = None,) ‑> RunBounds:Build the bounds the settings give, with a fresh cancel flag.
Arguments
task_hash: The run's task hash, for telemetry.project_id: The run's project, for telemetry.
Returns The bounds. The hard cap is the soft cap plus the wave timeout, and is disabled with either: an unbounded wave may legitimately run past any fixed cap.
Methods
clock
def clock(...) ‑> Callable[[], float]:monotonic() -> float
Monotonic clock, cannot go backward.
soft_cap_reached
def soft_cap_reached(self) ‑> bool:Return whether the wave loop has run for the soft cap or longer.
start_loop
def start_loop(self) ‑> None:Start the cap clock, once the run has finished setting up.
wait
async def wait( fs, *, timeout=None, return_when='ALL_COMPLETED',) ‑> Callable[..., Awaitable[tuple[set[typing.Any], set[typing.Any]]]]:Wait for the Futures or Tasks given by fs to complete.
The fs iterable must not be empty.
Coroutines will be wrapped in Tasks.
Returns two sets of Future: (done, pending).
TimeBoundExceededError
class TimeBoundExceededError( stop_reason: str, timeout_seconds: float, late_result: Any = None, *, threads_abandoned: bool = False,):Raised once a bound has expired and the work it bounded has stopped.
Arguments
stop_reason: The bound'sstop_reason.timeout_seconds: The bound.late_result: What the work returned after the bound expired.threads_abandoned: Whether the run walked away from a thread it could not stop.
Attributes
stop_reason: The bound'sstop_reason.timeout_seconds: The bound.late_result: What the work returned after the bound expired, when it returned rather than raised;Noneotherwise.threads_abandoned: Whether the run gave up waiting for the work instead of waiting it out.Falsewhen the work stopped before the error was raised, which is the case for every bound that has noabandon_after.Truemeans a thread is still running and the caller must not wait for it: it has kept what it holds and is being left to the process.
Build the error.