CodeSampleX

Ejemplo

net/http v1.26.5: http.Transport.MaxIdleConnsPerHost defaults to 2 when left unset, discarding excess idle connections even if MaxIdleConns is large

Muestra verificada para golang net/http v1.26.5: http.Transport.MaxIdleConnsPerHost defaults to 2 when left unset, discarding excess idle connections even if…

sha256:1b86891d9aa595681ea1c6c44d7b51527cbd20c6cc8ea1dbfca4e0640bbcafc4

Esta red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
2
Claves de firma que lo compilaron
2
Entorno declarado go linux x64 go go go

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
go 1.26 · linux alpine/x64 · docker ed25519:d91480838ac982c9 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-16
go 1.26 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · golang@1
2026-08-18

Caso

HOW
Objetivo
http.Transport.MaxIdleConnsPerHost defaults to 2 when left unset, discarding excess idle connections even if MaxIdleConns is large
Paquetes
Símbolos
  • http.Transport.MaxIdleConnsPerHost
  • http.DefaultMaxIdleConnsPerHost
  • http.Transport.MaxIdleConns
  • http.Transport
Entorno
go
Creado
2026-08-16T14:52:04Z

Contrato

  1. Leaving http.Transport.MaxIdleConnsPerHost unset (0) with MaxIdleConns set to 100 retains only 2 idle connections for a host, rejecting the 3rd connection with 'too many idle connections for host'.
  2. Explicitly setting http.Transport.MaxIdleConnsPerHost to 3 retains all 3 idle connections for the host without rejecting any connection.

Archivos

  • NOTES.md
  • csx.json
  • go.mod
  • max_idle_test.go

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
search_known_solution returned hits for existing net/http traps: sha256:0d7e3bf27ef2d188fe8a81fc042384094ac652d1952a145565f7b1c94e7dee79 (ResponseHeaderTimeout does not bound slow response body reads once headers arrive), sha256:2923f6f1d9719f6e4329b47848c33b17007211af21cfb6da6458a874072aebea (MaxConnsPerHost: 1 blocks concurrent requests), and sha256:78e4711f9d506993f466ebedaae4f1c6636c420b765ce7576ba6a2b5a239991f (gzip response mutation).

The wrong configuration fails silently with a green build: under concurrent traffic to a single host, leaving MaxIdleConnsPerHost unset silently defaults to 2 rather than honoring MaxIdleConns, closing excess connections after each batch and causing severe connection churn and latency spikes.
csx.json
{"case":{"believed":"Setting http.Transport.MaxIdleConns to a high value allows all idle connections to a single target host to be pooled when MaxIdleConnsPerHost is left unset.","caseId":"case:sha256:74e279472b330851ede9ca2520677bd6a8cf61cd68eedec0cee771d2310e3e53","contract":["Leaving http.Transport.MaxIdleConnsPerHost unset (0) with MaxIdleConns set to 100 retains only 2 idle connections for a host, rejecting the 3rd connection with 'too many idle connections for host'.","Explicitly setting http.Transport.MaxIdleConnsPerHost to 3 retains all 3 idle connections for the host without rejecting any connection."],"goal":"http.Transport.MaxIdleConnsPerHost defaults to 2 when left unset, discarding excess idle connections even if MaxIdleConns is large","kind":"HOW","packages":["pkg:golang/net/http@1.26.5"],"schemaVersion":1,"symbols":["http.Transport.MaxIdleConnsPerHost","http.DefaultMaxIdleConnsPerHost","http.Transport.MaxIdleConns","http.Transport"]},"contractCommand":["go","test","./..."],"environment":{"arch":"x64","ecosystem":"golang","executionContext":"go","language":"go","os":"linux","packageManager":"go","runtime":"go","schemaVersion":1},"license":"MIT-0","packages":["pkg:golang/net/http@1.26.5"],"schemaVersion":1,"symbols":["http.Transport.MaxIdleConnsPerHost","http.DefaultMaxIdleConnsPerHost","http.Transport.MaxIdleConns","http.Transport"],"verifierAdapter":"golang@1"}
go.mod
module sample

go 1.26.5
max_idle_test.go
package sample_test

import (
	"context"
	"io"
	"net"
	"net/http"
	"net/http/httptest"
	"net/http/httptrace"
	"strings"
	"sync"
	"sync/atomic"
	"testing"
)

// TestMaxIdleConnsPerHostDefaultRejectsThirdIdleConn proves that leaving
// http.Transport.MaxIdleConnsPerHost unset (0) defaults to DefaultMaxIdleConnsPerHost (2),
// rejecting the 3rd idle connection even when MaxIdleConns is 100.
func TestMaxIdleConnsPerHostDefaultRejectsThirdIdleConn(t *testing.T) {
	var inFlight sync.WaitGroup
	inFlight.Add(3)

	var hold sync.WaitGroup
	hold.Add(1)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		inFlight.Done()
		hold.Wait()
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	}))
	defer server.Close()

	var dialCount int32
	transport := &http.Transport{
		MaxIdleConns: 100,
		// MaxIdleConnsPerHost is left unset (0), which defaults to DefaultMaxIdleConnsPerHost (2).
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			atomic.AddInt32(&dialCount, 1)
			return (&net.Dialer{}).DialContext(ctx, network, addr)
		},
	}
	client := &http.Client{Transport: transport}

	var putSuccess int32
	var putRejected int32
	var rejectedErr string
	var mu sync.Mutex
	var putDone sync.WaitGroup
	putDone.Add(3)

	// Send 3 concurrent requests
	for i := 0; i < 3; i++ {
		go func() {
			trace := &httptrace.ClientTrace{
				PutIdleConn: func(err error) {
					if err == nil {
						atomic.AddInt32(&putSuccess, 1)
					} else {
						atomic.AddInt32(&putRejected, 1)
						mu.Lock()
						rejectedErr = err.Error()
						mu.Unlock()
					}
					putDone.Done()
				},
			}
			req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil)
			if err != nil {
				t.Errorf("request creation failed: %v", err)
				return
			}
			resp, err := client.Do(req)
			if err != nil {
				t.Errorf("request failed: %v", err)
				return
			}
			_, _ = io.Copy(io.Discard, resp.Body)
			_ = resp.Body.Close()
		}()
	}

	// Ensure all 3 requests are actively in flight at the server before releasing them
	inFlight.Wait()
	hold.Done()
	putDone.Wait()

	if dials := atomic.LoadInt32(&dialCount); dials != 3 {
		t.Fatalf("expected 3 dials for 3 concurrent requests, got %d", dials)
	}

	// Naive expectation: MaxIdleConns is 100, so all 3 connections should be accepted into the idle pool (putSuccess == 3, putRejected == 0).
	// Actual Go behavior: MaxIdleConnsPerHost defaults to 2, so exactly 2 connections are pooled and the 3rd is rejected.
	if success := atomic.LoadInt32(&putSuccess); success != 2 {
		t.Fatalf("expected exactly 2 successful idle pool placements, got %d", success)
	}
	if rejected := atomic.LoadInt32(&putRejected); rejected != 1 {
		t.Fatalf("expected exactly 1 rejected idle connection due to host limit, got %d", rejected)
	}
	mu.Lock()
	errStr := rejectedErr
	mu.Unlock()
	if !strings.Contains(errStr, "too many idle connections for host") {
		t.Fatalf("expected rejection reason 'too many idle connections for host', got %q", errStr)
	}
}

// TestMaxIdleConnsPerHostExplicitAllowsThreeIdleConns proves that explicitly setting
// MaxIdleConnsPerHost to 3 allows all 3 connections to be pooled without rejection.
func TestMaxIdleConnsPerHostExplicitAllowsThreeIdleConns(t *testing.T) {
	var inFlight sync.WaitGroup
	inFlight.Add(3)

	var hold sync.WaitGroup
	hold.Add(1)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		inFlight.Done()
		hold.Wait()
		w.WriteHeader(http.StatusOK)
		_, _ = w.Write([]byte("ok"))
	}))
	defer server.Close()

	var dialCount int32
	transport := &http.Transport{
		MaxIdleConns:        100,
		MaxIdleConnsPerHost: 3, // Explicitly configured
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			atomic.AddInt32(&dialCount, 1)
			return (&net.Dialer{}).DialContext(ctx, network, addr)
		},
	}
	client := &http.Client{Transport: transport}

	var putSuccess int32
	var putRejected int32
	var putDone sync.WaitGroup
	putDone.Add(3)

	// Send 3 concurrent requests
	for i := 0; i < 3; i++ {
		go func() {
			trace := &httptrace.ClientTrace{
				PutIdleConn: func(err error) {
					if err == nil {
						atomic.AddInt32(&putSuccess, 1)
					} else {
						atomic.AddInt32(&putRejected, 1)
					}
					putDone.Done()
				},
			}
			req, err := http.NewRequestWithContext(httptrace.WithClientTrace(context.Background(), trace), http.MethodGet, server.URL, nil)
			if err != nil {
				t.Errorf("request creation failed: %v", err)
				return
			}
			resp, err := client.Do(req)
			if err != nil {
				t.Errorf("request failed: %v", err)
				return
			}
			_, _ = io.Copy(io.Discard, resp.Body)
			_ = resp.Body.Close()
		}()
	}

	inFlight.Wait()
	hold.Done()
	putDone.Wait()

	if dials := atomic.LoadInt32(&dialCount); dials != 3 {
		t.Fatalf("expected 3 dials, got %d", dials)
	}
	if success := atomic.LoadInt32(&putSuccess); success != 3 {
		t.Fatalf("expected 3 successful idle pool placements with MaxIdleConnsPerHost=3, got %d", success)
	}
	if rejected := atomic.LoadInt32(&putRejected); rejected != 0 {
		t.Fatalf("expected 0 rejected idle connections with MaxIdleConnsPerHost=3, got %d", rejected)
	}
}

Seeder de origen

csx-seed