render: on macOS the context function's advertised 127.0.0.1:PORT can reach another process's listener (TestListenerRoundTrip flakes)
メンテナーはふだん 3 日以内に返信
まだ誰も着手していません。
評価
- 難易度
- 4/5
- 見積もり時間
- 3〜5日
- 初心者へのやさしさ
- 35/100
- issue の種類
- バグ
- 明瞭さ
- おおむね明確
- 活発さ
- 活発
- 技術スタック
- go, macos
- 領域
- cli, networking
調査の方向性
Start in cmd/crossplane/render/contextfn/listener.go at Start, where the listener is bound to ":0" and the target is advertised as 127.0.0.1:PORT, and read TestListenerRoundTrip in listener_test.go. Run the small two-listener program from the issue on macOS to see the shadowing, and check the lsof output the issue describes. Done means the advertised loopback port always reaches this process on macOS and Linux, and go test -count=100 on TestListenerRoundTrip passes without flakes.
索引モデルが issue の本文から書いたものです。
説明
Usernames and home paths in captured output are redacted to me / /Users/me.
What happened?
TestListenerRoundTrip (cmd/crossplane/render/contextfn) fails intermittently on macOS (found while working on unrelated render PRs) because its RPC reaches a server that isn't the context function:
rpc error: code = Unimplemented desc = unknown service apiextensions.fn.proto.v1.FunctionRunnerServicerpc error: code = Unavailable desc = connection error: desc = "error reading server preface: EOF"... error reading server preface: http2: failed reading the frame payload: http2: frame too large, note that the frame header looked like an HTTP/1.1 header... error reading server preface: read tcp 127.0.0.1:57131->127.0.0.1:57130: read: connection reset by peer
The cause is in the code under test. contextfn.Start listens on ":0" (a dual-stack wildcard, [::]:PORT) and advertises 127.0.0.1:PORT. On macOS (as on other BSD-derived kernels) the wildcard doesn't reserve 127.0.0.1:PORT: another process can listen there too, before or after us, and connections to 127.0.0.1:PORT go to that more specific listener. Linux refuses the second bind, so it isn't affected. Which error you get depends on what that listener speaks: gRPC gives unknown service, HTTP/1.1 gives frame too large, a raw TCP forwarder gives EOF or a reset.
Expected: a client dialing the advertised target always reaches the context function.
A small program shows it deterministically. Listening like Start, then binding 127.0.0.1 on the same port and dialing the advertised target, reaches the second listener on macOS; Linux rejects the second bind. The other bind order behaves the same on macOS.
Program and output
// Listens like contextfn.Start (":0"), then lets a second listener bind
// 127.0.0.1 on the same port, then dials the advertised target
// 127.0.0.1:PORT and reports which listener accepted the connection.
package main
import (
"fmt"
"net"
"time"
)
func try(first string) {
a, err := net.Listen("tcp", first)
if err != nil {
panic(err)
}
defer a.Close()
port := a.Addr().(*net.TCPAddr).Port
b, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
fmt.Printf("listen %-12q -> %s; then listen 127.0.0.1:%d -> %v\n", first, a.Addr(), port, err)
return
}
defer b.Close()
got := make(chan string, 2)
go func() { if _, err := a.Accept(); err == nil { got <- "the first listener" } }()
go func() { if _, err := b.Accept(); err == nil { got <- "the SECOND listener" } }()
c, err := net.Dial("tcp", fmt.Sprintf("127.0.0.1:%d", port))
if err != nil {
panic(err)
}
defer c.Close()
select {
case w := <-got:
fmt.Printf("listen %-12q -> %s; then listen 127.0.0.1:%d -> ok; dial 127.0.0.1:%d reached %s\n", first, a.Addr(), port, port, w)
case <-time.After(2 * time.Second):
fmt.Println("no accept")
}
}
func main() {
try(":0")
try("127.0.0.1:0")
}
macOS:
$ go run .
listen ":0" -> [::]:52543; then listen 127.0.0.1:52543 -> ok; dial 127.0.0.1:52543 reached the SECOND listener
listen "127.0.0.1:0" -> 127.0.0.1:52545; then listen 127.0.0.1:52545 -> listen tcp 127.0.0.1:52545: bind: address already in use
Linux (arm64, in a container):
listen ":0" -> [::]:43583; then listen 127.0.0.1:43583 -> listen tcp 127.0.0.1:43583: bind: address already in use
listen "127.0.0.1:0" -> 127.0.0.1:44079; then listen 127.0.0.1:44079 -> listen tcp 127.0.0.1:44079: bind: address already in use
Long-lived 127.0.0.1 listeners in the ephemeral range are common on a developer Mac (Rancher Desktop's limactl and steve, Chrome, IDEs, ssh forwards). Instrumenting the test to run lsof -nP -iTCP:<port> on failure caught them: the test binary (probe-con…) held *:PORT while steve or limactl held 127.0.0.1:PORT.
Two captured failures
--- FAIL: TestListenerRoundTrip (0.06s)
listener_test.go:60: RunFunction: rpc error: code = Unavailable desc = connection error: desc = "error reading server preface: http2: failed reading the frame payload: http2: frame too large, note that the frame header looked like an HTTP/1.1 header"
pid=42477 lsof:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
steve 9356 me 7u IPv4 0x1762ec606a975469 0t0 TCP 127.0.0.1:49574 (LISTEN)
probe-con 42477 me 4u IPv6 0xc9c60a2a9dce0c78 0t0 TCP *:49574 (LISTEN)
FAIL
--- FAIL: TestListenerRoundTrip (2.06s)
listener_test.go:60: RunFunction: rpc error: code = Unavailable desc = connection error: desc = "error reading server preface: EOF"
pid=42486 lsof:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
limactl 4651 me 9u IPv4 0x4e3222da67fe7a05 0t0 TCP 127.0.0.1:49340 (LISTEN)
probe-con 42486 me 4u IPv6 0xc5d00989bf2fe556 0t0 TCP *:49340 (LISTEN)
FAIL
Failure rate varies with the host's listeners: about 10% of runs on one day (go test -count=50: 5–8 failures), 0 on a quieter one (5 × -count=100 of the test binary, 3 × go test -count=100). For comparable numbers I ran 12 test processes at once, each -test.run '^TestListenerRoundTrip$' -test.count=200 (2,400 runs per round):
| Build | Rounds | Failed runs |
|---|---|---|
origin/main (":0") |
12 (28,800 runs) | 19: per round 2, 1, 2, 0, 1, 1, 2, 1, 1, 3, 1, 4 |
| Proposed fix below | 8 (19,200 runs) | 0: every round 0 |
In 10 of the 19 baseline failures lsof showed another process's 127.0.0.1 listener on the port (limactl 4, steve 2, Chrome 2, a desktop backup agent 2). In the other 9 it had gone by the time lsof ran: 4 frame too large (so an HTTP/1.1 server answered), 1 reset, and 4 DeadlineExceeded … while waiting for connections to become ready. None of these occurred with the fix.
Not just tests. Start's target is what render xr/render op give the render engine, rewritten to host.docker.internal by RewriteAddressesForDocker. With Rancher Desktop's default mapping (Lima's 192.168.5.2), Lima forwards to the host's 127.0.0.1:PORT, so the engine's connection is shadowed the same way. The engine container itself uses host.docker.internal:host-gateway (engine_docker.go), which Rancher resolves to 172.17.0.1; I didn't investigate that path.
Container check
A host program opened a ":0" listener, optionally a second 127.0.0.1:PORT listener, then ran docker run --rm alpine nc host.docker.internal PORT:
shadow=false port=51120 accepted by: contextfn-style listener [::]:51120 (remote 127.0.0.1:51122)
container output: nc exit 0
shadow=true port=51170 accepted by: SHADOW listener 127.0.0.1:51170 (remote 127.0.0.1:51171)
container output: nc exit 0
How can we reproduce it?
On macOS, repeat or parallelize until a run fails (the program above reproduces the underlying behaviour deterministically):
go test -count=100 ./cmd/crossplane/render/contextfn/ -run '^TestListenerRoundTrip$'
Possible fix. Keep the all-interfaces listener: the engine container must reach the context function (e80ffa7: "we have to listen on 0.0.0.0 (not localhost/127.0.0.1) to ensure we're reachable from Docker"). Also claim 127.0.0.1:PORT so nothing else can:
- Listen on
":0"(port P), then on127.0.0.1:P. If that succeeds (macOS/BSD), serve gRPC on both:grpc.Server.Servecan be called per listener, andGracefulStopcloses them all. - If it fails with
EADDRINUSE, either our wildcard already owns loopback (Linux) or another process does (macOS). Dial127.0.0.1:Pand check our listener accepted it: keep the single listener in the first case, try another port in the second.
The patch measured above (against 29316fe) passes go vet and golangci-lint run ./cmd/crossplane/render/contextfn/... and the package's tests on macOS, and go test -count=500 on Linux in a golang:1.26 container.
Patch
--- a/cmd/crossplane/render/contextfn/listener.go
+++ b/cmd/crossplane/render/contextfn/listener.go
@@ -22,6 +22,7 @@ import (
"fmt"
"net"
"sync"
+ "syscall"
"time"
fnv1 "github.com/crossplane/function-sdk-go/proto/v1"
@@ -63,8 +64,7 @@ func Start(ctx context.Context, log logging.Logger, contextData map[string]any)
return nil, errors.Wrap(err, "cannot create capture context function input")
}
- var lc net.ListenConfig
- lis, err := lc.Listen(ctx, "tcp", ":0")
+ lis, err := listen(ctx)
if err != nil {
return nil, errors.Wrap(err, "cannot create listener for context function")
}
@@ -73,7 +73,7 @@ func Start(ctx context.Context, log logging.Logger, contextData map[string]any)
fn := newServer(contextData)
fnv1.RegisterFunctionRunnerServiceServer(srv, fn)
- addr := lis.Addr().(*net.TCPAddr) //nolint:forcetypeassert // We specified "tcp" above.
+ addr := lis[0].Addr().(*net.TCPAddr) //nolint:forcetypeassert // listen only returns TCP listeners.
h := &Handle{
// Report the target as 127.0.0.1:PORT since the render machinery knows
@@ -85,15 +85,81 @@ func Start(ctx context.Context, log logging.Logger, contextData map[string]any)
captureInput: &runtime.RawExtension{Raw: ci},
}
- go func() {
- if err := srv.Serve(lis); err != nil {
- log.Debug("Context function gRPC server stopped", "error", err)
- }
- }()
+ for _, l := range lis {
+ go func() {
+ if err := srv.Serve(l); err != nil {
+ log.Debug("Context function gRPC server stopped", "error", err)
+ }
+ }()
+ }
return h, nil
}
+// listen returns listeners for a single port P that is reachable on all
+// interfaces (so the render engine container can reach it via
+// host.docker.internal) and whose 127.0.0.1:P address - the target we
+// advertise - is guaranteed to reach this process.
+//
+// On BSD-derived kernels such as macOS's, a dual-stack wildcard listener on
+// [::]:P does not stop another process from listening on 127.0.0.1:P (before or
+// after us), and connections to 127.0.0.1:P go to that more specific listener.
+// We therefore also claim 127.0.0.1:P ourselves. On Linux that bind fails
+// because our wildcard listener already owns 127.0.0.1:P; we confirm that by
+// dialing ourselves. If another process owns 127.0.0.1:P we try another port.
+func listen(ctx context.Context) ([]net.Listener, error) {
+ var lc net.ListenConfig
+ for range 10 {
+ all, err := lc.Listen(ctx, "tcp", ":0")
+ if err != nil {
+ return nil, err
+ }
+ port := all.Addr().(*net.TCPAddr).Port //nolint:forcetypeassert // We specified "tcp" above.
+
+ lo, err := lc.Listen(ctx, "tcp4", fmt.Sprintf("127.0.0.1:%d", port))
+ if err == nil {
+ return []net.Listener{all, lo}, nil
+ }
+ if !errors.Is(err, syscall.EADDRINUSE) {
+ _ = all.Close()
+ return nil, err
+ }
+ if servesLoopback(ctx, all, port) {
+ return []net.Listener{all}, nil
+ }
+ _ = all.Close()
+ }
+ return nil, errors.New("cannot find a port whose loopback address is not held by another process")
+}
+
+// servesLoopback reports whether a connection to 127.0.0.1:port is accepted by
+// lis. It must be called before lis is served.
+func servesLoopback(ctx context.Context, lis net.Listener, port int) bool {
+ ctx, cancel := context.WithTimeout(ctx, time.Second)
+ defer cancel()
+
+ var d net.Dialer
+ c, err := d.DialContext(ctx, "tcp4", fmt.Sprintf("127.0.0.1:%d", port))
+ if err != nil {
+ return false
+ }
+ defer c.Close() //nolint:errcheck // Nothing useful to do.
+
+ tl := lis.(*net.TCPListener) //nolint:forcetypeassert // listen only creates TCP listeners.
+ _ = tl.SetDeadline(time.Now().Add(time.Second))
+ defer tl.SetDeadline(time.Time{}) //nolint:errcheck // Nothing useful to do.
+
+ a, err := tl.Accept()
+ if err != nil {
+ return false
+ }
+ defer a.Close() //nolint:errcheck // Nothing useful to do.
+
+ ra := a.RemoteAddr().(*net.TCPAddr) //nolint:forcetypeassert // Accepted from a TCP listener.
+ la := c.LocalAddr().(*net.TCPAddr) //nolint:forcetypeassert // Dialed over TCP.
+ return ra.Port == la.Port && ra.IP.Equal(la.IP)
+}
+
// Stop gracefully stops the function server, which closes its listener. Safe to
// call multiple times.
func (h *Handle) Stop() {
Listening on 127.0.0.1:0 instead also stops the flake (0 failures across 19,200 runs), but reverts e80ffa7: on Linux host.docker.internal:host-gateway resolves to the bridge IP, so the engine container couldn't reach a loopback-only listener.
A deterministic regression test could assert the invariant directly: after Start, binding 127.0.0.1:<port> must fail with EADDRINUSE. On macOS that bind succeeds against origin/main; on Linux it fails before and after the fix.
What environment did it happen in?
- Crossplane CLI version: built from
main@29316fea54f2ede9d2c039d9c54f0c29cbad4b65(go version go1.26.7 darwin/arm64) - Platform (e.g., linux/amd64): darwin/arm64, Docker Engine 29.5.3 (Rancher Desktop)
- Crossplane version (if applicable): n/a (unit test)
- 主要言語
- Go
- スター
- 20
- フォーク
- 34
- 平均マージ
- 5日 4時間
- マージ済み PR(30日)
- 21
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートあり
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
crossplane/cli のほかの issue
-
bug
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
crossplane/cli#432 ·
メンテナーはふだん 3 日以内に返信
-
`credsStore` in docker config causes unit test failures対応中かも @sujeito-operator が 60 日前に担当しました。 オープンbug
難易度 2/5 1〜3時間 初心者へのやさしさ 84/100
crossplane/cli#282 ·
メンテナーはふだん 3 日以内に返信
-
Generated schemas go stale because each source writes into the shared tree on its own対応中かも @stevendborrelli が 3 日前に担当しました。 オープンenhancement
難易度 4/5 3〜5日 初心者へのやさしさ 18/100
crossplane/cli#428 ·
メンテナーはふだん 3 日以内に返信
-
nix.sh: fails immediately when run from a git worktree ("fatal: not a git repository")対応中かも @boxcee-interview が 4 日前に担当しました。 オープンbug
難易度 3/5 半日 初心者へのやさしさ 62/100
crossplane/cli#425 ·
メンテナーはふだん 3 日以内に返信
-
enhancement
難易度 4/5 3〜5日 初心者へのやさしさ 42/100
crossplane/cli#410 ·
メンテナーはふだん 3 日以内に返信
似ている issue
-
難易度 2/5 1〜3時間 初心者へのやさしさ 75/100
メンテナーはふだん 1 日以内に返信
-
ViewData can pair the in-flight proposal with the prepared flag of another proposal対応中かも @HagarMeir が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 82/100
hyperledger/SmartBFT#710 ·
メンテナーはふだん 1 日以内に返信
-
agent-butler-finding chore
難易度 1/5 1時間未満 初心者へのやさしさ 90/100
jordansmall/spindrift#5575 ·
メンテナーはふだん 1 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
open-telemetry/opentelemetry-go-compile-instrumentation#1512 ·
メンテナーはふだん 3 日以内に返信
-
難易度 1/5 1時間未満 初心者へのやさしさ 86/100
OpenPrinting/go-mfp#124 ·
メンテナーはふだん 1 日以内に返信