Skip to content

http: update m_keep_alive under m_send_mutex - #36259

Open
azuchi wants to merge 1 commit into
bitcoin:masterfrom
azuchi:http-keepalive-under-send-mutex
Open

azuchi wants to merge 1 commit into
bitcoin:masterfrom
azuchi:http-keepalive-under-send-mutex

Conversation

@azuchi

@azuchi azuchi commented Sep 15, 2026

Copy link
Copy Markdown
Contributor

HTTPRemoteClient::Send() sets m_keep_alive before taking m_send_mutex and appending the response to the send buffer, while the I/O thread reads it under m_send_mutex in MaybeSendBytesFromBuffer() right after the buffer drains to empty. The two updates are therefore not ordered with respect to each other, and a pipelining client can lose a response:

  1. Response 1 (keep-alive) is partially sent and the I/O thread is still draining it.
  2. Request 2 (Connection: close) is parsed from the receive buffer and dispatched to a worker (the send throttle from http: throttle send buffer when client stops draining #36174 only holds a request back once the buffer exceeds MAX_BODY_SIZE).
  3. The worker clears m_keep_alive; the I/O thread then finishes sending response 1, sees an empty buffer with m_keep_alive == false, and sets m_disconnect.
  4. The worker appends response 2, which is dropped when the client is disconnected on the next loop iteration.

This PR moves the assignment into the critical section that appends the response, and turns the field from std::atomic_bool into a plain bool GUARDED_BY(m_send_mutex) so Clang's thread-safety analysis enforces the ordering (the only reader already holds the mutex). With the flag and the buffer updated together, the I/O thread can no longer observe "empty && !keep_alive" between two pipelined responses.

The ordering dates back to the initial HTTP server implementation (#35182); #35829/#36007 only moved the code. The window is small and bitcoin-cli does not pipeline, so this is a low-severity fix.

Test

http_pipelined_keepalive_close_tests reproduces the interleaving deterministically with a mock socket: Send() fails with EAGAIN until the second request has been dispatched, then the I/O thread's next Send() (made while holding m_send_mutex) signals the worker to write its reply, waits for it to reach HTTPRemoteClient::Send(), and only then flushes the first reply. Sends are refused again until the test releases them, so the second reply is only delivered if the I/O loop kept the connection open. Without the first commit the test fails with server.GetConnectionsCount() == 1 has failed [0 != 1]: the client was disconnected with the second reply still in its send buffer.

@DrahtBot

DrahtBot commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

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
Concept ACK winterrdog, pinheadmz

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.

@winterrdog winterrdog left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

concept ACK

makes sense to update m_keep_alive in the same critical section as the send
buffer, since both are read together under the same lock (m_send_mutex). this
keeps the related state changes in sync and does not allow the I/O thread to
view an inconsistent state while the next response is being queued


edit: the motivation is fine but since this scenario is not easy to reach pragmatically,
i'd rather delay review

@pinheadmz

Copy link
Copy Markdown
Member

concept ACK
seems reasonable, but low priority for review

@hodlinator hodlinator left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Concept ACK dc8fb12

Seems more correct than on master, thanks for finding this!

Verified that the test fails when the implementation changes are reverted.

Comment thread src/test/httpserver_tests.cpp Outdated
Comment on lines +1087 to +1089
// The state is shared between the test, the request handler and the mock
// socket. It is static because the local class below cannot capture
// automatic variables.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: More to the point?

Suggested change
// The state is shared between the test, the request handler and the mock
// socket. It is static because the local class below cannot capture
// automatic variables.
// The state is shared between the test, the request handler and the mock
// socket. It is static since SocketTestingSetup::ConnectClient<T>() doesn't
// allow for additional socket ctor args.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Taken as suggested, thanks. Your wording is more accurate: the real constraint is ConnectClient<T>(), not the local class.

Comment thread src/test/httpserver_tests.cpp Outdated
Comment on lines +1090 to +1092
static std::atomic_bool second_request_dispatched{false};
static std::atomic_bool io_thread_in_send{false};
static std::atomic_bool allow_second_reply{false};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Could skip explicit initialization since std::atomic-ctor implicitly initializes to T()1/false2 and we overwrite the values immediately below anyway.

Suggested change
static std::atomic_bool second_request_dispatched{false};
static std::atomic_bool io_thread_in_send{false};
static std::atomic_bool allow_second_reply{false};
static std::atomic_bool second_request_dispatched;
static std::atomic_bool io_thread_in_send;
static std::atomic_bool allow_second_reply;

Footnotes

  1. https://en.cppreference.com/cpp/atomic/atomic/atomic ↩

  2. https://stackoverflow.com/questions/3308028/default-constructor-value-for-bool-type ↩

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.

Comment thread src/test/httpserver_tests.cpp Outdated
Comment on lines +1164 to +1165
char buf[0x10000] = {};
auto WaitForReply = [&](const std::string& reply) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: Might as well decrease scope of buf and skip initialization:

Suggested change
char buf[0x10000] = {};
auto WaitForReply = [&](const std::string& reply) {
auto WaitForReply = [&](const std::string& reply) {
char buf[0x10000];

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done, thanks.

HTTPRemoteClient::Send() wrote m_keep_alive before taking m_send_mutex
and appending the response to m_send_buffer. The I/O thread decides in
MaybeSendBytesFromBuffer() (under m_send_mutex) whether to disconnect
by checking "buffer drained to empty && !m_keep_alive". Because the flag
and the buffer were not updated together, a pipelined client could lose
a response:

 1. Response 1 (keep-alive) is partially sent; the I/O thread is still
    draining it.
 2. Request 2 ("Connection: close") is parsed from the receive buffer
    and dispatched to a worker (the send throttle only holds requests
    back once the buffer exceeds MAX_BODY_SIZE).
 3. The worker clears m_keep_alive, then the I/O thread finishes
    sending response 1, observes an empty buffer with
    m_keep_alive == false and sets m_disconnect.
 4. The worker appends response 2, which is dropped when the client is
    disconnected on the next I/O loop iteration.

Move the assignment into the same critical section that appends the
response, and change the field from std::atomic_bool to a plain bool
annotated GUARDED_BY(m_send_mutex) so that Clang's thread-safety
analysis enforces the ordering. The only reader already holds
m_send_mutex.

Add a unit test that reproduces the interleaving deterministically with a
mock socket: it holds the first reply in the send buffer until the second
(pipelined, "Connection: close") request has been dispatched, then lets
the I/O thread flush it while the worker is about to write the second
reply. Without the fix the client is disconnected with the second reply
still in the buffer.
@azuchi
azuchi force-pushed the http-keepalive-under-send-mutex branch from dc8fb12 to b71c028 Compare November 5, 2026 02:02
@azuchi

azuchi commented Nov 5, 2026

Copy link
Copy Markdown
Contributor Author

Pushed b71c028: addresses all three nits from @hodlinator (comment wording, dropped redundant {false} initializers, moved buf into the lambda). Test-only changes, no change to the fix itself.

Thanks for verifying that the test fails with the implementation changes reverted.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants