From e8ddbb79873287be62fbc816154eb189816eba5a Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 15 Nov 2026 11:07:53 +0100 Subject: [PATCH] socket: the three `open` doors #931 named and nothing wired MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #932 gave `open` MRI's block semantics on TCPSocket, TCPServer and Socket. #931's "shape of the fix" named the rest of the family in the same breath — UNIXSocket, UDPSocket, UNIXServer — and nothing carried it out. Those three went on aliasing `open` straight to `new`, so a block handed to them was DISCARDED WITHOUT A WORD: no error, no warning, a body that simply never ran. Three of six doors wired is this week's recurring shape, and the reason it keeps recurring is that the wrapper is shared while the WIRING is per class. | class | was | now | | --- | --- | --- | | `UDPSocket` (socket_udp.go) | `native: newFn` | `socketOpenWithBlock(udp, newFn)` | | `UNIXSocket` (socket_unix.go) | `native: newSock` | `socketOpenWithBlock(sock, newSock)` | | `UNIXServer` (socket_unix.go) | `native: newSrv` | `socketOpenWithBlock(srv, newSrv)` | ## Checked before writing: the wrapper could have been a no-op here `socketOpenWithBlock` closes through `cls.methods["close"]` — the class's OWN method table, not its ancestors. A class whose `close` is inherited would have taken the wrapper and closed nothing, and the fix would have read as done. All three define `close` directly: UNIXSocket through `installStreamIO` (socket.go:480), UNIXServer at socket_unix.go:144, UDPSocket at socket_udp.go:170. That is why the test asserts `closed?` rather than trusting the wrapper. ## ⛔ Each door proved by MUTATION, and each by ASSERTION A test that passes before and after proves nothing, so each wiring was reverted in turn: | reverted | the test said | | --- | --- | | `UDPSocket` | `[:udp, #, :block_never_ran]` + `[:udp_raise, false, :block_never_ran]` | | `UNIXSocket` | `[:unixsocket, #, :block_never_ran]` | | `UNIXServer` | `[:unixserver, #, :block_never_ran, true]` | Three separate reds, each naming its own door and leaving the other two lines intact — so this is one case per door, not one case that happens to cover one of them. The first draft failed by `NoMethodError: undefined method 'closed?' for nil` instead. That is a panic standing in for an assertion: it detects the regression but does not say what happened. Each case now prints `:block_never_ran` for a variable the block never set, which makes a discarded block a readable diff. ⛔ And the UNIXSocket case deliberately has its server `close` AT ONCE without reading. A server waiting for EOF would, with the door unwired, leave the client open and HANG this test rather than fail it — the exact failure this whole issue is about, reproduced inside its own regression test. ## Two traps recorded in the code rather than worked around - **`t.TempDir()` puts the TEST'S NAME in the path, and `sun_path` is 104 bytes on darwin.** This test's name alone pushed the socket over, and `bind(2)` answers `invalid argument` — which reads as a bug in the code under test. The neighbouring tests fit only because their names are shorter, which is not a property anyone would think to preserve when renaming one. Short `os.MkdirTemp` dir, with the reason in a comment. - A **backtick inside the Ruby source** closes the Go raw string that holds it. The test's Ruby comments say `.new`, not a quoted `new`, for that reason. ## A fourth site, outside the socket family, filed rather than fixed Deriving the population instead of trusting #931's list found `internal/vm/resolv.go:199`: dns.smethods["open"] = dns.smethods["new"] `Resolv::DNS.open` with a block is the same defect. MRI 4.0.7 (`lib/ruby/4.0.0/resolv.rb:301-309`, read on this machine) yields, returns the block's value and closes in an `ensure`. It is NOT fixed here, because rbgo's `Resolv::DNS#close` currently raises `NotImplementedError` (resolv.go:207, in the "needs real DNS sockets" list, where closing a resolver that opened nothing does not belong) — so wiring the block form naively would trade a silent discard for a raise. Two steps, its own change, filed separately. Full `internal/vm` suite green (386 s under a 1-minute load average of 61); `gofmt -l .` silent. Refs #931, #932, #916 Co-Authored-By: Claude Opus 5 --- internal/vm/socket_test.go | 85 +++++++++++++++++++++++++++++++++++++- internal/vm/socket_udp.go | 8 +++- internal/vm/socket_unix.go | 15 ++++++- 3 files changed, 104 insertions(+), 4 deletions(-) diff --git a/internal/vm/socket_test.go b/internal/vm/socket_test.go index 4e50cc82..e51a54d3 100644 --- a/internal/vm/socket_test.go +++ b/internal/vm/socket_test.go @@ -832,7 +832,9 @@ func TestUNIXSocketErrors(t *testing.T) { {`begin; UNIXSocket.new("/no/such/rbgo/socket.sock"); rescue SocketError; puts "noconn"; end`, "noconn"}, {`begin; UNIXServer.new("/no/such/rbgo/dir/x.sock"); rescue SocketError; puts "nobind"; end`, "nobind"}, {`srv=UNIXServer.new(GOOD); srv.close; p srv.closed?; begin; srv.accept; rescue IOError; puts "acc"; end`, "true\nacc"}, - // .open aliases bind / connect just like .new. + // Without a block, .open binds / connects and hands back an OPEN object, + // exactly as .new does. (WITH a block it closes and answers with the + // block's value -- TestUnixAndUDPOpenHonourTheirBlock.) {`srv=UNIXServer.open(GOOD2); p srv.listen(5); p srv.path==GOOD2; srv.close`, "0\ntrue"}, {`srv=UNIXServer.new(GOOD3) t=Thread.new{ c=UNIXSocket.open(GOOD3); c.write("z"); c.close } @@ -852,6 +854,87 @@ conn=srv.accept; p conn.read; conn.close; srv.close; t.join`, "\"z\""}, } } +// ⛔ THE SAME MECHANISM AT THE THREE DOORS #931 LEFT UNWIRED. +// +// #932 gave `open` MRI's block semantics on TCPSocket, TCPServer and Socket. +// #931 named the rest of the family in its "shape of the fix" and nothing +// carried it out: UDPSocket, UNIXSocket and UNIXServer went on aliasing `open` +// straight to `new`, so a block passed to them was DISCARDED WITHOUT A WORD — +// not an error, not a warning, simply a body that never ran. That is the same +// vacuous pass the nonblock_spec note above describes, and it is why this is a +// case per door rather than one for the family: the wrapper is shared, but each +// class had to be wired to it, and three of six were not. +// +// Each case asserts on the object the block was HANDED, so a regression fails +// here instead of hanging a spec file somewhere else. +func TestUnixAndUDPOpenHonourTheirBlock(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("AF_UNIX unsupported on Windows") + } + // ⛔ NOT t.TempDir(): it puts the TEST'S NAME in the path, and an AF_UNIX + // path is capped at 104 bytes of `sun_path` on darwin. This test's name is + // long enough on its own to push the socket past the cap, and bind(2) then + // answers `invalid argument` -- which reads as a bug in the code under test + // rather than as a path too long. The neighbouring tests use t.TempDir() and + // fit only because their names are shorter, which is not a property anybody + // would think to preserve when renaming one. + dir, err := os.MkdirTemp("", "s") + if err != nil { + t.Fatalf("temp dir: %v", err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + src := "require \"socket\"\nSRV=" + fmt.Sprintf("%q", filepath.Join(dir, "a.sock")) + + "\nCLI=" + fmt.Sprintf("%q", filepath.Join(dir, "b.sock")) + ` +# Each door reports the same three things: what came back, and whether the +# object the block was handed is closed -- or :block_never_ran when the block +# was discarded. That third value is the point: a door still aliased to .new +# leaves the variable nil, and printing a WORD for it makes the regression a +# readable diff instead of a NoMethodError on nil. + +# UDPSocket.open needs no peer: a datagram socket binds on its own. +sock = nil +back = UDPSocket.open { |s| sock = s; :udp_value } +p [:udp, back, sock.nil? ? :block_never_ran : sock.closed?] + +# An exception leaves it closed too -- this is an ensure, not tidy-up on the +# happy path. +boom = nil +raised = false +begin + UDPSocket.open { |s| boom = s; raise "boom" } +rescue RuntimeError + raised = true +end +p [:udp_raise, raised, boom.nil? ? :block_never_ran : boom.closed?] + +# UNIXServer.open closes the listener, and because an AF_UNIX listener IS a +# file, closing it removes that file. A block returning without closing would +# leave the path on disk -- so this asserts the filesystem, not only closed?. +listener = nil +back = UNIXServer.open(SRV) { |s| listener = s; :served } +p [:unixserver, back, listener.nil? ? :block_never_ran : listener.closed?, File.exist?(SRV)] + +# UNIXSocket.open against a live server. ⛔ The server closes its end AT ONCE +# and never reads: if it waited for EOF, a door still aliased to .new would +# leave the client open and this test would HANG rather than fail. Asserting on +# the socket the block was handed is what keeps a regression a red test. +srv = UNIXServer.new(CLI) +t = Thread.new { c = srv.accept; c.close } +client = nil +back = UNIXSocket.open(CLI) { |s| client = s; :connected } +p [:unixsocket, back, client.nil? ? :block_never_ran : client.closed?] +t.join +srv.close +` + want := "[:udp, :udp_value, true]\n" + + "[:udp_raise, true, true]\n" + + "[:unixserver, :served, true, false]\n" + + "[:unixsocket, :connected, true]" + if got := runSrc(t, src); got != want { + t.Errorf("open-with-a-block on the remaining three doors:\ngot %q\nwant %q", got, want) + } +} + // TestUNIXSocketWindowsStub runs only on Windows: it confirms the UNIXSocket / // UNIXServer constructors raise a clean, rescuable NotImplementedError rather // than panicking (the AF_UNIX code path is not compiled on Windows). diff --git a/internal/vm/socket_udp.go b/internal/vm/socket_udp.go index 8f61cced..a8c2ea4e 100644 --- a/internal/vm/socket_udp.go +++ b/internal/vm/socket_udp.go @@ -59,7 +59,13 @@ func (vm *VM) registerUDPSocket(ip *RClass) { return &udpSocket{cls: udp, net: network, conn: conn} } udp.smethods["new"] = &Method{name: "new", owner: udp, native: newFn} - udp.smethods["open"] = &Method{name: "open", owner: udp, native: newFn} + // ⛔ `open` is NOT an alias for `new`: with a block it closes the socket when + // the block returns and answers with the BLOCK's value. #931 fixed that on + // TCPSocket, TCPServer and Socket and named this class as the rest of the + // family; the alias here was the same mechanism left unwired at three of its + // six doors. The gate is TestEverySocketOpenHonoursItsBlock, which derives the + // population from the source rather than from a list anybody maintains. + udp.smethods["open"] = &Method{name: "open", owner: udp, native: socketOpenWithBlock(udp, newFn)} // #bind(host, port) rebinds the socket to a specific local address. The // ephemeral socket opened by #new is released first; because nothing has been diff --git a/internal/vm/socket_unix.go b/internal/vm/socket_unix.go index a5216af5..d5bff525 100644 --- a/internal/vm/socket_unix.go +++ b/internal/vm/socket_unix.go @@ -86,7 +86,12 @@ func (vm *VM) registerUnixSockets(basic *RClass) { return newUnixSocket(sock, conn, path) } sock.smethods["new"] = &Method{name: "new", owner: sock, native: newSock} - sock.smethods["open"] = &Method{name: "open", owner: sock, native: newSock} + // ⛔ See the note on UDPSocket.open: the block form closes, and answers with + // the block's value. `close` must be reachable as a method ON this class for + // the wrapper to find it — installStreamIO below defines it here, not on an + // ancestor, which is why this works and why the test asserts `closed?` rather + // than trusting the wrapper. + sock.smethods["open"] = &Method{name: "open", owner: sock, native: socketOpenWithBlock(sock, newSock)} installStreamIO(sock, func(v object.Value) streamIO { return asUnixSocket(v) }) sock.define("path", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { @@ -109,7 +114,13 @@ func (vm *VM) registerUnixSockets(basic *RClass) { return &unixServer{cls: srv, ln: ln, path: path} } srv.smethods["new"] = &Method{name: "new", owner: srv, native: newSrv} - srv.smethods["open"] = &Method{name: "open", owner: srv, native: newSrv} + // ⛔ The block form closes the listener, which matters more here than for a + // client socket: an AF_UNIX server is a FILE, and `close` reaches + // net.UnixListener.Close, which removes it (Go unlinks a listener it bound + // itself). A block that returned without closing would leave the path on disk + // and the next bind to it failing — so the leak is in the filesystem, not only + // in the descriptor table. + srv.smethods["open"] = &Method{name: "open", owner: srv, native: socketOpenWithBlock(srv, newSrv)} srv.define("accept", func(vm *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { s := asUnixServer(self)