Skip to content

Body dropped too late when an h1 handshake hits an error #4122

Description

@alexcrichton

Version

hyper 1.10.1

Platform

Linux x86_64 7.0.0-27-generic

Summary

Wasmtime hit a spurious failure in a test recently in CI that I think I've diagnosed to some code in hyper. The test in question is a wasm guest that issues an HTTP/1.1 request to a server that only works with HTTP/2, and the expectation is that the wasm guest gets a HttpProtocolError within wasm. This test ended up timing out in CI and getting a timeout failure instead.

After some investigation it looks like this is due hyper's use of tokio's channels and the precise synchronization/sequencing of sending a request from one channel to another. The code in question attached here is a small program which showcases this race where the intention of the test is:

  • No actual I/O is performed, it's just in-memory data structures.
  • An http1 handshake is done against a connection that reads corrupt data (sort of mimicking what an http2 server might initiate with)
  • The code in question sends a request, completes the connection I/O, and then asserts that the request was dropped.
  • There's various bits and pieces of the program intended to stress scheduling to make the bug appear more often.

Code Sample

use bytes::Bytes;
use http_body::Body;
use hyper::rt::{Read, ReadBufCursor, Write};
use std::future::Future;
use std::io;
use std::pin::Pin;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Barrier};
use std::task::{Context, Poll, Waker};

fn main() {
    // start up some background work to stress scheduling a bit more.
    for _ in 0..16 {
        std::thread::spawn(|| loop {
            std::hint::black_box(std::time::Instant::now());
        });
    }

    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap();
    let _guard = rt.enter();

    for _ in 0..2_000_000 {
        // Handshake against the mock IO. handshake() itself does no I/O.
        let (mut sender, mut conn) = match rt
            .block_on(hyper::client::conn::http1::handshake::<_, TrackedBody>(
                MockIo::default(),
            )) {
            Ok(p) => p,
            Err(_) => continue,
        };

        let dropped = Arc::new(AtomicBool::new(false));
        let req = hyper::Request::connect("http://x/")
            .body(TrackedBody {
                dropped: dropped.clone(),
            })
            .unwrap();

        let barrier = Arc::new(Barrier::new(2));

        // Thread B: dispatch the request the instant the barrier releases.
        let b2 = barrier.clone();
        let sender_thread = std::thread::spawn(move || {
            b2.wait();
            let fut = sender.send_request(req);
            (fut, sender)
        });

        barrier.wait();
        let waker = Waker::noop();
        let mut cx = Context::from_waker(&waker);
        for _ in 0..4 {
            if Pin::new(&mut conn).poll(&mut cx).is_ready() {
                break;
            }
        }
        drop(conn);

        let (fut, sender2) = sender_thread.join().unwrap();
        drop(fut);

        // At this point the future from `send_request` is gone, the receiver
        // through `conn` is gone, so it should be the case that our body in the
        // request that was sent was dropped. However this isn't always true so
        // sometimes this will print out.
        if !dropped.load(Ordering::SeqCst) {
            println!("body wasn't dropped");
        }
        drop(sender2);
        assert!(
            dropped.load(Ordering::SeqCst),
            "request must be reclaimed once the SendRequest drops"
        );
    }
}

#[derive(Default)]
struct MockIo {
    gave: bool,
}

impl Read for MockIo {
    fn poll_read(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        mut buf: ReadBufCursor<'_>,
    ) -> Poll<io::Result<()>> {
        // read enough bytes that the connection should terminate with an error.
        if !self.gave {
            self.gave = true;
            buf.put_slice(&[0u8; 9]);
        }
        Poll::Ready(Ok(()))
    }
}

impl Write for MockIo {
    fn poll_write(
        self: Pin<&mut Self>,
        _: &mut Context<'_>,
        _buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        // shouldn't be called for h1
        unreachable!()
    }
    fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }
    fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<io::Result<()>> {
        Poll::Ready(Ok(()))
    }
}

/// An empty body that sets `dropped` to true when dropped.
struct TrackedBody {
    dropped: Arc<AtomicBool>,
}

impl Body for TrackedBody {
    type Data = Bytes;
    type Error = std::convert::Infallible;
    fn poll_frame(
        self: Pin<&mut Self>,
        _: &mut Context<'_>,
    ) -> Poll<Option<Result<http_body::Frame<Bytes>, Self::Error>>> {
        Poll::Ready(None)
    }
}

impl Drop for TrackedBody {
    fn drop(&mut self) {
        self.dropped.store(true, Ordering::SeqCst);
    }
}

Expected Behavior

My expectation of this program is that the body of the request is always dropped by the time that the only live value is the sender itself. Effectively this should never print body wasn't dropped.

Actual Behavior

Locally ~2m iterations show ~20 instances of the body not being dropped before the sender is fully dropped. This is how in Wasmtime's embedding it ended up showing as a timeout because we rely on the body being dropped to register when the request is sent and such (or an error occurred).

Additional Context

Some poking and prodding around things shows that one possible culprit here is this line which is a bit more robust using Tokio's try_recv (my guess is that try_recv was added after this was authored). Even with that, however, the program above still doesn't drop the body 100% of the time, and this seems due to the fact that even if close has been called on a channel it's possible for try_recv to return Empty (as opposed to Disconnected) if there's an outstanding permit of a message being sent. I think this is basically still a race between the sender/receiver where try_recv isn't enough, hyper would have to loop over try_recv.

Overall this is where I figured it'd be best to file an issue. I'd want to confirm the expectation that this program should reliably drop the body, and then also see what others' thoughts are on this.

Activity

  1. added
    C-bugCategory: bug. Something is wrong. This is bad!
    on Jul 2, 2026
  2. seanmonstar commented on Jul 3, 2026

    @seanmonstar
    Member

    Interesting! Yea, the now or never thing is probably from a long time ago, and probably could be improved.

    Though, I'm curious about the test case that this is failing. Retrieval of the queued request is on a best-effort basis. It's possible it doesn't happen. And there's no external guarantee of drop order. So, I'm a little suspicious of a test that is depending on that. The body should drop eventually. (Though, I wonder if it's doing anything more, which is preventing the connection from dropping.)

    That said, it's always better internally to recover the request than to drop it, as it can allow trying to send it again on a better connection. So I'd like to improve that, just as a secondary thing I think.

  3. alexcrichton commented on Jul 6, 2026

    @alexcrichton
    ContributorAuthor

    FWIW the use case within Wasmtime doesn't depend on precise ordering of anything, but rather it'd be desirable to have the property than when the only live object is the sender that all other in-flight requests are either dropped or recovered somewhere. Right now I believe there's the possibility of an in-flight request being stuck in the sender with nowhere to go but being dropped when the sender is dropped itself.

    Another possible fix for us, which we're not doing yet, is to route the error from the conn part of the handshake back into the other side somehow. Right now that's just logged and we're relying on drop behavior, but if you're saying you'd rather not guarantee the drop behavior then routing that error somewhere is what we could do instead.

  4. fzlzjerry commented on Aug 10, 2026

    @fzlzjerry
    Contributor

    I reproduced this on current master. The race is between
    UnboundedSender::send reserving channel capacity and publishing the envelope:
    receiver shutdown can observe an empty channel and finish in that window,
    leaving the request owned by the remaining sender.

    I have a narrowly scoped HTTP/1 fix that serializes envelope publication with
    receiver shutdown, together with a regression test that exercises the
    close/send race. The 500,000-iteration stress harness went from 23 missed drops
    on master to 0 with the patch. I'm finishing the last checks and will open it as
    a draft shortly.

  5. added
    C-bugCategory: bug. Something is wrong. This is bad!
    and removed
    C-bugCategory: bug. Something is wrong. This is bad!
    on Aug 21, 2026
  6. added 2 commits that reference this issue on Aug 21, 2026
    42dfc55
    333d33a
  7. added 2 commits that reference this issue on Aug 30, 2026
    1f3b285
    6663880
  8. webdevsamran commented on Sep 6, 2026

    @webdevsamran
  9. fzlzjerry commented on Sep 7, 2026

    @fzlzjerry
    Contributor

    For coordination, there is already an open PR for this issue: #4150. The current revision drains the existing receive future during shutdown rather than adding an Arc<Mutex>, and it is waiting for maintainer re-review.

    Please take a look there before starting a separate implementation so we can avoid duplicating the work. An additional handshake-error reproducer would also be useful to compare against the existing regression test.

  10. added
    C-bugCategory: bug. Something is wrong. This is bad!
    and removed
    C-bugCategory: bug. Something is wrong. This is bad!
    on Oct 9, 2026
  11. seanmonstar commented on Oct 9, 2026

    @seanmonstar
    Member

    This should be fixed by #4222.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: bug. Something is wrong. This is bad!

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions