Skip to content

Commit 7e682ad

Browse files
committed
Make conn closed on receive not safe to retry
receiveMessage returned a connLockError when the connection was already closed. connLockError is always SafeToRetry, but the closed status is only seen in receiveMessage after an earlier read or write in the same operation failed, so a request may already have been sent. For example, Exec notices a dropped connection while peeking at the reply, closes the connection, and then receiveMessage reports "conn closed" as safe to retry. With stdlib, db.ExecContext(ctx, "insert ...") with no arguments uses the simple protocol, ExecContext maps a SafeToRetry error to driver.ErrBadConn, and database/sql then re-runs the INSERT on a new connection. pgx's Tx.Commit has the same flaw for callers that retry on SafeToRetry. Return an error that still wraps ErrConnClosed and keeps the "conn closed" text, but is not safe to retry. connLockError is now only used by lock(), where it is correct. Fixes #2700
1 parent b2ef08b commit 7e682ad

3 files changed

Lines changed: 102 additions & 2 deletions

File tree

‎pgconn/errors.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ func (e *sslCertModeError) Error() string {
105105
// ErrConnClosed is returned (possibly wrapped) when an operation is attempted
106106
// on a connection that the driver has already closed, e.g. because a prior
107107
// query was cancelled mid-flight or the underlying socket went away. Use
108-
// errors.Is to test for it, since it shows up wrapped inside connLockError.
108+
// errors.Is to test for it, since it is usually wrapped in another error.
109109
var ErrConnClosed = errors.New("conn closed")
110110

111111
type connLockError struct {

‎pgconn/pgconn.go‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -717,7 +717,9 @@ func (pgConn *PgConn) peekMessage() (pgproto3.BackendMessage, error) {
717717
// receiveMessage receives a message without setting up context cancellation
718718
func (pgConn *PgConn) receiveMessage() (pgproto3.BackendMessage, error) {
719719
if pgConn.status == connStatusClosed {
720-
return nil, &connLockError{status: "conn closed"}
720+
// The connection was closed by a failure earlier in this operation, after a request may already have been sent.
721+
// Unlike a lock failure this is not safe to retry.
722+
return nil, &pgconnError{err: ErrConnClosed, safeToRetry: false}
721723
}
722724

723725
msg, err := pgConn.peekMessage()

‎pgconn/pgconn_test.go‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3437,6 +3437,104 @@ func TestExecOnClosedConnErrConnClosed(t *testing.T) {
34373437
assert.ErrorIs(t, err, pgconn.ErrConnClosed)
34383438
}
34393439

3440+
// When the connection is lost after a statement was written, the server may already have executed it. The resulting
3441+
// error must not be SafeToRetry, or a caller that retries on SafeToRetry could run a statement such as COMMIT twice.
3442+
// See https://github.com/jackc/pgx/issues/2700.
3443+
func TestConnLostAfterStatementWrittenIsNotSafeToRetry(t *testing.T) {
3444+
t.Parallel()
3445+
3446+
for _, tt := range []struct {
3447+
name string
3448+
expectedSteps []pgmock.Step
3449+
run func(ctx context.Context, pgConn *pgconn.PgConn) error
3450+
wantConnClosed bool
3451+
}{
3452+
{
3453+
name: "Exec",
3454+
expectedSteps: []pgmock.Step{
3455+
pgmock.ExpectMessage(&pgproto3.Query{String: "commit"}),
3456+
},
3457+
run: func(ctx context.Context, pgConn *pgconn.PgConn) error {
3458+
_, err := pgConn.Exec(ctx, "commit").ReadAll()
3459+
return err
3460+
},
3461+
wantConnClosed: true,
3462+
},
3463+
{
3464+
// Already not retryable; guards the extended protocol path.
3465+
name: "ExecParams",
3466+
expectedSteps: []pgmock.Step{
3467+
pgmock.ExpectAnyMessage(&pgproto3.Parse{}),
3468+
pgmock.ExpectAnyMessage(&pgproto3.Bind{}),
3469+
pgmock.ExpectAnyMessage(&pgproto3.Describe{}),
3470+
pgmock.ExpectAnyMessage(&pgproto3.Execute{}),
3471+
pgmock.ExpectAnyMessage(&pgproto3.Sync{}),
3472+
},
3473+
run: func(ctx context.Context, pgConn *pgconn.PgConn) error {
3474+
_, err := pgConn.ExecParams(ctx, "commit", nil, nil, nil, nil).Close()
3475+
return err
3476+
},
3477+
},
3478+
} {
3479+
t.Run(tt.name, func(t *testing.T) {
3480+
t.Parallel()
3481+
3482+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
3483+
defer cancel()
3484+
3485+
// The mock server reads the statement and then closes the connection without replying.
3486+
steps := pgmock.AcceptUnauthenticatedConnRequestSteps()
3487+
steps = append(steps, tt.expectedSteps...)
3488+
script := &pgmock.Script{Steps: steps}
3489+
3490+
ln, err := net.Listen("tcp", "127.0.0.1:")
3491+
require.NoError(t, err)
3492+
defer ln.Close()
3493+
3494+
serverErrChan := make(chan error, 1)
3495+
go func() {
3496+
defer close(serverErrChan)
3497+
3498+
conn, err := ln.Accept()
3499+
if err != nil {
3500+
serverErrChan <- err
3501+
return
3502+
}
3503+
defer conn.Close()
3504+
3505+
err = conn.SetDeadline(time.Now().Add(5 * time.Second))
3506+
if err != nil {
3507+
serverErrChan <- err
3508+
return
3509+
}
3510+
3511+
err = script.Run(pgproto3.NewBackend(conn, conn))
3512+
if err != nil {
3513+
serverErrChan <- err
3514+
return
3515+
}
3516+
}()
3517+
3518+
host, port, _ := strings.Cut(ln.Addr().String(), ":")
3519+
connStr := fmt.Sprintf("sslmode=disable host=%s port=%s", host, port)
3520+
3521+
pgConn, err := pgconn.Connect(ctx, connStr)
3522+
require.NoError(t, err)
3523+
defer pgConn.Close(ctx)
3524+
3525+
err = tt.run(ctx, pgConn)
3526+
require.Error(t, err)
3527+
if tt.wantConnClosed {
3528+
assert.EqualError(t, err, "conn closed")
3529+
assert.ErrorIs(t, err, pgconn.ErrConnClosed)
3530+
}
3531+
assert.False(t, pgconn.SafeToRetry(err), "statement was already written: %v", err)
3532+
3533+
require.NoError(t, <-serverErrChan)
3534+
})
3535+
}
3536+
}
3537+
34403538
func TestConnCloseWhileCancellableQueryInProgress(t *testing.T) {
34413539
t.Parallel()
34423540

0 commit comments

Comments
 (0)