Merge bitcoin/bitcoin#36731: test: use monotonic clock for durations in test framework and http_interface
What changed, and why it matters
This commit only changes the test code that runs Bitcoin Core's automated tests. It swaps the clock used to measure how long things take from the regular system clock (which can jump forward or backward, for example when the system time is adjusted) to a monotonic clock (which only ever moves forward steadily). This makes the tests more reliable and less likely to fail randomly due to clock jumps, but it does not change the actual Bitcoin Core software that users run, nor does it fix any security vulnerability in the live network or node software.
No security action required. This is a normal test-quality improvement. Reviewers may verify that no time.time() calls remain in duration-measurement contexts in these files, but the patch appears complete for the stated scope.
Security signals we found
No production code modified
Test-only reliability improvement
Prevents timing-related test flakiness under faketime and clock jumps
No change to cryptographic, consensus, networking, or RPC behavior in shipped binaries
Evidence from the diff
The patch replaces time.time() with time.monotonic() in the functional test framework and interface_http test. Affected helpers include sync_blocks, sync_mempools, assert_debug_log, busy_wait_for_debug_log, ensure_for, wait_until_helper_internal, authproxy._get_response, and test_runner timing. Monotonic time is the correct source for measuring durations and timeouts because it is not subject to NTP adjustments or system clock jumps. The change is purely in test infrastructure; no production consensus, networking, wallet, or RPC code is modified.
Changed components
test/functional/interface_http.pytest/functional/test_framework/authproxy.pytest/functional/test_framework/test_framework.pytest/functional/test_framework/test_node.pytest/functional/test_framework/util.pytest/functional/test_runner.pyInspect captured patch +20 / −20
### test/functional/interface_http.py
@@ -91,9 +91,9 @@ def recv_raw(self):
def expect_timeout(self, seconds):
# Wait for response, but expect a timeout disconnection
- start = time.time()
+ start = time.monotonic()
response1 = self.recv_raw()
- stop = time.time()
+ stop = time.monotonic()
# Server disconnected with EOF
assert_equal(response1, b"")
# Server disconnected within an acceptable range of time:
### test/functional/test_framework/authproxy.py
@@ -160,7 +160,7 @@ def batch(self, rpc_call_list):
return response
def _get_response(self):
- req_start_time = time.time()
+ req_start_time = time.monotonic()
try:
http_response = self.__conn.getresponse()
except socket.timeout:
@@ -196,7 +196,7 @@ def _get_response(self):
raise JSONRPCException({
'code': -342, 'message': f'Cannot decode response in utf8 format, content: {data}, exception: {e}'})
response = json.loads(responsedata, parse_float=decimal.Decimal)
- elapsed = time.time() - req_start_time
+ elapsed = time.monotonic() - req_start_time
if "error" in response and response["error"] is None:
log.debug("<-%s- [%.6f] %s" % (response["id"], elapsed, self._json_dumps(response["result"])))
else:
### test/functional/test_framework/test_framework.py
@@ -708,8 +708,8 @@ def sync_blocks(self, nodes=None, *, wait=0.05, timeout=60):
"""
rpc_connections = nodes or self.nodes
timeout = int(timeout * self.options.timeout_factor)
- stop_time = time.time() + timeout
- while time.time() <= stop_time:
+ stop_time = time.monotonic() + timeout
+ while time.monotonic() <= stop_time:
best_hash = [x.getbestblockhash() for x in rpc_connections]
if best_hash.count(best_hash[0]) == len(rpc_connections):
return
@@ -728,8 +728,8 @@ def sync_mempools(self, nodes=None, *, wait=0.05, timeout=60, flush_scheduler=Tr
"""
rpc_connections = nodes or self.nodes
timeout = int(timeout * self.options.timeout_factor)
- stop_time = time.time() + timeout
- while time.time() <= stop_time:
+ stop_time = time.monotonic() + timeout
+ while time.monotonic() <= stop_time:
pool = [set(r.getrawmempool()) for r in rpc_connections]
if pool.count(pool[0]) == len(rpc_connections):
if flush_scheduler:
### test/functional/test_framework/test_node.py
@@ -639,7 +639,7 @@ def assert_debug_log(self, expected_msgs, unexpected_msgs=None, *, timeout=0):
assert_equal(type(unexpected_msgs), list)
remaining_expected = list(expected_msgs)
- time_end = time.time() + timeout * self.timeout_factor
+ time_end = time.monotonic() + timeout * self.timeout_factor
prev_size = self.debug_log_size(encoding="utf-8") # Must use same encoding that is used to read() below
def join_log(log):
@@ -659,7 +659,7 @@ def join_log(log):
remaining_expected.pop()
if not remaining_expected:
return
- if time.time() >= time_end:
+ if time.monotonic() >= time_end:
break
time.sleep(0.05)
remaining_expected = [e for e in remaining_expected if e not in log]
@@ -671,7 +671,7 @@ def busy_wait_for_debug_log(self, expected_msgs, timeout=60):
"""
Block until we see a particular debug log message fragment or until we exceed the timeout.
"""
- time_end = time.time() + timeout * self.timeout_factor
+ time_end = time.monotonic() + timeout * self.timeout_factor
prev_size = self.debug_log_size(mode="rb") # Must use same mode that is used to read() below
remaining_expected = list(expected_msgs)
@@ -687,7 +687,7 @@ def busy_wait_for_debug_log(self, expected_msgs, timeout=60):
if not remaining_expected:
return
- if time.time() >= time_end:
+ if time.monotonic() >= time_end:
print_log = " - " + "\n - ".join(log.decode("utf8", errors="replace").splitlines())
break
### test/functional/test_framework/util.py
@@ -414,12 +414,12 @@ def ensure_for(*, duration, f, check_interval=0.2):
# to checking once in the beginning and once at the end of duration
if check_interval <= 0 or check_interval > duration:
check_interval = duration
- time_end = time.time() + duration
+ time_end = time.monotonic() + duration
predicate_source = "''''\n" + inspect.getsource(f) + "'''"
while True:
if not f():
raise AssertionError(f"Predicate {predicate_source} became false within {duration} seconds")
- if time.time() > time_end:
+ if time.monotonic() > time_end:
return
time.sleep(check_interval)
@@ -434,9 +434,9 @@ def wait_until_helper_internal(predicate, *, timeout=60, lock=None, timeout_fact
`p2p.py` has a preset lock.
"""
timeout = timeout * timeout_factor
- time_end = time.time() + timeout
+ time_end = time.monotonic() + timeout
- while time.time() < time_end:
+ while time.monotonic() < time_end:
if lock:
with lock:
if predicate():
### test/functional/test_runner.py
@@ -661,7 +661,7 @@ def run_tests(*, test_list, build_dir, tmpdir, jobs=1, enable_coverage=False, ar
flags=flags,
use_term_control=use_term_control,
)
- start_time = time.time()
+ start_time = time.monotonic()
test_results = []
max_len_name = len(max(test_list, key=len))
@@ -703,7 +703,7 @@ def run_tests(*, test_list, build_dir, tmpdir, jobs=1, enable_coverage=False, ar
f"Test execution data left in {tmpdir}.\n"
f"Additional storage is needed to execute testing.")
- runtime = int(time.time() - start_time)
+ runtime = int(time.monotonic() - start_time)
print_results(test_results, max_len_name, runtime)
if results_filepath:
write_results(test_results, results_filepath, runtime)
@@ -797,7 +797,7 @@ def proc_wait(task):
task = [
test,
- time.time(),
+ time.monotonic(),
subprocess.Popen(
[sys.executable, self.tests_dir + test_argv[0]] + test_argv[1:] + self.flags + portseed_arg + tmpdir_arg,
text=True,
@@ -841,7 +841,7 @@ def proc_wait(task):
clearline = '\r' + (' ' * dot_count) + '\r'
print(clearline, end='', flush=True)
dot_count = 0
- ret.append((TestResult(name, status, int(time.time() - start_time)), testdir, stdout, stderr, proc.returncode, skip_reason))
+ ret.append((TestResult(name, status, int(time.monotonic() - start_time)), testdir, stdout, stderr, proc.returncode, skip_reason))
if ret:
return ret
if self.use_term_control:Why this scored 19/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.