Commit e4710a89e8 for golang

commit e4710a89e8870f87c0606a69cc2c0fd44df52abd
Author: Damien Neil <dneil@google.com>
Date:   Tue Nov 24 15:40:12 2026 -0800

    net/http: add GODEBUG=httptransportcancelrequest=1

    Restore support for Transport.CancelRequest, guarded by a GODEBUG.

    Fixes #79040

    Change-Id: Ie400b63740d5e0688f6ae155db73b3106a6a6964
    Reviewed-on: https://go-review.googlesource.com/c/go/+/868302
    Auto-Submit: Damien Neil <dneil@google.com>
    Reviewed-by: Nicholas Husin <nsh@golang.org>
    Reviewed-by: Nicholas Husin <husin@google.com>
    LUCI-TryBot-Result: golang-scoped@luci-project-accounts.iam.gserviceaccount.com <golang-scoped@luci-project-accounts.iam.gserviceaccount.com>

diff --git a/doc/godebug.md b/doc/godebug.md
index 8e7b2b3ff6..169b29ea54 100644
--- a/doc/godebug.md
+++ b/doc/godebug.md
@@ -156,6 +156,11 @@ and the [go command documentation](/cmd/go#hdr-Build_and_test_caching).

 ### Go 1.28

+Go 1.28 changed the long-deprecated
+[`net/http.Transport.CancelRequest`](/pkg/net/http#Transport.CancelRequest) method
+to do nothing. The `httptransportcancelrequest=1` setting restores its previous behavior.
+We plan to remove this setting in Go 1.32.
+
 Go 1.28 added a new `tlsechgrease` setting that controls whether crypto/tls
 sends a GREASE'd `encrypted_client_hello` extension on outer ClientHellos when
 no real ECH configuration is available (RFC 9849, Section 6.2). The default
diff --git a/src/internal/godebugs/table.go b/src/internal/godebugs/table.go
index 5815755c32..4ca084b67b 100644
--- a/src/internal/godebugs/table.go
+++ b/src/internal/godebugs/table.go
@@ -48,6 +48,7 @@ var All = []Info{
 	{Name: "httpmuxgo121", Package: "net/http", Changed: 22, Old: "1"},
 	{Name: "httpservecontentkeepheaders", Package: "net/http", Changed: 23, Old: "1"},
 	{Name: "httpservecontentmaxranges", Package: "net/http", Changed: 26, Old: "1"},
+	{Name: "httptransportcancelrequest", Package: "net/http", Changed: 28, Old: "1"},
 	{Name: "installgoroot", Package: "go/build"},
 	{Name: "jstmpllitinterp", Package: "html/template", Opaque: true}, // bug #66217: remove Opaque
 	//{Name: "multipartfiles", Package: "mime/multipart"},
diff --git a/src/net/http/client_test.go b/src/net/http/client_test.go
index fcbc624202..24cd3a20e8 100644
--- a/src/net/http/client_test.go
+++ b/src/net/http/client_test.go
@@ -1335,7 +1335,13 @@ func testClientTimeout_Headers(t *testing.T, mode testMode) {

 // Issue 16094: if Client.Timeout is set but not hit, a Timeout error shouldn't be
 // returned.
-func TestClientTimeoutCancel(t *testing.T) { runCancelTest(t, testClientTimeoutCancel) }
+func TestClientTimeoutCancel(t *testing.T) {
+	// This test has never worked with Transport.CancelRequest,
+	// because when Client.Timeout is set the Client makes a copy of the *Request
+	// to apply the timeout. CancelRequest on the original *Request won't find the
+	// request that was actually sent.
+	runCancelTest(t, testClientTimeoutCancel, optNoTransportCancel)
+}
 func testClientTimeoutCancel(t *testing.T, test cancelTest) {
 	testDone := make(chan struct{})

diff --git a/src/net/http/clientconn.go b/src/net/http/clientconn.go
index 13507965d2..e9dd642beb 100644
--- a/src/net/http/clientconn.go
+++ b/src/net/http/clientconn.go
@@ -408,19 +408,23 @@ func (cc *ClientConn) SetStateHook(f func(*ClientConn)) {
 // because they predate persistConn implementing genericClientConn.

 func (pc *persistConn) RoundTrip(req *Request) (*Response, error) {
-	ctx := req.Context()
-	trace := httptrace.ContextClientTrace(ctx)
-
 	// Convert Request.Cancel into context cancellation.
 	ctx, cancel := context.WithCancelCause(req.Context())
 	if req.Cancel != nil {
 		go awaitLegacyCancel(ctx, cancel, req)
 	}
+	resp, err := pc.roundTripWithCancel(ctx, cancel, req)
+	if err != nil {
+		cancel(err)
+	}
+	return resp, err
+}

+func (pc *persistConn) roundTripWithCancel(ctx context.Context, cancel context.CancelCauseFunc, req *Request) (*Response, error) {
+	trace := httptrace.ContextClientTrace(ctx)
 	treq := &transportRequest{Request: req, trace: trace, ctx: ctx, cancel: cancel}
 	resp, err := pc.roundTrip(treq)
 	if err != nil {
-		cancel(err)
 		return nil, err
 	}
 	resp.Request = req
diff --git a/src/net/http/transport.go b/src/net/http/transport.go
index 1fa9b70101..ed58509292 100644
--- a/src/net/http/transport.go
+++ b/src/net/http/transport.go
@@ -98,6 +98,9 @@ const DefaultMaxIdleConnsPerHost = 2
 type Transport struct {
 	pool clientConnPool

+	reqMu       sync.Mutex
+	reqCanceler map[*Request]context.CancelCauseFunc
+
 	altMu    sync.Mutex   // guards changing altProto only
 	altProto atomic.Value // of nil or map[string]RoundTripper, key is URI scheme

@@ -632,11 +635,6 @@ func (t *Transport) roundTrip(req *Request) (_ *Response, err error) {
 		return nil, errors.New("http: no Host in request URL")
 	}

-	// Transport request context.
-	//
-	// RoundTrip cancels this context before returning.
-	// On the HTTP/1 path, persistConn.RoundTrip creates its own context
-	// that persistConn.readLoop cancels after reading the response body.
 	ctx, cancel := context.WithCancelCause(req.Context())

 	// Convert Request.Cancel into context cancellation.
@@ -644,7 +642,16 @@ func (t *Transport) roundTrip(req *Request) (_ *Response, err error) {
 		go awaitLegacyCancel(ctx, cancel, origReq)
 	}

+	// Convert Transport.CancelRequest into context cancellation,
+	// but only when GODEBUG=httptransportcancelrequest=1.
+	if httptransportcancelrequest.Value() == "1" {
+		cancel = t.prepareTransportCancel(origReq, cancel)
+	}
+
 	defer func() {
+		if cancel == nil {
+			return
+		}
 		if err != nil {
 			cancel(err)
 		} else {
@@ -676,7 +683,16 @@ func (t *Transport) roundTrip(req *Request) (_ *Response, err error) {
 			return nil, err
 		}

-		resp, err := pconn.cc.RoundTrip(req)
+		var resp *Response
+		if pc, ok := pconn.cc.(*persistConn); ok {
+			resp, err = pc.roundTripWithCancel(ctx, cancel, req)
+			if err == nil {
+				// persistConn will call cancel.
+				cancel = nil
+			}
+		} else {
+			resp, err = pconn.cc.RoundTrip(req)
+		}
 		if err == nil {
 			resp.Request = origReq
 			return resp, nil
@@ -956,11 +972,49 @@ func (t *Transport) CloseIdleConnections() {
 	}
 }

+// GODEBUG=httptransportcancelrequest=1 restores Transport.CancelRequest (for now).
+var httptransportcancelrequest = godebug.New("httptransportcancelrequest")
+
+// prepareTransportCancel sets up state to convert Transport.CancelRequest into context cancellation.
+func (t *Transport) prepareTransportCancel(req *Request, origCancel context.CancelCauseFunc) context.CancelCauseFunc {
+	cancel := func(err error) {
+		origCancel(err)
+		t.reqMu.Lock()
+		delete(t.reqCanceler, req)
+		t.reqMu.Unlock()
+	}
+	t.reqMu.Lock()
+	if t.reqCanceler == nil {
+		t.reqCanceler = make(map[*Request]context.CancelCauseFunc)
+	}
+	t.reqCanceler[req] = cancel
+	t.reqMu.Unlock()
+	return cancel
+}
+
+var cancelRequestOnce sync.Once
+
 // CancelRequest is obsolete and does nothing.
 //
+// CancelRequest was changed to do nothing in Go 1.28.
+// GODEBUG=httptransportcancelrequest=1 temporarily reenables the pre-Go 1.28 behavior
+// of CancelRequest. This GODEBUG will be removed in a later version of Go.
+//
 // Deprecated: Use [NewRequestWithContext] to create a request with a
 // cancelable context instead.
 func (t *Transport) CancelRequest(req *Request) {
+	if httptransportcancelrequest.Value() != "1" {
+		log.Println("net/http: Use of unsupported Transport.CancelRequest. Use NewRequestWithContext instead.")
+		return
+	}
+	t.reqMu.Lock()
+	cancel := t.reqCanceler[req]
+	delete(t.reqCanceler, req)
+	t.reqMu.Unlock()
+	if cancel != nil {
+		httptransportcancelrequest.IncNonDefault()
+		cancel(errRequestCanceled)
+	}
 }

 //
diff --git a/src/net/http/transport_test.go b/src/net/http/transport_test.go
index 4d7b17fcaa..f135025cc2 100644
--- a/src/net/http/transport_test.go
+++ b/src/net/http/transport_test.go
@@ -2582,6 +2582,25 @@ type cancelTest struct {
 	checkErr func(when string, err error)      // verify the expected error
 }

+// runCancelTestTransport uses Transport.CancelRequest.
+func runCancelTestTransport(t *testing.T, mode testMode, f func(t *testing.T, test cancelTest)) {
+	t.Setenv("GODEBUG", "httptransportcancelrequest=1")
+	f(t, cancelTest{
+		mode: mode,
+		newReq: func(req *Request) *Request {
+			return req
+		},
+		cancel: func(tr *Transport, req *Request) {
+			tr.CancelRequest(req)
+		},
+		checkErr: func(when string, err error) {
+			if !errors.Is(err, ExportErrRequestCanceled) && !errors.Is(err, ExportErrRequestCanceledConn) {
+				t.Errorf("%v error = %v, want errRequestCanceled or errRequestCanceledConn", when, err)
+			}
+		},
+	})
+}
+
 // runCancelTestChannel uses Request.Cancel.
 func runCancelTestChannel(t *testing.T, mode testMode, f func(t *testing.T, test cancelTest)) {
 	cancelc := make(chan struct{})
@@ -2622,8 +2641,25 @@ func runCancelTestContext(t *testing.T, mode testMode, f func(t *testing.T, test
 	})
 }

+var optNoTransportCancel = "optNoTransportCancel"
+
 func runCancelTest(t *testing.T, f func(t *testing.T, test cancelTest), opts ...any) {
+	noTransportCancel := false
+	opts = slices.DeleteFunc(opts, func(v any) bool {
+		if v == optNoTransportCancel {
+			noTransportCancel = true
+			return true
+		}
+		return false
+	})
+
+	opts = append([]any{testNotParallel}, opts...)
 	runNoSynctest(t, func(t *testing.T, mode testMode) {
+		if mode == http1Mode && !noTransportCancel {
+			synctest.Subtest(t, "TransportCancel", func(t *testing.T) {
+				runCancelTestTransport(t, mode, f)
+			})
+		}
 		synctest.Subtest(t, "RequestCancel", func(t *testing.T) {
 			if mode == http3Mode {
 				t.Skip("Request.Cancel not supported for HTTP/3")
@@ -2649,6 +2685,41 @@ func testTransportCancelRequest(t *testing.T, test cancelTest) {
 	}))
 	defer close(unblockc)

+	req, _ := NewRequest("GET", cst.ts.URL, nil)
+	req = test.newReq(req)
+	res, err := cst.tr.RoundTrip(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	body := make([]byte, len(msg))
+	n, _ := io.ReadFull(res.Body, body)
+	if n != len(body) || !bytes.Equal(body, []byte(msg)) {
+		t.Errorf("Body = %q; want %q", body[:n], msg)
+	}
+	synctest.Wait()
+	test.cancel(cst.tr, req)
+
+	tail, err := io.ReadAll(res.Body)
+	res.Body.Close()
+	test.checkErr("Body.Read", err)
+	if len(tail) > 0 {
+		t.Errorf("Spurious bytes from Body.Read: %q", tail)
+	}
+}
+
+func TestClientConnCancelRequest(t *testing.T) {
+	runCancelTest(t, testClientConnCancelRequest, optNoTransportCancel)
+}
+func testClientConnCancelRequest(t *testing.T, test cancelTest) {
+	const msg = "Hello"
+	unblockc := make(chan bool)
+	cst := newClientServerTest(t, test.mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+		io.WriteString(w, msg)
+		w.(Flusher).Flush() // send headers and some body
+		<-unblockc
+	}))
+	defer close(unblockc)
+
 	conn, err := cst.tr.NewClientConn(t.Context(), test.mode.Scheme(), "example.tld:80")
 	if err != nil {
 		t.Fatal(err)
@@ -2788,6 +2859,42 @@ func testTransportCancelRequestWithBody(t *testing.T, test cancelTest) {
 	}))
 	defer close(unblockc)

+	req, _ := NewRequest("POST", cst.ts.URL, strings.NewReader("withbody"))
+	req = test.newReq(req)
+
+	res, err := cst.tr.RoundTrip(req)
+	if err != nil {
+		t.Fatal(err)
+	}
+	body := make([]byte, len(msg))
+	n, _ := io.ReadFull(res.Body, body)
+	if n != len(body) || !bytes.Equal(body, []byte(msg)) {
+		t.Errorf("Body = %q; want %q", body[:n], msg)
+	}
+	synctest.Wait()
+	test.cancel(cst.tr, req)
+
+	tail, err := io.ReadAll(res.Body)
+	res.Body.Close()
+	test.checkErr("Body.Read", err)
+	if len(tail) > 0 {
+		t.Errorf("Spurious bytes from Body.Read: %q", tail)
+	}
+}
+
+func TestClientConnCancelRequestWithBody(t *testing.T) {
+	runCancelTest(t, testClientConnCancelRequestWithBody, optNoTransportCancel)
+}
+func testClientConnCancelRequestWithBody(t *testing.T, test cancelTest) {
+	const msg = "Hello"
+	unblockc := make(chan struct{})
+	cst := newClientServerTest(t, test.mode, HandlerFunc(func(w ResponseWriter, r *Request) {
+		io.WriteString(w, msg)
+		w.(Flusher).Flush() // send headers and some body
+		<-unblockc
+	}))
+	defer close(unblockc)
+
 	conn, err := cst.tr.NewClientConn(t.Context(), test.mode.Scheme(), "example.tld:80")
 	if err != nil {
 		t.Fatal(err)
@@ -2826,7 +2933,8 @@ func testTransportCancelRequestWithBody(t *testing.T, test cancelTest) {
 }

 func TestTransportCancelRequestBeforeDo(t *testing.T) {
-	runCancelTest(t, testTransportCancelRequestBeforeDo)
+	// Transport.CancelRequest does not support canceling a request before RoundTrip is called.
+	runCancelTest(t, testTransportCancelRequestBeforeDo, optNoTransportCancel)
 }
 func testTransportCancelRequestBeforeDo(t *testing.T, test cancelTest) {
 	unblockc := make(chan bool)
diff --git a/src/runtime/metrics/doc.go b/src/runtime/metrics/doc.go
index 8a49725dfd..524355dcb7 100644
--- a/src/runtime/metrics/doc.go
+++ b/src/runtime/metrics/doc.go
@@ -339,6 +339,11 @@ Below is the full list of supported metrics, ordered lexicographically.
 		by the net/http package due to a non-default
 		GODEBUG=httpservecontentmaxranges=... setting.

+	/godebug/non-default-behavior/httptransportcancelrequest:events
+		The number of non-default behaviors executed
+		by the net/http package due to a non-default
+		GODEBUG=httptransportcancelrequest=... setting.
+
 	/godebug/non-default-behavior/installgoroot:events
 		The number of non-default behaviors executed by the go/build
 		package due to a non-default GODEBUG=installgoroot=... setting.