Skip to content

fix: stop the first Close from returning net.ErrClosed - #564

Draft
mafredri wants to merge 4 commits into
masterfrom
mafredri/fix-close-race-net-errclosed
Draft

mafredri wants to merge 4 commits into
masterfrom
mafredri/fix-close-race-net-errclosed

Conversation

@mafredri

@mafredri mafredri commented May 22, 2026 •

Copy link
Copy Markdown
Member

The first call to Close or CloseNow could return failed to close WebSocket: use of closed network connection even when the connection had closed normally. This happens when the library closes the connection before the user calls Close: after the peer's close frame is read, when CloseRead receives a data message, when a NetConn reads a message of the wrong type, or when wsjson.Read receives a message that is not valid JSON. On Wasm, the same error appeared after the browser closed the connection. Code that reads until a close error and then calls Close therefore failed on every normal peer close.

Now the first user call to Close or CloseNow returns nil in these cases. On native, it still waits until the connection, and the CloseRead goroutine if any, have finished closing. On Wasm, it waits until the browser has closed the connection, but not for the CloseRead goroutine. Later calls behave as before: a call that closes the connection returns the result of that close, and a call that finds the connection closing or closed waits, then returns net.ErrClosed. If a later call closes the connection before the first call starts closing it, the first call also returns nil.

Library code that closes the connection, including wsjson.Read, now calls an internal function instead of Close, so it does not use up the user's first call. On Wasm this covers the error event, failed writes, the read limit, the read timeout, CloseRead and the finalizer.

TestConn/firstCloseAfterLibraryClose and TestWasmFirstCloseAfterPeerClose fail on master with the error above and pass on this branch. go test -race ./... and TestWasm pass.

Refs coder/internal#1541

Decision log
  • Only the user's first call turns net.ErrClosed into nil. A later call that finds the connection closing or closed keeps returning net.ErrClosed, because repeated-Close behavior is a separate decision.
  • On native, the first call still waits for the connection's goroutines before it returns.
  • Rejected checking only whether the connection is closed: the user's first call would return net.ErrClosed after a library close finished.
  • Library callers use the internal close. If they called Close, they would use up the user's first call and the user's own Close would still fail; the closeReadDataMessage, netConnUnexpectedType and wsjsonInvalidJSON subtests cover this.
  • wsjson is a separate package and cannot call the unexported internal close, so package websocket stores it in internal/libclose during initialization, and wsjson.Read calls it from there. This adds no public API.
  • Wasm CloseRead defers the internal close with StatusGoingAway, which is what Wasm CloseNow sends.
  • The "Additional calls to Close are no-ops" doc comment is unchanged. It is inaccurate on master too, and fixing it belongs to the repeated-Close decision.
  • The closeReadDataMessage subtests take 15s because the CloseRead goroutine waits for its own exit until the 15s timeout. Master has the same wait; this PR does not change it. fix: stop CloseRead from waiting on itself #607 removes the wait, and it conflicts with this PR where the CloseRead goroutine closes the connection in read.go.
  • The TestWasm server closes first when the client requests the close subprotocol.

🤖 This PR was created with the help of Coder Agents.

@mafredri
mafredri force-pushed the mafredri/fix-close-race-net-errclosed branch 2 times, most recently from b76fd5d to e5aa423 Compare May 22, 2026 11:13
@mafredri

This comment has been minimized.

@coder-agents-review

coder-agents-review Bot commented May 22, 2026 •

Copy link
Copy Markdown

Review posted | Chat
Requested: 2026-05-22 14:18 UTC by @mafredri

Review history
  • R1 (2026-05-22): 12 reviewers, 2 Nit, 2 Note, 1 P2, 3 P3, COMMENT. Review

deep-review v0.13.0 | Round 2 | 12c866f..538ba5c

Last posted: Round 2, 10 findings (2 P2, 4 P3, 2 Nit, 2 Note), COMMENT. Review

Finding inventory

Findings

# Sev Status Location Summary Round Reviewer Posted
CRF-1 P3 Author contested; panel re-raised R2 close.go:92 Doc comment claims "Additional calls to Close are no-ops" but post-close calls return net.ErrClosed R1 Netero, Pariston Yes
CRF-2 Note Dropped by orchestrator (pre-existing, outside diff) close_test.go:49 Pre-existing tc := tc in 4 range loops, unnecessary since Go 1.22 R1 Netero No
CRF-3 P2 Author fixed (538ba5c) close.go:102 No regression test for the race condition this PR fixes R1 Bisky P1, Hisoka P2, Mafu-san P2, Mafuuu P2, Meruem P2, Chopper P2, Pariston P3, Leorio P3, Takumi P3 Yes
CRF-4 P3 Author contested; panel closed R2 (1/1 accept) close.go:130 CloseNow doc comment says nothing about repeated or concurrent call behavior R1 Leorio Yes
CRF-5 Nit Author fixed (PR description rewritten) close.go:111 PR description claims concurrent calls "return instantly without blocking" but they block on waitGoroutines for up to 15s R1 Pariston Nit, Mafuuu Note, Takumi Note Yes
CRF-6 P3 Author fixed (538ba5c) conn.go:80 userClosed naming: reads as completion (like closed) but tracks initiation; also set by internal library code via CloseRead R1 Gon P3, Hisoka Note, Chopper Note Yes
CRF-7 Nit Author fixed (538ba5c) conn.go:80 Comment "on first user call" restates what name and type already show R1 Gon P2, Leorio Nit Yes
CRF-8 Note Author fixed (538ba5c) conn.go:80 Close state tracked across three independent boolean-ish variables forming implicit state machine R1 Meruem Yes
CRF-9 Note Author fixed (538ba5c, check removed) close.go:102 Non-atomic gap between userClosed.Swap and isClosed is benign; system converges to correct state R1 Takumi Yes
CRF-10 P3 Open ws_js.go:152 No test covers the Wasm library-close call sites converted to closeWithHandshake R2 Netero Yes
CRF-11 P2 Open read.go:82 CloseRead goroutine waits 15s on its own closeReadDone, so a user Close in that window returns a timeout error instead of nil R2 Mafuuu P2, Takumi P2, Kite P2, Bisky OOS, Pariston OOS, Leorio OOS Yes
CRF-12 P3 Dropped by orchestrator (requester limited R2 to P0-P2 and highly relevant P3) close.go:112 No test checks that a second Close returns net.ErrClosed; removing firstCall && passes all tests R2 Bisky No
CRF-13 Nit Dropped by orchestrator (downgraded from P2: comment is accurate, only longer than needed; requester filter) conn.go:80 closeCalled comment padded R2 Gon P2 No
CRF-14 Nit Dropped by orchestrator (downgraded from P2: comment is accurate, only longer than needed; requester filter) ws_js.go:59 Wasm closeCalled comment padded R2 Gon P2 No
CRF-15 Nit Dropped by orchestrator (downgraded from P2: wording only; requester filter) internal/libclose/libclose.go:1 Package doc padding; "application's" vs "user's" first Close R2 Gon P2 No
CRF-16 Nit Dropped by orchestrator (downgraded from P2: wording only, Leorio rated the same comment a positive Note; requester filter) internal/libclose/libclose.go:6 libclose.Close doc wordy R2 Gon P2, Leorio Note No
CRF-17 P3 Dropped by orchestrator (requester filter; the CRF-10 test would guard this line) ws_js.go:428 No comment on why Wasm CloseRead defers closeWithHandshake instead of CloseNow R2 Gon No
CRF-18 Note Dropped by orchestrator (no action requested) internal/libclose/libclose.go:6 libclose.Close doc explains type and init order R2 Leorio No
CRF-19 OOS Out of scope (body) dial_test.go:48 badTLS case dials external host; TestMain goroutine leak on some networks R2 Netero No
CRF-20 OOS Out of scope (body) ws_js.go:430 Wasm CloseRead close codes inverted relative to native R2 Netero No

Contested and acknowledged

CRF-1 (P3, close.go:92) - Close doc says additional calls are no-ops

  • Finding: Close's doc comment says "Additional calls to Close are no-ops", but later calls return net.ErrClosed. Proposed: document the actual contract.
  • Author defense (R2 decision log): The sentence is inaccurate on master too; fixing it belongs to the repeated-Close decision. Only the first user call maps net.ErrClosed to nil.
  • Panel re-raised (R2): Netero (new agent; round-1 agent unavailable in this orchestrator chat) re-raised: the PR adds the first-call guarantee and the doc neither states it nor matches later-call behavior; updating the text records shipped behavior and does not decide the repeated-Close question. Pariston (new agent, same reason) accepted the defense as pre-existing. One re-raise keeps it open. Leorio supplied replacement text that also covers CloseNow.

CRF-4 (P3, close.go:130) - CloseNow doc silent on repeated calls

  • Finding: CloseNow's doc says nothing about repeated or concurrent calls, based on the round-1 contract where concurrent calls returned nil.
  • Author defense (R2 decision log): Repeated-call behavior is now the same as master; that behavior is a separate decision.
  • Panel closure (R2, 1/1): Leorio (new agent; round-1 agent unavailable in this orchestrator chat) accepted: the round-1 prescription described a contract the head removed, and CloseNow's doc tells callers no less than on master. The remaining doc gap for CloseNow is folded into CRF-1's fix text.

Round log

Round 1

Panel. 1 P2, 3 P3, 2 Nit, 2 Note new. 1 pre-existing Note dropped. Reviewed against d099e16..e5aa423. Panel: Bisky, Hisoka, Mafu-san, Mafuuu, Pariston, Ging-Go, Gon, Leorio, Takumi, Meruem, Killua, Chopper.

Round 2

Restructure round (internal/libclose added, Close/CloseNow rewritten as wrappers, description rewritten). Churn guard PROCEED: CRF-3, 5, 6, 7, 8, 9 addressed; CRF-1, CRF-4 contested. Netero: 1 P3 (CRF-10), 2 OOS. Panel: Pariston, Mafuuu, Ging-Go, Takumi, Ryosuke, Melody, Killua, Bisky, Gon, Leorio, Kite (wildcard). Size 11 exceeds focused target: specialists Ging-Go, Takumi, Ryosuke, Melody, Killua triggered; Gon and Leorio mandatory on restructure; Leorio also contested. No previous agents existed in this orchestrator chat, so Netero, Pariston and Leorio were new agents reading round-1 outputs.
Requester asked to limit to P0-P2 and highly relevant P3. New: 1 P2 (CRF-11), 2 P3, 4 Nit, 1 Note, 2 OOS. Posted: CRF-11, CRF-10, CRF-1 re-raise.
Drop/downgrade gate: CRF-13..16 keep-argument: four of the PR's new comments carry padding and one name mismatch, and the PR author will not revisit them. Downgrade reason: every comment is accurate and the cost is reading length, which is a style Nit, and the requester excluded P3 and below. CRF-12 keep-argument: removing firstCall && in Close passes all tests, so later-call behavior the decision log keeps is unguarded. Not posted per requester filter; behavior matches master. CRF-11 OOS (Bisky, Pariston, Leorio) vs P2 (Mafuuu, Takumi, Kite): P2 wins; the PR's description claims the first Close returns nil after a CloseRead data message, read.go:82 is a changed line, and three reviewers reproduced the timeout error.
Reviewed against 12c866f..538ba5c.

About deep-review

CRF = Coder Review Finding (P0-P4, Nit, Note)

Reviewer Focus
Bisky tests
Chopper ops/errors
Churn-guard change verification
Ging language modernization
Gon naming
Hisoka edge cases
Killua perf
Kite change integrity
Knov contracts
Knuckle SQL
Kurapika security
Leorio docs
Luffy product
Mafu-san process
Mafuuu contracts
Melody dispatch/pairing
Meruem structural
Nami frontend
Netero mechanical checks
Pariston premise testing
Pen-botter product gaps
Razor verification
Robin duplication
Ryosuke Go arch
Takumi concurrency
Zoro shape

🤖 Managed by Coder Agents.

coder-agents-review[bot]

This comment was marked as outdated.

@mafredri
mafredri force-pushed the mafredri/fix-close-race-net-errclosed branch from e5aa423 to 21b8e2a Compare October 28, 2026 15:55
@mafredri mafredri changed the title fix: suppress net.ErrClosed on concurrent Close fix: stop the first Close from returning net.ErrClosed Oct 28, 2026
@mafredri
mafredri force-pushed the mafredri/fix-close-race-net-errclosed branch from 21b8e2a to 60b4584 Compare November 3, 2026 19:14
@mafredri

This comment has been minimized.

@linear-code

linear-code Bot commented Nov 17, 2026

Copy link
Copy Markdown

CODAGT-1601

Close and CloseNow returned a wrapped net.ErrClosed when the
internal read loop or write path won the casClosing race before
the user-facing call. The defer that suppresses net.ErrClosed
was only registered on the CAS winner path.

Separate user-facing close tracking from internal close
coordination. A userClosed atomic tracks whether the user has
called Close/CloseNow before. Combined with isClosed, this
gives three distinct behaviors:

- First user call, close in progress or peer closed: nil.
- Concurrent user calls while close is in progress: nil,
  returns instantly without blocking.
- User call after close has fully completed: net.ErrClosed.
When the read or write path closed the connection first, for example
after the peer's close frame, the user's first Close or CloseNow
returned a wrapped net.ErrClosed. The first user call now returns nil in
that case, and library code that closes the connection (CloseRead and
NetConn reads) uses an internal close so it does not count as that call.
On Wasm, the user's first Close returned a wrapped net.ErrClosed after
the browser or library code had already closed the connection, the same
failure as the native fix. Close now applies the same first-call rule,
and the read limit, read timeout, CloseRead and finalizer paths use an
internal close. TestWasm gains a server mode that closes first.
@mafredri
mafredri force-pushed the mafredri/fix-close-race-net-errclosed branch from 60b4584 to aca4625 Compare November 20, 2026 14:42
wsjson.Read closed the connection with the public Close when the
message was not valid JSON, so the application's first Close or
CloseNow returned net.ErrClosed. wsjson cannot call the unexported
closeWithHandshake, so package websocket stores it in
internal/libclose during initialization and wsjson.Read calls it
from there.
@mafredri

Copy link
Copy Markdown
Member Author

/coder-agents-review Please limit the review to P0, P1, P2 issues only. Include only highly relevant P3 issues.

🤖 Created with the help of Coder Agents.

@coder-agents-review

coder-agents-review Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Chat: Review in progress (13/13 reviewers complete) | View chat
Requested: 2026-11-24 14:48 UTC by @mafredri
Spend: $9.75 / $100.00

🤖 Managed by Coder Agents.

@coder-agents-review coder-agents-review Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This round reviews the rewritten branch, which routes library closes through internal closeWithHandshake and closeWithoutHandshake so the user's first Close or CloseNow returns nil after a library or peer close. As requested, it posts P0 to P2 findings and only the most relevant P3 findings: 1 P2, 2 P3.

The new tests cover the bug from round 1, and the naming, comment, description and isClosed race findings are addressed. The CloseNow doc finding is closed. The Close doc finding is still open; see the reply below.

Out of scope (needs a ticket or explicit acceptance by a human):

  • dial_test.go:48: the badTLS case dials the external host totallyfake.nhooyr.io, so go test -race ./... fails TestMain with a goroutine leak on networks where that dial leaves TLS goroutines running (reproduced on head and base).
  • ws_js.go:430: Wasm CloseRead sends StatusPolicyViolation "unexpected data message" when c.read returns an error and StatusGoingAway when it receives a data message, the inverse of native read.go:81, so a Wasm peer that sends data after CloseRead receives 1001 instead of 1008.

In reply to PRR_kwDOCJ5FYc8AAAABAxB24A:

The close.go:93 doc finding is still open. The behavior it misstates predates this PR, but this PR adds the first-call guarantee (close.go:110, close.go:163, ws_js.go:240) and the doc does not state it, so godoc readers cannot learn the contract this PR ships. Updating the text records current behavior and does not decide the repeated-Close question. Suggested text for native Close, Wasm Close and CloseNow:

// If the connection is already closing or closed, for example after a read
// returned the peer's close frame, the first call to Close or CloseNow waits
// for the close to finish and returns nil. A later call that finds the
// connection closing or closed waits, then returns an error wrapping
// net.ErrClosed.

🤖

🤖 This review was automatically generated with Coder Agents.

Comment thread read.go Resolved
Comment thread ws_js.go Resolved
@mafredri

This comment has been minimized.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant