http: disconnect clients that never finish a request #36204

Open
janb84 wants to merge 2 commits from http-request-deadline into master AGit
janb84 commented 2026-09-09 11:55:30 +00:00 (Migrated from github.com)

The -rpcservertimeout timer only measures inactivity. Every read from a client resets it, so a client that keeps sending bytes without ever completing a request can hold the connection for ever.

Connection slots are capped by default 16 or by -rpcmaxconnections. Once those slots are taken, the server stops accepting new connections. Because no request ever completes the authentication functions are never hit.
The impact is low because RPC port binds to localhost by default, so this is a robustness fix rather than a remotely exploitable security issue.

How to reproduce

To reproduce: start a node with -rpcmaxconnections=2, open two sockets, and write "GET / HTTP/1.1\r\n" one byte at a time with ten seconds between bytes. bitcoin-cli getblockcount then hangs until one of the (trickling) sockets is closed.

The fix adds a second deadline next to the idle timer. It is armed on the first byte of a request and expires after -rpcservertimeout (the same value as the idle timer). This timer also does not resets or is extended by later reads. Completing request parsing clears the deadline, so a long-running RPC keeps its connection as before. The deadline is deferred while a worker holds the request, for the same reason the idle timer is. It is restarted while response bytes
are written, because the client cannot start a new request during that window. -rpcservertimeout=0 disables both timers. No new option is added.

Disclaimer this bug is found by utilizing ASTRA. Verified using KIMI 3 and Claude.

The -rpcservertimeout timer only measures inactivity. Every read from a client resets it, so a client that keeps sending bytes without ever completing a request can hold the connection for ever. Connection slots are capped by default 16 or by -rpcmaxconnections. Once those slots are taken, the server stops accepting new connections. Because no request ever completes the authentication functions are never hit. The impact is low because RPC port binds to localhost by default, so this is a robustness fix rather than a remotely exploitable security issue. <details> <summary> How to reproduce </summary> To reproduce: start a node with -rpcmaxconnections=2, open two sockets, and write "GET / HTTP/1.1\r\n" one byte at a time with ten seconds between bytes. bitcoin-cli getblockcount then hangs until one of the (trickling) sockets is closed. </details> The fix adds a second deadline next to the idle timer. It is armed on the first byte of a request and expires after -rpcservertimeout (the same value as the idle timer). This timer also does not resets or is extended by later reads. Completing request parsing clears the deadline, so a long-running RPC keeps its connection as before. The deadline is deferred while a worker holds the request, for the same reason the idle timer is. It is restarted while response bytes are written, because the client cannot start a new request during that window. -rpcservertimeout=0 disables both timers. No new option is added. Disclaimer this bug is found by utilizing ASTRA. Verified using KIMI 3 and Claude.
DrahtBot commented 2026-09-09 11:55:37 +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
Approach ACK winterrdog
Stale ACK pinheadmz, hodlinator

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

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #37019 (http: free idle connection slots for waiting connections at the limit by optout21)
  • #36434 (http: support unix sockets by pinheadmz)
  • #36187 (http: Restore requirement of IPv4 bind success by hodlinator)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

<!--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/36204 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36204.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36204#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 | | ---- | --------- | | Approach ACK | [winterrdog](https://github.com/bitcoin/bitcoin/pull/36204#pullrequestreview-6161987041) | | Stale ACK | [pinheadmz](https://github.com/bitcoin/bitcoin/pull/36204#pullrequestreview-6045249318), [hodlinator](https://github.com/bitcoin/bitcoin/pull/36204#pullrequestreview-6112590545) | 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 Reviewers, this pull request conflicts with the following ones: * [#37019](https://github.com/bitcoin/bitcoin/pull/37019) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/37019.svg"></sub> (http: free idle connection slots for waiting connections at the limit by optout21) * [#36434](https://github.com/bitcoin/bitcoin/pull/36434) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36434.svg"></sub> (http: support unix sockets by pinheadmz) * [#36187](https://github.com/bitcoin/bitcoin/pull/36187) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36187.svg"></sub> (http: Restore requirement of IPv4 bind success by hodlinator) If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first. <!--5faf32d7da4f0f540f40219e4f7537a3-->
hodlinator (Migrated from github.com) reviewed 2026-09-11 13:29:19 +00:00
hodlinator (Migrated from github.com) left a comment

Concept ACK 537944cb78

Concept ACK 537944cb7869039912139793b58bc6296b64eebe
hodlinator (Migrated from github.com) commented 2026-09-11 13:04:35 +00:00

remark: Was wondering whether we were missing another call to RestartRequestDeadline() when HTTPRemoteClient::Send() calls MaybeSendBytesFromBuffer() and always sets m_req_busy = false. If it succeeds in emptying the send buffer ReadyToSend() will return false and we will not set Sock::SendEvent, so the request deadline will not be reset. But m_request_since will be nullopt when the request completes parsing and is handed to the worker, so no need to bump it along in that case.

remark: Was wondering whether we were missing another call to `RestartRequestDeadline()` when `HTTPRemoteClient::Send()` calls `MaybeSendBytesFromBuffer()` and always sets `m_req_busy = false`. If it succeeds in emptying the send buffer `ReadyToSend()` will return `false` and we will not set `Sock::SendEvent`, so the request deadline will not be reset. But `m_request_since` will be `nullopt` when the request completes parsing and is handed to the worker, so no need to bump it along in that case.
Lines 1166-1169
hodlinator (Migrated from github.com) commented 2026-09-11 12:39:27 +00:00

nanonit: Feels like !m_req_busy would be the cheapest check and be the first one (same for is_idle).

nanonit: Feels like `!m_req_busy` would be the cheapest check and be the first one (same for `is_idle`).
Lines 655-658
hodlinator (Migrated from github.com) commented 2026-09-11 12:46:11 +00:00

Slightly more accurate?

    //! Timestamp for when the first byte of the current request was read,
    //! or when we last attempted to send more data to the client.
    //! nullopt when no request is in progress. Together with -rpcservertimeout
    //! this is the deadline for delivering one complete request.
    std::optional<SteadySeconds> m_request_since;

An alternative would be to always add rpcservertimeout to it when updating the value and call it m_request_deadline or m_req_read_deadline, which is easier to wrap one's head around?

Slightly more accurate? ```suggestion //! Timestamp for when the first byte of the current request was read, //! or when we last attempted to send more data to the client. //! nullopt when no request is in progress. Together with -rpcservertimeout //! this is the deadline for delivering one complete request. std::optional<SteadySeconds> m_request_since; ``` --- An alternative would be to always add `rpcservertimeout` to it when updating the value and call it `m_request_deadline` or `m_req_read_deadline`, which is easier to wrap one's head around?
hodlinator (Migrated from github.com) commented 2026-09-11 12:50:46 +00:00

Not sure time drift is an issue with these tests, but #36159's 9afe15897e switches to the mockable steady clock and freezes time in 784ac4fb9b using a FakeSteadyClock. Worth adopting here?

Not sure time drift is an issue with these tests, but #36159's 9afe15897e8dbee9429722d0db7859d895919bf4 switches to the mockable steady clock and freezes time in 784ac4fb9b4b3b9a5614e4ea54c108e1246ce50a using a `FakeSteadyClock`. Worth adopting here?
hodlinator (Migrated from github.com) commented 2026-09-11 13:06:50 +00:00

nitlinator:

        """Feed a bad HTTP request to the server one byte at a time.

(Actually the first time in this file where the casing was messed up).

nitlinator: ```suggestion """Feed a bad HTTP request to the server one byte at a time. ``` (Actually the first time in this file where the casing was messed up).
hodlinator (Migrated from github.com) commented 2026-09-11 13:09:13 +00:00

Seems to work fine without send the first byte here and instead sending it in the thread?

Seems to work fine without send the first byte here and instead sending it in the thread?
hodlinator (Migrated from github.com) commented 2026-09-11 13:19:15 +00:00

If the test fails for some reason we don't need to clean up the tricklers right? See 659671ac3d

If the test fails for some reason we don't need to clean up the `tricklers` right? See 659671ac3db7e5157178efe4d9f8bce7d92ea237
janb84 (Migrated from github.com) reviewed 2026-09-14 17:52:30 +00:00
Lines 655-658
janb84 (Migrated from github.com) commented 2026-09-14 17:52:30 +00:00

Taken thanks

Taken thanks
janb84 commented 2026-09-14 17:55:33 +00:00 (Migrated from github.com)

Rebased to latests master
Made change for the changes made by pr #36174
Incoporated suggestions made by @hodlinator
Reworked functional tests

Rebased to latests master Made change for the changes made by pr #36174 Incoporated suggestions made by @hodlinator Reworked functional tests
janb84 (Migrated from github.com) reviewed 2026-09-14 17:56:07 +00:00
janb84 (Migrated from github.com) commented 2026-09-14 17:56:07 +00:00

Yes and I reworked the test, thanks

Yes and I reworked the test, thanks
janb84 (Migrated from github.com) reviewed 2026-09-14 17:56:22 +00:00
janb84 (Migrated from github.com) commented 2026-09-14 17:56:22 +00:00

correct, thanks, see above

correct, thanks, see above
janb84 (Migrated from github.com) reviewed 2026-09-14 17:57:39 +00:00
janb84 (Migrated from github.com) commented 2026-09-14 17:57:39 +00:00

If you do not count Line 326 it's the first messed up casing indeed, stupid mistake, rectified!

If you do not count Line 326 it's the first messed up casing indeed, stupid mistake, rectified!
janb84 (Migrated from github.com) reviewed 2026-09-14 17:59:13 +00:00
janb84 (Migrated from github.com) commented 2026-09-14 17:59:13 +00:00

Not sure what to do with this, yes you are correct. But to do this correctly that PR has to land first right?

Not sure what to do with this, yes you are correct. But to do this correctly that PR has to land first right?
janb84 (Migrated from github.com) reviewed 2026-09-14 18:03:47 +00:00
Lines 1184-1187
janb84 (Migrated from github.com) commented 2026-09-14 18:03:47 +00:00

Have to pushback on this one, m_req_busy is mostly false so the negate makes that true. It would cause an extra check that is mostly true and therefor does not short the evaluation. I think the rpcservertimeout.count() is the cheapest one, given it's already in a register.

Have to pushback on this one, m_req_busy is mostly false so the negate makes that true. It would cause an extra check that is mostly true and therefor does not short the evaluation. I think the `rpcservertimeout.count()` is the cheapest one, given it's already in a register.
janb84 (Migrated from github.com) reviewed 2026-09-14 18:12:14 +00:00
janb84 (Migrated from github.com) commented 2026-09-14 18:12:14 +00:00

After some checking, changed the comment. Do not think extra action is needed in send(), the extra call to RestartRequestDeadline() would not do a thing because of the empty m_reqeust_since. Imho, happy to be wrong.

After some checking, changed the comment. Do not think extra action is needed in send(), the extra call to `RestartRequestDeadline()` would not do a thing because of the empty m_reqeust_since. Imho, happy to be wrong.
DrahtBot commented 2026-09-16 08:53:15 +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).
janb84 commented 2026-09-17 08:21:40 +00:00 (Migrated from github.com)

Rebased and adjusted the function naming.

Rebased and adjusted the function naming.
hodlinator (Migrated from github.com) reviewed 2026-09-17 10:18:22 +00:00
Lines 1184-1187
hodlinator (Migrated from github.com) commented 2026-09-17 10:18:22 +00:00

Would expect m_req_busy to be true most of the time, a worker thread is busy processing the request. (The exception being very bad connections with larger requests which take time to receive). But maybe there's something with keep-alive connections that make them tend to linger after the response was sent.

I think the rpcservertimeout.count() is the cheapest one, given it's already in a register.

Agree on this.

Would expect `m_req_busy` to be true most of the time, a worker thread is busy processing the request. (The exception being very bad connections with larger requests which take time to receive). But maybe there's something with keep-alive connections that make them tend to linger after the response was sent. > I think the rpcservertimeout.count() is the cheapest one, given it's already in a register. Agree on this.
hodlinator (Migrated from github.com) commented 2026-09-17 10:19:18 +00:00

Or you could incorporate parts of it into this one? I'm happy however the changes get in.

Or you could incorporate parts of it into this one? I'm happy however the changes get in.
hodlinator (Migrated from github.com) reviewed 2026-09-18 13:13:04 +00:00
hodlinator (Migrated from github.com) left a comment

Reviewed 99e880356b

Nice how you cleaned up the test, makes it easy to grasp.

Reviewed 99e880356bac7ab6b0ed9f3fb1ff5cfdab4a4266 Nice how you cleaned up the test, makes it easy to grasp.
hodlinator (Migrated from github.com) commented 2026-09-18 13:10:57 +00:00

nit: Maybe could switch commits from {fix+test} to {characterization-test+fix}? That way the ancestor commits CI job can also verify the pre-fix behavior (edit: and humans can clearly see the behavior-change). See https://github.com/bitcoin/bitcoin/compare/master...hodlinator:bitcoin:pr/36204_suggestions

nit: Maybe could switch commits from {fix+test} to {characterization-test+fix}? That way the ancestor commits CI job can also verify the pre-fix behavior (edit: and humans can clearly see the behavior-change). See https://github.com/bitcoin/bitcoin/compare/master...hodlinator:bitcoin:pr/36204_suggestions
hodlinator (Migrated from github.com) commented 2026-09-18 12:43:46 +00:00

Why would we allow less than RPCSERVERTIMEOUT (which is only 2)?

        assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}"
Why would we allow *less* than `RPCSERVERTIMEOUT` (which is only `2`)? ```suggestion assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}" ```
First-time contributor

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.

🟠 Minor · -rpcservertimeout also cuts off progressing body uploads

The new completion budget can disconnect legitimate body uploads despite continued receive progress; no affected deployment has been identified.

Location: src/httpserver.cpp:1241 (head).

🟠 Minor · The final clock advance can race with send bookkeeping

The unit test can exhaust its disconnect retries if the I/O thread records both timer timestamps after the final mock-clock advance; this failure has not been observed.

Location: src/test/httpserver_tests.cpp:1075 (head).

🟠 Minor · Debug-log capture starts after the deadline can fire

A roughly two-second main-thread stall can make the functional test miss the expected deadline message and fail despite correct server behavior; this failure has not been observed.

Location: test/functional/interface_http.py:493 (head).

🔵 Suggestion · The I/O-loop test's final disconnect does not isolate the deadline

The final timeout + 1s advance expires the idle timer too, so the I/O-loop test can pass without a working completion deadline for the second pipelined request.

Location: src/test/httpserver_tests.cpp:1075 (head).


Reviewed: 1dfe11b66622 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:312ddb2095238aa2ca395a9cc39b05ab5a38a7177afbdb0d69098df9c3e0bef9:9a7f127b15c6116c267953d38288a9f17ec7c7bcd3a975fb71a2db8bfd974dbf --> <!-- ralph-base:afa492e233868bcf4799bb62943baa28017938f6 --> <!-- ralph-head:1dfe11b66622daa3e0699e962480fb5d5f653616 --> <!-- ralph-case:48c6ac52040a84f9758bdb59e7cd22363a3f8952cf2f6e7b4e11afc9a84528d6 --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🟠 Minor · `-rpcservertimeout` also cuts off progressing body uploads** The new completion budget can disconnect legitimate body uploads despite continued receive progress; no affected deployment has been identified. Location: [`src/httpserver.cpp:1241`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1dfe11b66622daa3e0699e962480fb5d5f653616/src/httpserver.cpp#L1241>) (head). **🟠 Minor · The final clock advance can race with send bookkeeping** The unit test can exhaust its disconnect retries if the I/O thread records both timer timestamps after the final mock-clock advance; this failure has not been observed. Location: [`src/test/httpserver_tests.cpp:1075`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1dfe11b66622daa3e0699e962480fb5d5f653616/src/test/httpserver_tests.cpp#L1075>) (head). **🟠 Minor · Debug-log capture starts after the deadline can fire** A roughly two-second main-thread stall can make the functional test miss the expected deadline message and fail despite correct server behavior; this failure has not been observed. Location: [`test/functional/interface_http.py:493`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1dfe11b66622daa3e0699e962480fb5d5f653616/test/functional/interface_http.py#L493>) (head). **🔵 Suggestion · The I/O-loop test's final disconnect does not isolate the deadline** The final `timeout + 1s` advance expires the idle timer too, so the I/O-loop test can pass without a working completion deadline for the second pipelined request. Location: [`src/test/httpserver_tests.cpp:1075`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/1dfe11b66622daa3e0699e962480fb5d5f653616/src/test/httpserver_tests.cpp#L1075>) (head). <!-- Review tier: sensitive --> --- Reviewed: [`1dfe11b66622`](<https://git.fish.foo/bitcoin/bitcoin/commit/1dfe11b66622daa3e0699e962480fb5d5f653616>) · [Review report](<https://review.fish.foo/report/36204-1dfe11b66622daa3e0699e962480fb5d5f653616-3391-8.html>) · [Previous reports](<https://review.fish.foo/traces/36204/>) [permalink](<https://review.fish.foo/report/36204-1dfe11b66622daa3e0699e962480fb5d5f653616-3391-8.html>)
DrahtBot commented 2026-10-19 09:20:51 +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).
pinheadmz commented 2026-10-30 15:12:33 +00:00 (Migrated from github.com)

concept ACK, this mitigates slow-loris and perhaps most importantly, mitigates the LLM "findings" reports we keep getting 👍

concept ACK, this mitigates slow-loris and perhaps most importantly, mitigates the LLM "findings" reports we keep getting 👍
janb84 (Migrated from github.com) reviewed 2026-11-02 15:59:02 +00:00
janb84 (Migrated from github.com) commented 2026-11-02 15:59:02 +00:00

Given your PR was merged, I now changed to code to use mockable steady clock

Given your PR was merged, I now changed to code to use mockable steady clock
hodlinator (Migrated from github.com) reviewed 2026-11-03 14:13:18 +00:00
hodlinator (Migrated from github.com) left a comment

Reviewed bfbe9a6474

Reviewed bfbe9a647407071af2d9a169db3c275748cd8bcc
hodlinator (Migrated from github.com) commented 2026-11-03 11:16:11 +00:00

nit: Clearer through one of these?

    //! this is the deadline for delivering one complete request to the server.
    //! this is the deadline for receiving one complete request.
nit: Clearer through one of these? ```suggestion //! this is the deadline for delivering one complete request to the server. ``` ```suggestion //! this is the deadline for receiving one complete request. ```
hodlinator (Migrated from github.com) commented 2026-11-03 12:02:51 +00:00

nit: Clarify that NotIdleAt() is critical?

        BOOST_CHECK(client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false));
        client->NotIdleAt(now());
        BOOST_CHECK(!client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false));
nit: Clarify that `NotIdleAt()` is critical? ```suggestion BOOST_CHECK(client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false)); client->NotIdleAt(now()); BOOST_CHECK(!client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false)); ```
hodlinator (Migrated from github.com) commented 2026-11-03 12:04:08 +00:00

nit: Show that timeout argument is indeed the deciding factor?

        BOOST_CHECK(client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false));
        BOOST_CHECK(!client->ShouldDisconnect(now(), 0s, /*disconnect_all=*/false));
nit: Show that timeout argument is indeed the deciding factor? ```suggestion BOOST_CHECK(client->ShouldDisconnect(now(), timeout, /*disconnect_all=*/false)); BOOST_CHECK(!client->ShouldDisconnect(now(), 0s, /*disconnect_all=*/false)); ```
hodlinator (Migrated from github.com) commented 2026-11-03 13:55:48 +00:00

nit: Might as well skip string_view?

    const std::string first_request{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"};
    const std::string second_request_start{"GET /second HTTP/1.1\r\n"};
    const std::string data{first_request + second_request_start};
nit: Might as well skip `string_view`? ```suggestion const std::string first_request{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"}; const std::string second_request_start{"GET /second HTTP/1.1\r\n"}; const std::string data{first_request + second_request_start}; ```
hodlinator (Migrated from github.com) commented 2026-11-03 12:21:46 +00:00

Why are non of the other unit tests doing this cleanup? I tried variants of the following diff with the BOOST_REQUIRE(false) in different places but the unit tests seem to terminate okay without deadlocking:

--- a/src/test/httpserver_tests.cpp
+++ b/src/test/httpserver_tests.cpp
@@ -1025,20 +1025,6 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests)
     BOOST_REQUIRE(server.BindAndStartListening(addr_bind));
     server.StartSocketsThreads();
 
-    // Stop the I/O thread however this test exits. A failed BOOST_REQUIRE
-    // would otherwise leave it running against this test's stack, which
-    // hangs the test cases after it.
-    struct StopServer {
-        HTTPServer& server;
-        ~StopServer()
-        {
-            server.InterruptNet();
-            server.JoinSocketsThreads();
-            server.ClearConnectedClients();
-            server.StopListening();
-        }
-    } stop_server{server};
-
     // A complete request followed by the start of a second one. The second
     // request's deadline starts once the first one's reply is written.
     constexpr std::string_view first_request{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"};
@@ -1101,6 +1087,13 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests)
         std::this_thread::sleep_for(10ms);
         BOOST_REQUIRE(--attempts > 0);
     }
+
+    BOOST_REQUIRE(false);
+
+    server.InterruptNet();
+    server.JoinSocketsThreads();
+    server.ClearConnectedClients();
+    server.StopListening();
 }
 
 BOOST_AUTO_TEST_CASE(http_server_socket_tests)
Why are non of the other unit tests doing this cleanup? I tried variants of the following diff with the `BOOST_REQUIRE(false)` in different places but the unit tests seem to terminate okay without deadlocking: ```diff --- a/src/test/httpserver_tests.cpp +++ b/src/test/httpserver_tests.cpp @@ -1025,20 +1025,6 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests) BOOST_REQUIRE(server.BindAndStartListening(addr_bind)); server.StartSocketsThreads(); - // Stop the I/O thread however this test exits. A failed BOOST_REQUIRE - // would otherwise leave it running against this test's stack, which - // hangs the test cases after it. - struct StopServer { - HTTPServer& server; - ~StopServer() - { - server.InterruptNet(); - server.JoinSocketsThreads(); - server.ClearConnectedClients(); - server.StopListening(); - } - } stop_server{server}; - // A complete request followed by the start of a second one. The second // request's deadline starts once the first one's reply is written. constexpr std::string_view first_request{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"}; @@ -1101,6 +1087,13 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests) std::this_thread::sleep_for(10ms); BOOST_REQUIRE(--attempts > 0); } + + BOOST_REQUIRE(false); + + server.InterruptNet(); + server.JoinSocketsThreads(); + server.ClearConnectedClients(); + server.StopListening(); } BOOST_AUTO_TEST_CASE(http_server_socket_tests) ```
janb84 (Migrated from github.com) reviewed 2026-11-03 14:15:45 +00:00
janb84 (Migrated from github.com) commented 2026-11-03 14:15:45 +00:00

Good catch, not sure why i though this was needed. Taken

Good catch, not sure why i though this was needed. Taken
janb84 (Migrated from github.com) reviewed 2026-11-04 14:28:16 +00:00
janb84 (Migrated from github.com) commented 2026-11-04 14:28:16 +00:00

Because of the comment I do not think 2 separate assignments are not needed for clarity, have removed those to just do one without concatenation.

Because of the comment I do not think 2 separate assignments are not needed for clarity, have removed those to just do one without concatenation.
janb84 (Migrated from github.com) reviewed 2026-11-04 14:30:15 +00:00
janb84 (Migrated from github.com) commented 2026-11-04 14:30:15 +00:00

Taken and have added extra reset so that the test become stronger.

Taken and have added extra reset so that the test become stronger.
janb84 (Migrated from github.com) reviewed 2026-11-04 14:30:48 +00:00
janb84 (Migrated from github.com) commented 2026-11-04 14:30:48 +00:00

Taken

Taken
janb84 (Migrated from github.com) reviewed 2026-11-04 14:31:03 +00:00
janb84 (Migrated from github.com) commented 2026-11-04 14:31:03 +00:00

took option A

took option A
janb84 (Migrated from github.com) reviewed 2026-11-04 14:35:20 +00:00
janb84 (Migrated from github.com) commented 2026-11-04 14:35:20 +00:00

taken (not all), have aligned it with the other tests.

taken (not all), have aligned it with the other tests.
janb84 commented 2026-11-04 14:42:19 +00:00 (Migrated from github.com)

Incorporated the suggested changes by the review from hodlinator.
Changed a line in httpserver.cpp (L 1242) !m_req_busy => Assume(!m_req_busy) because that state (armed and busy) cannot happen on production, reduces test code.

Incorporated the suggested changes by the review from hodlinator. Changed a line in httpserver.cpp (L 1242) `!m_req_busy` => `Assume(!m_req_busy)` because that state (armed and busy) cannot happen on production, reduces test code.
hodlinator (Migrated from github.com) reviewed 2026-11-09 16:11:02 +00:00
hodlinator (Migrated from github.com) commented 2026-11-09 16:11:02 +00:00

Agree, the paths /first & /second are enough. Could return to constexpr std::string_view:

--- a/src/test/httpserver_tests.cpp
+++ b/src/test/httpserver_tests.cpp
@@ -1007,8 +1007,8 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests)
 
     // A complete request followed by the start of a second one. The second
     // request's deadline starts once the first one's reply is written.
-    const std::string data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"
-                           "GET /second HTTP/1.1\r\n"};
+    constexpr std::string_view data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"
+                                    "GET /second HTTP/1.1\r\n"};
     std::shared_ptr<GateSock::Pipes> pipes{ConnectClient<GateSock>(std::as_bytes(std::span(data)))};
 
     // Answer the first request with no send tokens, so the whole reply stays
Agree, the paths /first & /second are enough. Could return to `constexpr std::string_view`: ```diff --- a/src/test/httpserver_tests.cpp +++ b/src/test/httpserver_tests.cpp @@ -1007,8 +1007,8 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests) // A complete request followed by the start of a second one. The second // request's deadline starts once the first one's reply is written. - const std::string data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n" - "GET /second HTTP/1.1\r\n"}; + constexpr std::string_view data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n" + "GET /second HTTP/1.1\r\n"}; std::shared_ptr<GateSock::Pipes> pipes{ConnectClient<GateSock>(std::as_bytes(std::span(data)))}; // Answer the first request with no send tokens, so the whole reply stays ```
janb84 (Migrated from github.com) reviewed 2026-11-10 09:47:08 +00:00
janb84 (Migrated from github.com) commented 2026-11-10 09:47:08 +00:00

taken

taken
pinheadmz (Migrated from github.com) approved these changes 2026-11-24 20:50:51 +00:00
pinheadmz (Migrated from github.com) left a comment

ACK 2f699f91f1

Built and tested on macos/arm64. Played with the new timeout using socat to manually make very slow (and then fast) HTTP requests. Mutated the patch a few places to observe test failure, and watched the packets in wireshark throughout to see the trickle.

Reviewed the code and left a few aesthetic nits, no blockers. I found the unit test with the token counter a bit hard to follow but after trying to simplify it myself a few different ways I ended up understanding it and agreeing with the approach.

kimi-k3 gave up trying to write a slow loris attack against this patch ;-)

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 2f699f91f12e163229edc979769af58457a5f6d0
-----BEGIN PGP SIGNATURE-----

iQJPBAEBCAA5FiEE5hdzzW4BBA4vG9eM5+KYS2KJyToFAmsF95QbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMCwzAAoJEOfimEtiick6mF4QANnw9RpPRMezeATOiSHO
q/wt1wVotMJKGJsy5xRwgW+tuegFhKNB73JNT7uC+KNq4KE8InT/Qr4+QqN0mOAN
rQ65V/PzMhVNs7QXT/waw2iPDPMKYY3QooPkvBaviWSrsKuk/DhmbMZw57iJdWqH
IMF1crTEUzcSUmS3S+EawwTyPBTv9vVaYiki1eZBdzAn14mHkKkNALTu33fbvhWd
DcOPrFyrM+9V+OYwHgiKhHv9UOv3tMGpGXGZU2Fs1xBBeq3snslaMhQv7FTzQCs9
YDKdeoehv3/IRRckzoe1OlvtyQ5grkvSFcAHHurDdq2qtV0okhG5zasFkS5K4Aiw
6M4dHtZvmdWn63Vg7NyB/FznGUtl27/yEOiQxmvyOM95dbec5Mbzq3epgoxfvFHZ
jzzwuhR9RIUIlv8Ng2M4kgAcYx6duQpxfzgmbi+py/XWNpk9kIbMi6yNGp2MLupQ
BpriQK890kx4jdY/s0959OeQ5VM0Q31S861duuY4S5rFPHkFsvGKpwg/prZIPsBu
qYcgCrdpLbo6snbD19GxsfLoTcO0BZ2z2BbuAExzWRRdrcZxV+HvrObc32GpGQik
bXVKqsK6JZrHQQmJ45d9pr3OV4HNflsy79qjOseGU+oMvmSh44irHkFO5FKbwBz1
FFtnnO838TnxgW03FAkCFgLr
=IX/c
-----END PGP SIGNATURE-----

pinheadmz's public key is on openpgp.org

ACK 2f699f91f12e163229edc979769af58457a5f6d0 Built and tested on macos/arm64. Played with the new timeout using `socat` to manually make very slow (and then fast) HTTP requests. Mutated the patch a few places to observe test failure, and watched the packets in wireshark throughout to see the trickle. Reviewed the code and left a few aesthetic nits, no blockers. I found the unit test with the token counter a bit hard to follow but after trying to simplify it myself a few different ways I ended up understanding it and agreeing with the approach. kimi-k3 gave up trying to write a slow loris attack against this patch ;-) <details><summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK 2f699f91f12e163229edc979769af58457a5f6d0 -----BEGIN PGP SIGNATURE----- iQJPBAEBCAA5FiEE5hdzzW4BBA4vG9eM5+KYS2KJyToFAmsF95QbFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMCwzAAoJEOfimEtiick6mF4QANnw9RpPRMezeATOiSHO q/wt1wVotMJKGJsy5xRwgW+tuegFhKNB73JNT7uC+KNq4KE8InT/Qr4+QqN0mOAN rQ65V/PzMhVNs7QXT/waw2iPDPMKYY3QooPkvBaviWSrsKuk/DhmbMZw57iJdWqH IMF1crTEUzcSUmS3S+EawwTyPBTv9vVaYiki1eZBdzAn14mHkKkNALTu33fbvhWd DcOPrFyrM+9V+OYwHgiKhHv9UOv3tMGpGXGZU2Fs1xBBeq3snslaMhQv7FTzQCs9 YDKdeoehv3/IRRckzoe1OlvtyQ5grkvSFcAHHurDdq2qtV0okhG5zasFkS5K4Aiw 6M4dHtZvmdWn63Vg7NyB/FznGUtl27/yEOiQxmvyOM95dbec5Mbzq3epgoxfvFHZ jzzwuhR9RIUIlv8Ng2M4kgAcYx6duQpxfzgmbi+py/XWNpk9kIbMi6yNGp2MLupQ BpriQK890kx4jdY/s0959OeQ5VM0Q31S861duuY4S5rFPHkFsvGKpwg/prZIPsBu qYcgCrdpLbo6snbD19GxsfLoTcO0BZ2z2BbuAExzWRRdrcZxV+HvrObc32GpGQik bXVKqsK6JZrHQQmJ45d9pr3OV4HNflsy79qjOseGU+oMvmSh44irHkFO5FKbwBz1 FFtnnO838TnxgW03FAkCFgLr =IX/c -----END PGP SIGNATURE----- ``` pinheadmz's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/E61773CD6E01040E2F1BD78CE7E2984B6289C93A) </details>
pinheadmz (Migrated from github.com) commented 2026-11-24 18:55:02 +00:00

b5104d4d41

optional style nit, could use a one-liner and keep the function name

  public:
      using HTTPRemoteClient::SetIdleSince;
b5104d4d4174df336e67480957bb7e0248ce655d optional style nit, could use a one-liner and keep the function name ```cpp public: using HTTPRemoteClient::SetIdleSince; ```
pinheadmz (Migrated from github.com) commented 2026-11-24 18:43:20 +00:00

b5104d4d41

Could use a DebugLogHelper to assert the reason for disconnecting

b5104d4d4174df336e67480957bb7e0248ce655d Could use a `DebugLogHelper` to assert the reason for disconnecting
pinheadmz (Migrated from github.com) commented 2026-11-24 18:50:02 +00:00

b5104d4d41

nit, I'd say the deadline is actually now + timeout, the reset call moves the interval start time to now.

b5104d4d4174df336e67480957bb7e0248ce655d nit, I'd say the deadline is actually `now + timeout`, the reset call moves the interval *start* time to now.
janb84 (Migrated from github.com) reviewed 2026-11-27 12:08:58 +00:00
janb84 (Migrated from github.com) commented 2026-11-27 12:08:58 +00:00

taken, makes it a bit clearer.

taken, makes it a bit clearer.
janb84 (Migrated from github.com) reviewed 2026-11-27 12:09:09 +00:00
janb84 (Migrated from github.com) commented 2026-11-27 12:09:09 +00:00

you are correct sir, taken

you are correct sir, taken
janb84 (Migrated from github.com) reviewed 2026-11-27 12:44:12 +00:00
janb84 (Migrated from github.com) commented 2026-11-27 12:44:12 +00:00

taken

taken
janb84 commented 2026-11-27 12:44:49 +00:00 (Migrated from github.com)

Pushed update to fix the lint issue & suggestions of @pinheadmz taken.

Pushed update to fix the lint issue & suggestions of @pinheadmz taken.
hodlinator (Migrated from github.com) reviewed 2026-11-30 12:31:54 +00:00
hodlinator (Migrated from github.com) commented 2026-11-30 12:27:35 +00:00

Was about to write something similar, using seems good!

However, the first commit still introduces NotIdleAt while the second one changes it to SetIdleSince. Seems like all changes to src/test/httpserver_tests.cpp in the second commit could be cherrypicked into the first commit.

Was about to write something similar, `using` seems good! *However*, the first commit still introduces `NotIdleAt` while the second one changes it to `SetIdleSince`. Seems like all changes to src/test/httpserver_tests.cpp in the second commit could be cherrypicked into the first commit.
hodlinator (Migrated from github.com) commented 2026-11-30 12:23:28 +00:00

If you touch again:

    constexpr std::string_view data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n"
                                    "GET /second HTTP/1.1\r\n"};
If you touch again: ```suggestion constexpr std::string_view data{"GET /first HTTP/1.1\r\nHost: 127.0.0.1\r\n\r\n" "GET /second HTTP/1.1\r\n"}; ```
hodlinator (Migrated from github.com) approved these changes 2026-11-30 14:35:37 +00:00
hodlinator (Migrated from github.com) left a comment

ACK b6dfbd6f71

Nice to avert slow-loris attacks even though RPC is a slightly trusted interface.

I think one could tighten up the functional test a little bit more, but not blocking.

ACK b6dfbd6f711d1e1069a612d5d91dfaca875429e5 Nice to avert slow-loris attacks even though RPC is a slightly trusted interface. I think one could tighten up the functional test a little bit more, but not blocking.
hodlinator (Migrated from github.com) commented 2026-11-30 12:59:39 +00:00

Could add comment to explain why we don't store send_tokens directly in the socket type.

        /**
         * Since SocketTestingSetup::ConnectClient() creates the socket and
         * returns the Pipes we store the state to be mutated here.
         */
        struct Pipes : DynSock::Pipes {
Could add comment to explain why we don't store `send_tokens` directly in the socket type. ```suggestion /** * Since SocketTestingSetup::ConnectClient() creates the socket and * returns the Pipes we store the state to be mutated here. */ struct Pipes : DynSock::Pipes { ```
hodlinator (Migrated from github.com) commented 2026-11-30 13:06:56 +00:00

remark: Would be nice if the ctor parameter where called request_dispatcher so we could go

    HTTPServer server{/*request_dispatcher=*/[&](std::unique_ptr<HTTPRequest>&& req) {

But unfortunately it's func.

remark: Would be nice if the ctor parameter where called `request_dispatcher` so we could go ```suggestion HTTPServer server{/*request_dispatcher=*/[&](std::unique_ptr<HTTPRequest>&& req) { ``` But unfortunately it's `func`.
hodlinator (Migrated from github.com) commented 2026-11-30 13:16:37 +00:00

Might as well declare step as size_t:

--- a/src/test/httpserver_tests.cpp
+++ b/src/test/httpserver_tests.cpp
@@ -1042,11 +1042,11 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests)
     // it on every pass that tries to send.
     std::string received;
     char buf[0x10000] = {};
-    for (int step{0}; step < 5; ++step) {
+    for (size_t step{0}; step < 5; ++step) {
         clock += timeout / 3;
         pipes->send_tokens += 1;
         attempts = 6000;
-        while (received.size() <= static_cast<size_t>(step) && server.GetConnectionsCount() == 1) {
+        while (received.size() <= step && server.GetConnectionsCount() == 1) {
             const ssize_t bytes_read{pipes->send.GetBytes(buf, sizeof(buf), 0)};
             if (bytes_read > 0) received.append(buf, bytes_read);
             std::this_thread::sleep_for(10ms);
Might as well declare `step` as `size_t`: ```diff --- a/src/test/httpserver_tests.cpp +++ b/src/test/httpserver_tests.cpp @@ -1042,11 +1042,11 @@ BOOST_AUTO_TEST_CASE(http_request_deadline_io_loop_tests) // it on every pass that tries to send. std::string received; char buf[0x10000] = {}; - for (int step{0}; step < 5; ++step) { + for (size_t step{0}; step < 5; ++step) { clock += timeout / 3; pipes->send_tokens += 1; attempts = 6000; - while (received.size() <= static_cast<size_t>(step) && server.GetConnectionsCount() == 1) { + while (received.size() <= step && server.GetConnectionsCount() == 1) { const ssize_t bytes_read{pipes->send.GetBytes(buf, sizeof(buf), 0)}; if (bytes_read > 0) received.append(buf, bytes_read); std::this_thread::sleep_for(10ms); ```
hodlinator (Migrated from github.com) commented 2026-11-30 14:15:10 +00:00

It's slightly unclear whether the trickling completes or not. One could assert the return value from the trickling function:

--- a/test/functional/interface_http.py
+++ b/test/functional/interface_http.py
--- a/test/functional/interface_http.py
+++ b/test/functional/interface_http.py
@@ -474,32 +474,34 @@ class HTTPBasicsTest (BitcoinTestFramework):
                     conn.send_raw(bad_http_request[i:i + 1])
                 except NETWORK_ERRORS:
                     # The server disconnected mid-write.
-                    return
+                    return "errors"
                 if stop_trickling.wait(RPCSERVERTIMEOUT / 4):
-                    return
+                    return "stopped"
+            return "completed"
 
         start = time.monotonic()
-        send_thread = threading.Thread(target=trickle_request, args=(conn,))
-        send_thread.start()
-
-        # The server is full, so a new client waits in the kernel's accept queue.
-        # It only gets served if the trickling doesn't push the deadline back.
-        # The extra time on the timeout is slack for a slow CI machine. The log
-        # check keeps this from passing on an idle timeout instead.
-        waiting_conn = BitcoinHTTPConnection(self.node)
-        waiting_conn.set_timeout(RPCSERVERTIMEOUT + 2)
-        with self.node.assert_debug_log(["took too long to send a complete request"]):
-            waiting_conn.post_raw('/', '{"method": "getblockcount"}')
-            response = waiting_conn.recv_raw()
-            duration = time.monotonic() - start
-            assert response.startswith(b"HTTP/1.1 200 OK")
-
-        # The slot isn't freed before the deadline. `start` is taken before the
-        # first byte goes out, so the server can't have waited longer than this.
-        assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}"
-
-        stop_trickling.set()
-        send_thread.join()
+        with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex:
+            future = ex.submit(trickle_request, conn)
+
+            # The server is full, so a new client waits in the kernel's accept queue.
+            # It only gets served if the trickling doesn't push the deadline back.
+            # The extra time on the timeout is slack for a slow CI machine. The log
+            # check keeps this from passing on an idle timeout instead.
+            waiting_conn = BitcoinHTTPConnection(self.node)
+            waiting_conn.set_timeout(RPCSERVERTIMEOUT + 2)
+            with self.node.assert_debug_log(["took too long to send a complete request"]):
+                waiting_conn.post_raw('/', '{"method": "getblockcount"}')
+                response = waiting_conn.recv_raw()
+                duration = time.monotonic() - start
+                assert response.startswith(b"HTTP/1.1 200 OK")
+
+            # The slot isn't freed before the deadline. `start` is taken before the
+            # first byte goes out, so the server can't have waited longer than this.
+            assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}"
+
+            stop_trickling.set()
+            # The trickling has been aborted due to request timeout.
+            assert future.result(timeout=5), "errors"
 
         # Close the waiting connection for clean up, so the next restart's stop
         # RPC doesn't wait for its idle timeout.
It's slightly unclear whether the trickling completes or not. One could assert the return value from the trickling function: ```diff --- a/test/functional/interface_http.py +++ b/test/functional/interface_http.py --- a/test/functional/interface_http.py +++ b/test/functional/interface_http.py @@ -474,32 +474,34 @@ class HTTPBasicsTest (BitcoinTestFramework): conn.send_raw(bad_http_request[i:i + 1]) except NETWORK_ERRORS: # The server disconnected mid-write. - return + return "errors" if stop_trickling.wait(RPCSERVERTIMEOUT / 4): - return + return "stopped" + return "completed" start = time.monotonic() - send_thread = threading.Thread(target=trickle_request, args=(conn,)) - send_thread.start() - - # The server is full, so a new client waits in the kernel's accept queue. - # It only gets served if the trickling doesn't push the deadline back. - # The extra time on the timeout is slack for a slow CI machine. The log - # check keeps this from passing on an idle timeout instead. - waiting_conn = BitcoinHTTPConnection(self.node) - waiting_conn.set_timeout(RPCSERVERTIMEOUT + 2) - with self.node.assert_debug_log(["took too long to send a complete request"]): - waiting_conn.post_raw('/', '{"method": "getblockcount"}') - response = waiting_conn.recv_raw() - duration = time.monotonic() - start - assert response.startswith(b"HTTP/1.1 200 OK") - - # The slot isn't freed before the deadline. `start` is taken before the - # first byte goes out, so the server can't have waited longer than this. - assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}" - - stop_trickling.set() - send_thread.join() + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as ex: + future = ex.submit(trickle_request, conn) + + # The server is full, so a new client waits in the kernel's accept queue. + # It only gets served if the trickling doesn't push the deadline back. + # The extra time on the timeout is slack for a slow CI machine. The log + # check keeps this from passing on an idle timeout instead. + waiting_conn = BitcoinHTTPConnection(self.node) + waiting_conn.set_timeout(RPCSERVERTIMEOUT + 2) + with self.node.assert_debug_log(["took too long to send a complete request"]): + waiting_conn.post_raw('/', '{"method": "getblockcount"}') + response = waiting_conn.recv_raw() + duration = time.monotonic() - start + assert response.startswith(b"HTTP/1.1 200 OK") + + # The slot isn't freed before the deadline. `start` is taken before the + # first byte goes out, so the server can't have waited longer than this. + assert duration >= RPCSERVERTIMEOUT, f"Slot reclaimed too fast: {duration}" + + stop_trickling.set() + # The trickling has been aborted due to request timeout. + assert future.result(timeout=5), "errors" # Close the waiting connection for clean up, so the next restart's stop # RPC doesn't wait for its idle timeout. ```
janb84 (Migrated from github.com) reviewed 2026-12-01 13:39:13 +00:00
janb84 (Migrated from github.com) commented 2026-12-01 13:39:13 +00:00

Taken and adapted

Taken and adapted
janb84 (Migrated from github.com) reviewed 2026-12-01 13:39:23 +00:00
janb84 (Migrated from github.com) commented 2026-12-01 13:39:23 +00:00

taken

taken
janb84 (Migrated from github.com) reviewed 2026-12-01 13:39:45 +00:00
janb84 (Migrated from github.com) commented 2026-12-01 13:39:45 +00:00

taken

taken
janb84 (Migrated from github.com) reviewed 2026-12-01 13:42:32 +00:00
janb84 (Migrated from github.com) commented 2026-12-01 13:42:32 +00:00

If correct and CI builds now, the form is now changed to {characterization-test , fix + flipped assertions + new deadline tests)

If correct and CI builds now, the form is now changed to {characterization-test , fix + flipped assertions + new deadline tests)
janb84 commented 2026-12-01 13:47:04 +00:00 (Migrated from github.com)

Reviewers, sorry. I have changed the form now to {characterization-test , fix + flipped assertions + new deadline tests). (where new is not new from a reviewer viewpoint but from master / code viewpoint)
So mainly the order is changed not the tests & code.

Pushed new updates that addresses suggestions by @hodlinator and drahtbot

Reviewers, sorry. I have changed the form now to {characterization-test , fix + flipped assertions + new deadline tests). (where new is not new from a reviewer viewpoint but from master / code viewpoint) So mainly the order is changed not the tests & code. Pushed new updates that addresses suggestions by @hodlinator and drahtbot
winterrdog (Migrated from github.com) reviewed 2026-12-03 01:13:30 +00:00
winterrdog (Migrated from github.com) left a comment

approach ACK

approach ACK
winterrdog (Migrated from github.com) reviewed 2026-12-03 01:14:01 +00:00
winterrdog (Migrated from github.com) commented 2026-12-03 01:14:01 +00:00

on NetBSD 11.0, check_trickled_request_timeout() fails. waiting_conn.recv_raw() raises TimeoutError because the client-side timeout (RPCSERVERTIMEOUT + 2) expires before a response shows up

on NetBSD, increasing the client-side timeout to any value >= RPCSERVERTIMEOUT * 3 makes the test pass. RPCSERVERTIMEOUT * 2 is still not enough. the test also passes if i remove the client-side timeout altogether. Linux passes without any of these changes, using the original RPCSERVERTIMEOUT + 2

what i cannot tell yet is why it breaks. in the failing run's debug.log, i never see HTTP client took too long to send a complete request


some logs:

test output log
...
2026-11-17T00:23:21.273664Z TestFramework (INFO): Client did not finish sending request before connection was terminated
2026-11-17T00:23:21.279598Z TestFramework (INFO): Check -rpcservertimeout
2026-11-17T00:23:23.747429Z TestFramework (INFO): Check that -rpcservertimeout disconnects clients that never finish a request
2026-11-17T00:23:26.149963Z TestFramework (ERROR): Unexpected exception:
Traceback (most recent call last):
  File "/home/user404/bitcoin/test/functional/test_framework/test_framework.py", line 149, in main
    self.run_test()
    ~~~~~~~~~~~~~^^
  File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 155, in run_test
    self.check_trickled_request_timeout()
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^
  File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 495, in check_trickled_request_timeout
    response = waiting_conn.recv_raw()
  File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 91, in recv_raw
    return self.conn.sock.recv(1024)
           ~~~~~~~~~~~~~~~~~~~^^^^^^
TimeoutError: timed out
2026-11-17T00:23:26.153951Z TestFramework (INFO): Not stopping nodes as test failed. The dangling processes will be cleaned up later.
2026-11-17T00:23:26.154074Z TestFramework (WARNING): Not cleaning up dir /tmp/bitcoin_func_test_s9etyj6d
2026-11-17T00:23:26.154171Z TestFramework (ERROR): Test failed. Test logging available at /tmp/bitcoin_func_test_s9etyj6d/test_framework.log
...
debug.log excerpt
...
2026-11-17T04:15:04.537793Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=240 buffered=1
2026-11-17T04:15:04.786570Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=241 buffered=2
2026-11-17T04:15:05.035110Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=242 buffered=3
2026-11-17T04:15:05.283603Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=243 buffered=4
2026-11-17T04:15:05.532013Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=244 buffered=5
2026-11-17T04:15:05.781073Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=245 buffered=6
2026-11-17T04:15:06.029565Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=246 buffered=7
2026-11-17T04:15:06.278318Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=247 buffered=8
2026-11-17T04:15:06.504703Z [http] [httpserver.cpp:957] [Receive] [http] Received EOF from 127.0.0.1:62906 (id=5)
2026-11-17T04:15:06.504776Z [http] [httpserver.cpp:1197] [operator()] [http] Disconnecting HTTP client 127.0.0.1:62906 (id=5)
2026-11-17T04:15:06.504887Z [http] [httpserver.cpp:884] [NewSockAccepted] [http] HTTP Connection accepted from 127.0.0.1:62905 (id=6)
2026-11-17T04:15:06.504943Z [http] [httpserver.cpp:977] [Receive] [http] Received 189 bytes from 127.0.0.1:62905 (id=6): total=189 buffered=189
2026-11-17T04:15:06.505030Z [http] [httpserver.cpp:1174] [TryReadRequestInternal] [http] Received a POST request for / from 127.0.0.1:62905 (id=6)
2026-11-17T04:15:06.505124Z [http] [httpserver.cpp:957] [Receive] [http] Received EOF from 127.0.0.1:62905 (id=6)
2026-11-17T04:15:06.505192Z [http] [httpserver.cpp:1197] [operator()] [http] Disconnecting HTTP client 127.0.0.1:62905 (id=6)
  • node's full debug.log here -- the tail has the lines of interest
on NetBSD 11.0, `check_trickled_request_timeout()` fails. `waiting_conn.recv_raw()` raises `TimeoutError` because the client-side timeout (`RPCSERVERTIMEOUT + 2`) expires before a response shows up on NetBSD, increasing the client-side timeout to any value >= `RPCSERVERTIMEOUT * 3` makes the test pass. `RPCSERVERTIMEOUT * 2` is still not enough. the test also passes if i remove the client-side timeout altogether. Linux passes without any of these changes, using the original `RPCSERVERTIMEOUT + 2` what i cannot tell yet is _why_ it breaks. in the failing run's `debug.log`, i never see `HTTP client took too long to send a complete request` --- **some logs**: <details> <summary>test output log </summary> ```text ... 2026-11-17T00:23:21.273664Z TestFramework (INFO): Client did not finish sending request before connection was terminated 2026-11-17T00:23:21.279598Z TestFramework (INFO): Check -rpcservertimeout 2026-11-17T00:23:23.747429Z TestFramework (INFO): Check that -rpcservertimeout disconnects clients that never finish a request 2026-11-17T00:23:26.149963Z TestFramework (ERROR): Unexpected exception: Traceback (most recent call last): File "/home/user404/bitcoin/test/functional/test_framework/test_framework.py", line 149, in main self.run_test() ~~~~~~~~~~~~~^^ File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 155, in run_test self.check_trickled_request_timeout() ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^ File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 495, in check_trickled_request_timeout response = waiting_conn.recv_raw() File "/home/user404/bitcoin/build/test/functional/interface_http.py", line 91, in recv_raw return self.conn.sock.recv(1024) ~~~~~~~~~~~~~~~~~~~^^^^^^ TimeoutError: timed out 2026-11-17T00:23:26.153951Z TestFramework (INFO): Not stopping nodes as test failed. The dangling processes will be cleaned up later. 2026-11-17T00:23:26.154074Z TestFramework (WARNING): Not cleaning up dir /tmp/bitcoin_func_test_s9etyj6d 2026-11-17T00:23:26.154171Z TestFramework (ERROR): Test failed. Test logging available at /tmp/bitcoin_func_test_s9etyj6d/test_framework.log ... ``` </details> <details> <summary><code>debug.log</code> excerpt </summary> ```text ... 2026-11-17T04:15:04.537793Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=240 buffered=1 2026-11-17T04:15:04.786570Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=241 buffered=2 2026-11-17T04:15:05.035110Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=242 buffered=3 2026-11-17T04:15:05.283603Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=243 buffered=4 2026-11-17T04:15:05.532013Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=244 buffered=5 2026-11-17T04:15:05.781073Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=245 buffered=6 2026-11-17T04:15:06.029565Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=246 buffered=7 2026-11-17T04:15:06.278318Z [http] [httpserver.cpp:977] [Receive] [http] Received 1 bytes from 127.0.0.1:62906 (id=5): total=247 buffered=8 2026-11-17T04:15:06.504703Z [http] [httpserver.cpp:957] [Receive] [http] Received EOF from 127.0.0.1:62906 (id=5) 2026-11-17T04:15:06.504776Z [http] [httpserver.cpp:1197] [operator()] [http] Disconnecting HTTP client 127.0.0.1:62906 (id=5) 2026-11-17T04:15:06.504887Z [http] [httpserver.cpp:884] [NewSockAccepted] [http] HTTP Connection accepted from 127.0.0.1:62905 (id=6) 2026-11-17T04:15:06.504943Z [http] [httpserver.cpp:977] [Receive] [http] Received 189 bytes from 127.0.0.1:62905 (id=6): total=189 buffered=189 2026-11-17T04:15:06.505030Z [http] [httpserver.cpp:1174] [TryReadRequestInternal] [http] Received a POST request for / from 127.0.0.1:62905 (id=6) 2026-11-17T04:15:06.505124Z [http] [httpserver.cpp:957] [Receive] [http] Received EOF from 127.0.0.1:62905 (id=6) 2026-11-17T04:15:06.505192Z [http] [httpserver.cpp:1197] [operator()] [http] Disconnecting HTTP client 127.0.0.1:62905 (id=6) ``` </details> - node's full `debug.log` [here](https://termbin.com/yxqro) -- the tail has the lines of interest
Sign in to join this conversation.
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!36204
No description provided.