Share Python Timeout Budgets with time.monotonic_ns
A release tool has two sequential stages and a total budget of five seconds. Giving each stage a fresh five-second timeout permits roughly ten seconds of waiting. The intended rule is one deadline: time spent in the first stage reduces what the second stage may use.
These examples use Python 3.10 or later. They implement a small, cooperative budget for operations in one process. The helper reports remaining time; the operation receiving that value must enforce its own timeout.
Separate Wall Time from Elapsed Time
Calendar timestamps answer when an event happened. Timeout accounting asks how much time has passed. A system clock correction can change a wall-clock reading, so subtracting time.time() values is a poor basis for this budget.
The Python time reference documents a clock that cannot go backward and is unaffected by system clock updates. Its origin is unspecified; compare readings from the same clock rather than interpreting one as a calendar date.
time.monotonic_ns() supplies integer nanoseconds. Integer arithmetic keeps the deadline and its subtraction out of floating-point calculations. Nanosecond units do not imply nanosecond hardware resolution. Keep wall-clock timestamps for human-readable logs and monotonic differences for this deadline.
Create the Deadline Once
Save this module as budget.py:
| |
The public input is a nonnegative integer number of milliseconds. Booleans, fractional numbers, strings, and None are rejected. Zero creates an immediately exhausted budget. At the exact deadline, starting another stage is also rejected.
Each instance records its deadline only during construction. Calling require_seconds() samples the clock again without extending that deadline. Conversion to floating-point seconds occurs only at the consumer boundary; choose practical timeout values supported by that consumer’s API.
Pass the Remaining Budget to Each Stage
Add this function to budget.py:
Both callbacks must accept timeout in seconds and apply it to their complete stage. The second callback receives the remaining allowance after the first callback returns. Constructing a new Budget before each callback would restart the allowance and defeat the shared limit.
Check the actual API being adapted. Some network APIs interpret a timeout as an inactivity limit or apply it separately to different phases. Passing a number to such an API does not automatically bound the entire stage. If the callback performs multiple waits, pass the same budget inward and recalculate before each wait.
An exception from either callback propagates. If the first stage consumes the budget, the next budget check raises before calling the second. Work already completed by the first stage remains completed; expiration supplies no rollback.
Test Boundaries with a Fake Clock
Save this as test_budget.py beside the module and run python test_budget.py:
| |
The fake advances only when the test requests it. The assertions cover a reduced second-stage allowance, a positive value immediately before expiration, exact expiration, and clamping after expiration. No real sleep or scheduler timing makes the test flaky.
Treat Expiration as a Cooperative Boundary
This class cannot interrupt a callback that blocks forever or ignores its timeout. There is also time between checking the budget and beginning a wait. Completion may occur after the deadline because of scheduling, cleanup, or the consumer’s timeout behavior. A hard execution limit requires an execution model that can enforce it.
Retries and backoff should use the original budget too. Recheck after sleeping: the sleep documentation allows a suspension to exceed the requested duration. A requested delay is not proof of the exact elapsed interval.
Keep the deadline local to the running process. Do not save it as an expiry timestamp or send it to another machine. Suspension behavior depends on the underlying clock and platform, so define separate policy if the budget must include machine sleep. For ordinary sequential waits, one monotonic deadline makes the remaining allowance explicit at every stage.