mining: handle negative and NaN wait timeouts #36940

Manually merged
enochaz merged 3 commits from 11-26-mining-timeout-nan into master 2026-12-02 03:09:40 +00:00 AGit
enochaz commented 2026-11-21 16:54:11 +00:00 (Migrated from github.com)

An ipc client can pass any timeout to waitTipChanged, but the code assumes it is never negative:

Assume(timeout >= 0ms); // No internal callers should use a negative timeout

On debug builds, a negative or NaN timeout fails this check and aborts the node. I reproduced this with a timeout of -1.0.

On release builds the check is skipped. Negative values are clamped to zero, but NaN is not, because every comparison with NaN is false. It ends up as the deadline passed to wait_until.

waitNext has no Assume, but it also doesn't check its timeout. A NaN timeout waits one extra fee tick (about one second) before returning.

waitTipChanged and waitNext now throw an error for negative or NaN timeouts. The internal Assume in WaitTipChanged still checks internal callers. The interface documents the errors, and the functional test covers rejection of negative and NaN timeouts and acceptance of positive infinity in both methods.

I'm not aware of any client that sends these values (sv2-tp, for example, requires an interval of at least one second), so this is hardening against bad input from ipc clients.

This is similar to #36520, which handles invalid arguments to the Chain interface for the same reason.

Links

An ipc client can pass any timeout to `waitTipChanged`, but the code assumes it is never negative: ``` Assume(timeout >= 0ms); // No internal callers should use a negative timeout ``` On debug builds, a negative or NaN timeout fails this check and aborts the node. I reproduced this with a timeout of -1.0. On release builds the check is skipped. Negative values are clamped to zero, but NaN is not, because every comparison with NaN is false. It ends up as the deadline passed to `wait_until`. `waitNext` has no Assume, but it also doesn't check its timeout. A NaN timeout waits one extra fee tick (about one second) before returning. `waitTipChanged` and `waitNext` now throw an error for negative or NaN timeouts. The internal `Assume` in `WaitTipChanged` still checks internal callers. The interface documents the errors, and the functional test covers rejection of negative and NaN timeouts and acceptance of positive infinity in both methods. I'm not aware of any client that sends these values (sv2-tp, for example, requires an interval of at least one second), so this is hardening against bad input from ipc clients. _This is similar to #36520, which handles invalid arguments to the Chain interface for the same reason._ Links - https://ipcbugs.ofsky.org/bugs/bitcoin-2026-wait-timeout-assume/
DrahtBot commented 2026-11-21 16:54:22 +00:00 (Migrated from github.com)

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
ACK Sjors, nervana21, ryanofsky

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

No conflicts as of last run.

LLM Linter (✨ experimental)

Possible places where comparison-specific test macros should replace generic comparisons:

  • test/functional/interface_ipc_mining.py: assert template8 is None → Prefer assert_equal(template8, None).
  • test/functional/test_framework/ipc_util.py: assert wait_done >= do_called → Prefer assert_greater_than_or_equal(wait_done, do_called).

2026-11-30 15:01:37

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36940 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36940.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36940#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | ACK | [Sjors](https://github.com/bitcoin/bitcoin/pull/36940#issuecomment-7311670137), [nervana21](https://github.com/bitcoin/bitcoin/pull/36940#issuecomment-7314075633), [ryanofsky](https://github.com/bitcoin/bitcoin/pull/36940#pullrequestreview-6143342505) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3--> ### LLM Linter (✨ experimental) Possible places where comparison-specific test macros should replace generic comparisons: - `test/functional/interface_ipc_mining.py`: `assert template8 is None` → Prefer `assert_equal(template8, None)`. - `test/functional/test_framework/ipc_util.py`: `assert wait_done >= do_called` → Prefer `assert_greater_than_or_equal(wait_done, do_called)`. <sup>2026-11-30 15:01:37</sup>
First-time contributor

🔵 Suggestion · The waitNext infinity test stops before the deadline loop check

The waitNext infinity case interrupts after 0.1 seconds, so a regression that returns after the first one-second fee tick would still pass.

Location: test/functional/interface_ipc_mining.py:358 (head).

🔵 Suggestion · Callable interrupts leave their IPC errors unobserved

wait_and_do discards promises returned by callable interrupts, so a rejected interrupt can leave the new infinite waits pending instead of propagating its error; no hang was observed.

Location: test/functional/test_framework/ipc_util.py:55 (head).


Reviewed: d293ef600dbe · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:483ed3be8d13b50996bf0f81d4f55487b6b938dd --> <!-- ralph-head:d293ef600dbe056b3a1b7392f03e4f562c1026f1 --> <!-- ralph-case:39d15758b7e0ae50defd4c501d99f13923bc082681351c85f0f817fb7ab0f776 --> **🔵 Suggestion · The `waitNext` infinity test stops before the deadline loop check** The `waitNext` infinity case interrupts after 0.1 seconds, so a regression that returns after the first one-second fee tick would still pass. Location: [`test/functional/interface_ipc_mining.py:358`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d293ef600dbe056b3a1b7392f03e4f562c1026f1/test/functional/interface_ipc_mining.py#L358>) (head). **🔵 Suggestion · Callable interrupts leave their IPC errors unobserved** `wait_and_do` discards promises returned by callable interrupts, so a rejected interrupt can leave the new infinite waits pending instead of propagating its error; no hang was observed. Location: [`test/functional/test_framework/ipc_util.py:55`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/d293ef600dbe056b3a1b7392f03e4f562c1026f1/test/functional/test_framework/ipc_util.py#L55>) (head). <!-- Review tier: sensitive --> --- Reviewed: [`d293ef600dbe`](<https://git.fish.foo/bitcoin/bitcoin/commit/d293ef600dbe056b3a1b7392f03e4f562c1026f1>) · [Review report](<https://review.fish.foo/report/36940-d293ef600dbe056b3a1b7392f03e4f562c1026f1-3355-8.html>) · [Previous reports](<https://review.fish.foo/traces/36940/>) [permalink](<https://review.fish.foo/report/36940-d293ef600dbe056b3a1b7392f03e4f562c1026f1-3355-8.html>)
DrahtBot commented 2026-11-21 19:26:06 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
nervana21 commented 2026-11-21 19:59:34 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
Sjors (Migrated from github.com) reviewed 2026-11-23 14:40:31 +00:00
Sjors (Migrated from github.com) left a comment

Thanks.

Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0.

Thanks. Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0.
Sjors (Migrated from github.com) commented 2026-11-23 14:13:24 +00:00

Might as well also cover "-inf" (rejected) and "inf" (accepted).

Might as well also cover `"-inf"` (rejected) and `"inf"` (accepted).
enochaz (Migrated from github.com) reviewed 2026-11-23 15:40:53 +00:00
enochaz (Migrated from github.com) commented 2026-11-23 15:40:53 +00:00

Done. -inf is now tested alongside -1.0 and NaN as rejected.

Done. `-inf `is now tested alongside -1.0 and NaN as rejected.
enochaz commented 2026-11-23 15:42:56 +00:00 (Migrated from github.com)

Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0.

Thanks, done. waitTipChanged and waitNext now throw an error for negative or NaN timeouts instead of clamping them.

> Since both negative values and NaN indicate a broken client, I prefer returning an error message, rather than clamping to 0. Thanks, done. `waitTipChanged` and `waitNext` now throw an error for negative or NaN timeouts instead of clamping them.
DrahtBot commented 2026-11-23 16:48:31 +00:00 (Migrated from github.com)

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/45207773992/job/137808054907
LLM reason (✨ experimental): CI failed because IWYU added a missing <compare> include to src/node/interfaces.cpp, leaving an uncommitted diff that the check rejects.

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/45207773992/job/137808054907</sub> <sub>LLM reason (✨ experimental): CI failed because IWYU added a missing `<compare>` include to `src/node/interfaces.cpp`, leaving an uncommitted diff that the check rejects.</sub> <details><summary>Hints</summary> Try to run the tests locally, according to the documentation. However, a CI failure may still happen due to a number of reasons, for example: * Possibly due to a silent merge conflict (the changes in this pull request being incompatible with the current code in the target branch). If so, make sure to rebase on the latest commit of the target branch. * A sanitizer issue, which can only be found by compiling with the sanitizer and running the affected test. * An intermittent issue. Leave a comment here, if you need help tracking down a confusing failure. </details>
ryanofsky (Migrated from github.com) approved these changes 2026-11-23 17:41:12 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK 758ae2c916. This stops an IPC client from crashing debug builds of the node by passing a negative or NaN timeout to waitTipChanged, and from turning a NaN timeout into a wait_until deadline in release builds. Rejecting these values in node/interfaces.cpp, as Sjors suggested, is the same way #36520 handles invalid Chain arguments, and it lets the internal Assume stay.

This issue was also reported privately in two security audits: [1] found the negative and NaN timeout problem and reproduced the abort, and [2] suggested rejecting non-finite values when libmultiprocess reads any duration from the wire, which could stop this kind of bug from coming back with new duration parameters.

Code review ACK 758ae2c916eb8d2127ab1949b9630cf4348b8945. This stops an IPC client from crashing debug builds of the node by passing a negative or NaN timeout to `waitTipChanged`, and from turning a NaN timeout into a `wait_until` deadline in release builds. Rejecting these values in `node/interfaces.cpp`, as Sjors suggested, is the same way #36520 handles invalid `Chain` arguments, and it lets the internal `Assume` stay. This issue was also reported privately in two security audits: [[1]](https://ipcbugs.ofsky.org/audits/ar-38/) found the negative and NaN timeout problem and reproduced the abort, and [[2]](https://ipcbugs.ofsky.org/audits/ar-80/) suggested rejecting non-finite values when libmultiprocess reads any duration from the wire, which could stop this kind of bug from coming back with new duration parameters.
ryanofsky (Migrated from github.com) commented 2026-11-23 17:31:01 +00:00

In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916)

The iwyu CI job is failing because the new timeout >= 0ms comparisons need <compare>. Adding #include <compare> after #include <atomic> a few lines above should fix it. That one line is the whole diff the job prints.

In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945) The [iwyu CI job](https://github.com/bitcoin/bitcoin/actions/runs/45207773992/job/137808054907) is failing because the new `timeout >= 0ms` comparisons need `<compare>`. Adding `#include <compare>` after `#include <atomic>` a few lines above should fix it. That one line is the whole diff the job prints.
Lines 928-929
ryanofsky (Migrated from github.com) commented 2026-11-23 16:45:31 +00:00

In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916)

nit: could say why the comparison is negated, here and in waitTipChanged, so it doesn't get simplified to timeout < 0ms, which would accept NaN:

// Timeout can come from an IPC client, so reject negative and NaN values.
// The negated comparison is also true for NaN.
In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945) nit: could say why the comparison is negated, here and in `waitTipChanged`, so it doesn't get simplified to `timeout < 0ms`, which would accept NaN: ```cpp // Timeout can come from an IPC client, so reject negative and NaN values. // The negated comparison is also true for NaN. ```
Lines 972-973
ryanofsky (Migrated from github.com) commented 2026-11-23 16:45:30 +00:00

In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916)

The commit message and PR description still describe the previous push: the commit says negative and NaN timeouts are treated as zero, and the PR description says the Assume is removed. Now that these calls throw and the Assume stays, both should be updated. The commit subject could also mention waitNext, for example "mining: reject negative and NaN wait timeouts from IPC clients", and NaN is spelled "Nan" in two places.

In commit "mining: handle negative and NaN waitTipChanged timeouts" (758ae2c916eb8d2127ab1949b9630cf4348b8945) The commit message and PR description still describe the previous push: the commit says negative and NaN timeouts are treated as zero, and the PR description says the Assume is removed. Now that these calls throw and the Assume stays, both should be updated. The commit subject could also mention `waitNext`, for example "mining: reject negative and NaN wait timeouts from IPC clients", and NaN is spelled "Nan" in two places.
enochaz (Migrated from github.com) reviewed 2026-11-25 08:51:50 +00:00
enochaz (Migrated from github.com) commented 2026-11-25 08:51:50 +00:00

Thanks, added after

Thanks, added <compare> after <atomic>
enochaz (Migrated from github.com) reviewed 2026-11-25 08:53:37 +00:00
Lines 928-929
enochaz (Migrated from github.com) commented 2026-11-25 08:53:37 +00:00

Thanks, added a comment at both checks explaining that the negated comparison also catches NaN.

Thanks, added a comment at both checks explaining that the negated comparison also catches NaN.
enochaz (Migrated from github.com) reviewed 2026-11-25 08:56:23 +00:00
Lines 972-973
enochaz (Migrated from github.com) commented 2026-11-25 08:56:23 +00:00

Made the changes here, updated both. They now say that waitTipChanged and waitNext reject negative and NaN timeouts. The internal Assume stays

Made the changes here, updated both. They now say that `waitTipChanged` and `waitNext` reject negative and NaN timeouts. The internal Assume stays
enochaz commented 2026-11-25 08:59:44 +00:00 (Migrated from github.com)

Thanks for the reviews and for sharing the audit context. made the changes for iwyu and a comment at both checks explaining why the negated comparison catches NaN.

also updated the commit message and pr description to reflect that both methods reject invalid timeouts and the internal Assume stays.

Thanks for the reviews and for sharing the audit context. made the changes for iwyu and a comment at both checks explaining why the negated comparison catches NaN. also updated the commit message and pr description to reflect that both methods reject invalid timeouts and the internal `Assume` stays.
enochaz commented 2026-11-25 09:10:06 +00:00 (Migrated from github.com)

Thanks for the reviews, resolved the iwyu issues and updated the commit and pr descriptions to match the recent changes

Thanks for the reviews, resolved the iwyu issues and updated the commit and pr descriptions to match the recent changes
nervana21 commented 2026-11-25 17:33:16 +00:00 (Migrated from github.com)

tACK 2bfe24e3ad

tACK 2bfe24e3ad8be86c76a6530ea056964c50cc1ca9
ryanofsky (Migrated from github.com) approved these changes 2026-11-25 20:13:34 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK 2bfe24e3ad. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a wait_until deadline in release builds.

Thanks for the quick updates, this addresses all my earlier comments. One test suggestion inline: the new infinite-timeout checks don't test what they're meant to, because of how the interrupt is sent.

Code review ACK 2bfe24e3ad8be86c76a6530ea056964c50cc1ca9. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a `wait_until` deadline in release builds. Thanks for the quick updates, this addresses all my earlier comments. One test suggestion inline: the new infinite-timeout checks don't test what they're meant to, because of how the interrupt is sent.
ryanofsky (Migrated from github.com) commented 2026-11-25 19:03:21 +00:00

In commit "mining: reject negative and NaN wait timeouts from IPC clients" (2bfe24e3ad)

These "Infinite timeout is accepted" tests, here and in the waitTipChanged test above, check that an infinite timeout isn't rejected, but not that the call actually waits. They would also pass if an infinite timeout made waitNext or waitTipChanged return immediately, for example because it was clamped to zero. template6.interruptWait() is evaluated as an argument to wait_and_do, and pycapnp sends the request right then, so the interrupt reaches the node before the wait starts and the wait returns immediately. I measured both waits returning in under 4ms instead of after wait_and_do's 0.1s sleep. The Ralph review pointed out the waitNext case.

Passing the method without calling it (template6.interruptWait rather than template6.interruptWait()) lets wait_and_do call it after the sleep. To catch the problem, wait_and_do could take an optional check_order argument that asserts the wait finished after do_fn was called, used here for the two new tests. I checked that this passes with the current code and fails with wait finished 0.097s before do_fn was called if waitNext treats an infinite timeout as zero:

diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py
--- a/test/functional/interface_ipc_mining.py
+++ b/test/functional/interface_ipc_mining.py
@@ -168,7 +168,7 @@ class IPCMiningTest(BitcoinTestFramework):
             async def wait_for_tip_inf():
                 result = (await mining.waitTipChanged(ctx, newblockref.hash, float("inf"))).result
                 assert_equal(len(result.hash), 0)
-            await wait_and_do(wait_for_tip_inf(), mining.interrupt())
+            await wait_and_do(wait_for_tip_inf(), mining.interrupt, check_order=True)

             self.log.debug("interrupt() should abort waitTipChanged()")
             async def wait_for_tip():
@@ -355,7 +355,7 @@ class IPCMiningTest(BitcoinTestFramework):
                     inf_waitoptions.feeThreshold = MAX_MONEY
                     template8 = await mining_wait_next_template(template6, stack, ctx, inf_waitoptions)
                     assert template8 is None
-                await wait_and_do(wait_for_block_inf(), template6.interruptWait())
+                await wait_and_do(wait_for_block_inf(), template6.interruptWait, check_order=True)
                 waitoptions.timeout = self.default_ipc_timeout_ms

                 self.log.debug("interruptWait should abort the current wait")
diff --git a/test/functional/test_framework/ipc_util.py b/test/functional/test_framework/ipc_util.py
--- a/test/functional/test_framework/ipc_util.py
+++ b/test/functional/test_framework/ipc_util.py
@@ -10,6 +10,7 @@ from dataclasses import dataclass
 from io import BytesIO
 from pathlib import Path
 import shutil
+import time
 from typing import Optional

 from test_framework.messages import CBlock
@@ -45,20 +46,31 @@ async def destroying(obj, ctx):
         await obj.destroy(ctx)


-async def wait_and_do(wait_fn, do_fn, sleep_time=0.1):
+async def wait_and_do(wait_fn, do_fn, sleep_time=0.1, check_order=False):
     """Call wait_fn, then sleep, then call do_fn in a parallel task. Wait for
-    both tasks to complete."""
+    both tasks to complete.
+
+    With check_order, assert that wait_fn finishes after do_fn is called, to
+    catch waits that return early instead of being ended by do_fn. Pass do_fn
+    as a callable for this: pycapnp sends an IPC request when the method is
+    called, so cap.method() passed directly reaches the server before the
+    wait starts."""
     wait_started = asyncio.Event()
     result = None
+    wait_done = None
+    do_called = None

     async def wait():
-        nonlocal result
+        nonlocal result, wait_done
         wait_started.set()
         result = await wait_fn
+        wait_done = time.monotonic()

     async def do():
+        nonlocal do_called
         await wait_started.wait()
         await asyncio.sleep(sleep_time)
+        do_called = time.monotonic()
         # Let do_fn be either a callable or an awaitable object
         if inspect.isawaitable(do_fn):
             await do_fn
@@ -66,6 +78,8 @@ async def wait_and_do(wait_fn, do_fn, sleep_time=0.1):
             do_fn()

     await asyncio.gather(wait(), do())
+    if check_order:
+        assert wait_done >= do_called, f"wait finished {do_called - wait_done:.3f}s before do_fn was called"
     return result



The interrupt tests already on master have the same problem: the interrupt() test for waitTipChanged, the createNewBlock cooldown test and the interruptWait() test all pass the IPC call itself, so the interrupt is sent before the wait starts. The cooldown test also has no cooldown to interrupt: the previous step submits the announced block, so the tip has caught up. With the interrupt sent at the right time, createNewBlock returns a template and the test fails; announcing a header for a new block first fixes it.

A follow-up could fix these three tests, make check_order the default so every wait_and_do caller gets the check, and require do_fn to be a callable (awaiting what it returns) so an IPC call can't be passed directly again. I tried that version with all five call sites passing the method uncalled and the cooldown test fixed, and the test passes. That could be done here as well, or separately.

In commit "mining: reject negative and NaN wait timeouts from IPC clients" (2bfe24e3ad8be86c76a6530ea056964c50cc1ca9) These "Infinite timeout is accepted" tests, here and in the [`waitTipChanged` test above](https://github.com/bitcoin/bitcoin/blob/2bfe24e3ad8be86c76a6530ea056964c50cc1ca9/test/functional/interface_ipc_mining.py#L167-L171), check that an infinite timeout isn't rejected, but not that the call actually waits. They would also pass if an infinite timeout made `waitNext` or `waitTipChanged` return immediately, for example because it was clamped to zero. `template6.interruptWait()` is evaluated as an argument to `wait_and_do`, and pycapnp sends the request right then, so the interrupt reaches the node before the wait starts and the wait returns immediately. I measured both waits returning in under 4ms instead of after `wait_and_do`'s 0.1s sleep. The [Ralph review](https://review.fish.foo/report/36940-758ae2c916eb8d2127ab1949b9630cf4348b8945-2999-4.html#finding-finding%3A2) pointed out the `waitNext` case. Passing the method without calling it (`template6.interruptWait` rather than `template6.interruptWait()`) lets `wait_and_do` call it after the sleep. To catch the problem, `wait_and_do` could take an optional `check_order` argument that asserts the wait finished after `do_fn` was called, used here for the two new tests. I checked that this passes with the current code and fails with `wait finished 0.097s before do_fn was called` if `waitNext` treats an infinite timeout as zero: ```diff diff --git a/test/functional/interface_ipc_mining.py b/test/functional/interface_ipc_mining.py --- a/test/functional/interface_ipc_mining.py +++ b/test/functional/interface_ipc_mining.py @@ -168,7 +168,7 @@ class IPCMiningTest(BitcoinTestFramework): async def wait_for_tip_inf(): result = (await mining.waitTipChanged(ctx, newblockref.hash, float("inf"))).result assert_equal(len(result.hash), 0) - await wait_and_do(wait_for_tip_inf(), mining.interrupt()) + await wait_and_do(wait_for_tip_inf(), mining.interrupt, check_order=True) self.log.debug("interrupt() should abort waitTipChanged()") async def wait_for_tip(): @@ -355,7 +355,7 @@ class IPCMiningTest(BitcoinTestFramework): inf_waitoptions.feeThreshold = MAX_MONEY template8 = await mining_wait_next_template(template6, stack, ctx, inf_waitoptions) assert template8 is None - await wait_and_do(wait_for_block_inf(), template6.interruptWait()) + await wait_and_do(wait_for_block_inf(), template6.interruptWait, check_order=True) waitoptions.timeout = self.default_ipc_timeout_ms self.log.debug("interruptWait should abort the current wait") diff --git a/test/functional/test_framework/ipc_util.py b/test/functional/test_framework/ipc_util.py --- a/test/functional/test_framework/ipc_util.py +++ b/test/functional/test_framework/ipc_util.py @@ -10,6 +10,7 @@ from dataclasses import dataclass from io import BytesIO from pathlib import Path import shutil +import time from typing import Optional from test_framework.messages import CBlock @@ -45,20 +46,31 @@ async def destroying(obj, ctx): await obj.destroy(ctx) -async def wait_and_do(wait_fn, do_fn, sleep_time=0.1): +async def wait_and_do(wait_fn, do_fn, sleep_time=0.1, check_order=False): """Call wait_fn, then sleep, then call do_fn in a parallel task. Wait for - both tasks to complete.""" + both tasks to complete. + + With check_order, assert that wait_fn finishes after do_fn is called, to + catch waits that return early instead of being ended by do_fn. Pass do_fn + as a callable for this: pycapnp sends an IPC request when the method is + called, so cap.method() passed directly reaches the server before the + wait starts.""" wait_started = asyncio.Event() result = None + wait_done = None + do_called = None async def wait(): - nonlocal result + nonlocal result, wait_done wait_started.set() result = await wait_fn + wait_done = time.monotonic() async def do(): + nonlocal do_called await wait_started.wait() await asyncio.sleep(sleep_time) + do_called = time.monotonic() # Let do_fn be either a callable or an awaitable object if inspect.isawaitable(do_fn): await do_fn @@ -66,6 +78,8 @@ async def wait_and_do(wait_fn, do_fn, sleep_time=0.1): do_fn() await asyncio.gather(wait(), do()) + if check_order: + assert wait_done >= do_called, f"wait finished {do_called - wait_done:.3f}s before do_fn was called" return result ``` --- The interrupt tests already on master have the same problem: the [`interrupt()` test for `waitTipChanged`](https://github.com/bitcoin/bitcoin/blob/5ba05739881855cba25c3c05d6f82a61b8a0665f/test/functional/interface_ipc_mining.py#L168), the [`createNewBlock` cooldown test](https://github.com/bitcoin/bitcoin/blob/5ba05739881855cba25c3c05d6f82a61b8a0665f/test/functional/interface_ipc_mining.py#L252-L258) and the [`interruptWait()` test](https://github.com/bitcoin/bitcoin/blob/5ba05739881855cba25c3c05d6f82a61b8a0665f/test/functional/interface_ipc_mining.py#L349) all pass the IPC call itself, so the interrupt is sent before the wait starts. The cooldown test also has no cooldown to interrupt: the [previous step](https://github.com/bitcoin/bitcoin/blob/5ba05739881855cba25c3c05d6f82a61b8a0665f/test/functional/interface_ipc_mining.py#L233-L245) submits the announced block, so the tip has caught up. With the interrupt sent at the right time, `createNewBlock` returns a template and the test fails; announcing a header for a new block first fixes it. A follow-up could fix these three tests, make `check_order` the default so every `wait_and_do` caller gets the check, and require `do_fn` to be a callable (awaiting what it returns) so an IPC call can't be passed directly again. I tried that version with all five call sites passing the method uncalled and the cooldown test fixed, and the test passes. That could be done here as well, or separately.
enochaz (Migrated from github.com) reviewed 2026-11-26 18:56:07 +00:00
enochaz (Migrated from github.com) commented 2026-11-26 18:56:07 +00:00

Good point, I checked this locally by timing the wait in the infinite timeout tests. With the interrupt passed as a call the wait returned in about 1ms, and after passing it uncalled it took about 105ms, so it now actually waits for the interrupt.

Added your check_order change in a separate commit and used it for both tests, also added you as the co author. Thanks

The existing interrupt tests have the same issue, so they could use check_order too. Making it the default and only accepting a callable would also stop this from coming back. I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling.

Good point, I checked this locally by timing the wait in the infinite timeout tests. With the interrupt passed as a call the wait returned in about 1ms, and after passing it uncalled it took about 105ms, so it now actually waits for the interrupt. Added your `check_order` change in a separate commit and used it for both tests, also added you as the co author. Thanks The existing interrupt tests have the same issue, so they could use `check_order` too. Making it the default and only accepting a callable would also stop this from coming back. I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling.
enochaz commented 2026-11-26 19:03:05 +00:00 (Migrated from github.com)

Thanks for the review @ryanofsky, split the test change into a separate commit that adds check_order to wait_and_do, and used it for both infinite timeout tests so they now check the wait actually lasts until the interrupt. Will open a follow-up for the existing interrupt tests

Thanks for the review @ryanofsky, split the test change into a separate commit that adds `check_order` to `wait_and_do`, and used it for both infinite timeout tests so they now check the wait actually lasts until the interrupt. Will open a follow-up for the existing interrupt tests
ryanofsky (Migrated from github.com) approved these changes 2026-11-30 14:42:48 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK 525d69e3f9. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a wait_until deadline in release builds.

Thanks for adding the check_order commit! Left some possible followup suggestions but no changes need to be made here.

Code review ACK 525d69e3f9c258e61c4dde540ec0722470eab2df. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a `wait_until` deadline in release builds. Thanks for adding the `check_order` commit! Left some possible followup suggestions but no changes need to be made here.
Lines 973-974
ryanofsky (Migrated from github.com) commented 2026-11-30 14:40:00 +00:00

In commit "mining: reject negative and NaN wait timeouts from IPC clients" (525d69e3f9)

Since IPC clients can see this change, it could use a release note, like the one in the 32.1 notes for #33966 ("The IPC mining interface now rejects out-of-range block template options instead of silently clamping them"). The Ralph review suggested this too. Maybe a doc/release-notes-36940.md like:

Mining
------

- The IPC mining interface now rejects negative and NaN timeouts passed to
  `waitTipChanged` and `waitNext`. Previously, release builds treated a
  negative timeout as zero and could misbehave on NaN, and debug builds
  aborted. (#36940)
In commit "mining: reject negative and NaN wait timeouts from IPC clients" (525d69e3f9c258e61c4dde540ec0722470eab2df) Since IPC clients can see this change, it could use a release note, like the one in the 32.1 notes for #33966 ("The IPC mining interface now rejects out-of-range block template options instead of silently clamping them"). The [Ralph review](https://review.fish.foo/report/36940-525d69e3f9c258e61c4dde540ec0722470eab2df-3218-7.html#finding-finding%3A2) suggested this too. Maybe a `doc/release-notes-36940.md` like: ```markdown Mining ------ - The IPC mining interface now rejects negative and NaN timeouts passed to `waitTipChanged` and `waitNext`. Previously, release builds treated a negative timeout as zero and could misbehave on NaN, and debug builds aborted. (#36940) ```
ryanofsky (Migrated from github.com) commented 2026-11-30 14:39:59 +00:00

re: https://github.com/bitcoin/bitcoin/pull/36940#discussion_r4712425285

I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling.

Makes sense, thanks for applying this and for checking the timing. Doing the existing tests separately keeps this PR focused, and the cooldown test needs its setup fixed as well, which is unrelated to timeouts.

The Ralph review points out two more things that would fit the follow-up: wait_and_do calls do_fn without awaiting what it returns, so an error from the interrupt call is dropped, and with an infinite timeout a broken interrupt would make the test hang instead of fail, which an asyncio.wait_for deadline around those waits would prevent.

re: https://github.com/bitcoin/bitcoin/pull/36940#discussion_r4712425285 > I'd prefer to do that in a follow-up so this pr stays focused on the timeout handling. Makes sense, thanks for applying this and for checking the timing. Doing the existing tests separately keeps this PR focused, and the cooldown test needs its setup fixed as well, which is unrelated to timeouts. The [Ralph review](https://review.fish.foo/report/36940-525d69e3f9c258e61c4dde540ec0722470eab2df-3218-7.html#finding-finding%3A1) points out two more things that would fit the follow-up: `wait_and_do` calls `do_fn` without awaiting what it returns, so an error from the interrupt call is dropped, and with an infinite timeout a broken interrupt would make the test hang instead of fail, which an `asyncio.wait_for` deadline around those waits would prevent.
enochaz (Migrated from github.com) reviewed 2026-11-30 15:03:36 +00:00
Lines 973-974
enochaz (Migrated from github.com) commented 2026-11-30 15:03:36 +00:00

Thanks, added it here with some slight changes. It documents the behaviour this pr changes, so it made more sense here than in the follow up.

Thanks, added it here with some slight changes. It documents the behaviour this pr changes, so it made more sense here than in the follow up.
enochaz commented 2026-11-30 15:06:34 +00:00 (Migrated from github.com)

Thanks for the review @ryanofsky, added a release note in a separate commit. The test suggestions will go in the follow up.

Thanks for the review @ryanofsky, added a release note in a separate commit. The test suggestions will go in the follow up.
Sjors commented 2026-12-01 12:48:15 +00:00 (Migrated from github.com)
ACK d293ef600dbe056b3a1b7392f03e4f562c1026f1
nervana21 commented 2026-12-01 14:19:53 +00:00 (Migrated from github.com)

tACK d293ef600d

tACK d293ef600dbe056b3a1b7392f03e4f562c1026f1
ryanofsky (Migrated from github.com) approved these changes 2026-12-02 01:44:16 +00:00
ryanofsky (Migrated from github.com) left a comment

Code review ACK d293ef600d. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a wait_until deadline in release builds.

Only change since my last review is the new release note, which looks good and describes the old behavior accurately. Thanks for adding it!

For the follow-up, the Ralph review has another idea: the infinite waitNext test could pass sleep_time=fee_ticks_wait_s so the interrupt comes after the first fee tick, which would catch a wait that ends after one tick instead of running until interrupted.

Code review ACK d293ef600dbe056b3a1b7392f03e4f562c1026f1. This stops IPC clients from crashing debug builds of the node with negative or NaN wait timeouts, and from turning a NaN timeout into a `wait_until` deadline in release builds. Only change since my last review is the new release note, which looks good and describes the old behavior accurately. Thanks for adding it! For the follow-up, the [Ralph review](https://review.fish.foo/report/36940-d293ef600dbe056b3a1b7392f03e4f562c1026f1-3355-8.html#finding-finding%3A1) has another idea: the infinite `waitNext` test could pass `sleep_time=fee_ticks_wait_s` so the interrupt comes after the first fee tick, which would catch a wait that ends after one tick instead of running until interrupted.
Sign in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!36940
No description provided.