From 550c24a27a439a8f11fc38444c08d74732148a37 Mon Sep 17 00:00:00 2001 From: sahilkalgutkar Date: Tue, 8 Sep 2026 23:14:54 -0400 Subject: [PATCH] Stop freePort handing out the same port twice freePort asks the kernel for port 0, records the address and closes the listener before Run binds it. The kernel will not offer a port that is still open, but it does reuse one released a moment ago, so two calls could name the same port and the second bind would fail with "address already in use". It now records every address it issues and skips one already handed out, so no two callers can be pointed at the same port. The window between releasing a port and Run binding it stays, as the comment already noted -- Run owns its listener and cannot be handed one already bound -- but that is the rarer external case, not the suite colliding with itself. Same defect and same fix as raftlite's cli and server tests, where the six-ports-in-a-row case failed CI outright. This one has never fired: three tests call freePort, one port each, and none run in parallel. --- internal/app/app_test.go | 39 +++++++++++++++++++++++++++++++++------ 1 file changed, 33 insertions(+), 6 deletions(-) diff --git a/internal/app/app_test.go b/internal/app/app_test.go index f70f2c7..d3d5827 100644 --- a/internal/app/app_test.go +++ b/internal/app/app_test.go @@ -12,6 +12,7 @@ import ( "os" "path/filepath" "strings" + "sync" "syscall" "testing" "time" @@ -349,19 +350,45 @@ func truncate(s string) string { return s } +// issuedPorts records every address freePort has handed out in this test +// binary, so two callers cannot be pointed at the same one. +var ( + issuedMu sync.Mutex + issuedPorts = map[string]bool{} +) + // freePort asks the kernel for an unused port and gives it straight back. // There is a race between releasing it and Run binding it, but it is the only // way to test the real listener path — Run owns its own listener, so the port // cannot be handed in already bound. +// +// The kernel will not offer a port that is still open, but it does reuse one +// released a moment ago, so repeated calls could name the same port twice and +// the second bind would fail with "address already in use". Anything already +// issued is therefore skipped. func freePort(t *testing.T) string { t.Helper() - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) + for attempt := 0; attempt < 50; attempt++ { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + addr := l.Addr().String() + l.Close() + + issuedMu.Lock() + fresh := !issuedPorts[addr] + if fresh { + issuedPorts[addr] = true + } + issuedMu.Unlock() + + if fresh { + return addr + } } - addr := l.Addr().String() - l.Close() - return addr + t.Fatal("could not find an unused loopback port") + return "" } // TestRunServesThenShutsDownCleanly exercises the real listener and the