Compose Timeouts With A Shared Deadline
A deadline helper that derives per-step timeouts from one shared budget so a slow first step cannot make later steps exceed the total.
Code
import time
from typing import Callable
class DeadlineExceededError(RuntimeError):
"""Raised when the shared budget no longer covers the requested step."""
class Deadline:
"""A single budget shared by every step of an operation."""
def __init__(self, budget_s: float, clock: Callable[[], float] = time.monotonic) -> None:
if budget_s <= 0:
raise ValueError("budget_s must be positive")
self._budget_s = budget_s
self._clock = clock
self._start = clock()
def remaining(self) -> float:
return max(0.0, self._budget_s - (self._clock() - self._start))
def expired(self) -> bool:
return self.remaining() <= 0.0
def require(self, needed_s: float) -> float:
"""Return the time granted for a step, or raise if it cannot fit."""
if needed_s <= 0:
raise ValueError("needed_s must be positive")
left = self.remaining()
if left < needed_s:
raise DeadlineExceededError(
"budget exhausted: %.3fs left, %.3fs needed" % (left, needed_s)
)
return needed_sGiving each step its own full timeout lets three steps each use the whole budget, so the caller waits three times longer than promised.
Use case: engineers chaining network calls under one total budget
Inputs / outputs
- Input: a total budget in seconds plus a monotonic clock function
- Output: remaining budget queries and a deadline exceeded error when the budget is gone
Error conditions
- budget already exhausted before a step starts
- non-positive total budget
- remaining time requested for a step
Approach
record the start time once; remaining() computes budget minus elapsed; require() raises when a step cannot get at least the requested slice.
Implementation
import time
from typing import Callable
class DeadlineExceededError(RuntimeError):
"""Raised when the shared budget no longer covers the requested step."""
class Deadline:
"""A single budget shared by every step of an operation."""
def __init__(self, budget_s: float, clock: Callable[[], float] = time.monotonic) -> None:
if budget_s <= 0:
raise ValueError("budget_s must be positive")
self._budget_s = budget_s
self._clock = clock
self._start = clock()
def remaining(self) -> float:
return max(0.0, self._budget_s - (self._clock() - self._start))
def expired(self) -> bool:
return self.remaining() <= 0.0
def require(self, needed_s: float) -> float:
"""Return the time granted for a step, or raise if it cannot fit."""
if needed_s <= 0:
raise ValueError("needed_s must be positive")
left = self.remaining()
if left < needed_s:
raise DeadlineExceededError(
"budget exhausted: %.3fs left, %.3fs needed" % (left, needed_s)
)
return needed_s
Verification tests
import unittest
from example import Deadline, DeadlineExceededError
class FakeClock:
def __init__(self):
self.t = 0.0
def __call__(self):
return self.t
class DeadlineTests(unittest.TestCase):
def test_remaining_decreases_as_time_passes(self):
clock = FakeClock()
deadline = Deadline(1.0, clock)
self.assertAlmostEqual(deadline.remaining(), 1.0)
clock.t = 0.25
self.assertAlmostEqual(deadline.remaining(), 0.75)
self.assertFalse(deadline.expired())
def test_expires_when_the_budget_is_gone(self):
clock = FakeClock()
deadline = Deadline(0.5, clock)
clock.t = 0.5
self.assertTrue(deadline.expired())
self.assertEqual(deadline.remaining(), 0.0)
def test_raises_before_starting_an_impossible_step(self):
clock = FakeClock()
deadline = Deadline(1.0, clock)
clock.t = 0.9
with self.assertRaises(DeadlineExceededError):
deadline.require(0.5)
def test_grants_a_step_that_fits(self):
clock = FakeClock()
deadline = Deadline(1.0, clock)
self.assertEqual(deadline.require(0.5), 0.5)
def test_rejects_an_invalid_budget(self):
with self.assertRaises(ValueError):
Deadline(0)
with self.assertRaises(ValueError):
Deadline(1.0).require(0)
if __name__ == "__main__":
unittest.main()
Dependencies and running
No external dependencies (standard library only).
Runtime: python >= 3.9 Entry point: python example.py
Limitations and error handling
no cancellation of running work; cooperative checking between steps only.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.