Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pgx.Conn: Fix memory leak: Delete items from preparedStatements #1614

Merged
merged 1 commit into from
May 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -1326,6 +1326,7 @@ func (c *Conn) deallocateInvalidatedCachedStatements(ctx context.Context) error

for _, sd := range invalidatedStatements {
pipeline.SendDeallocate(sd.Name)
delete(c.preparedStatements, sd.Name)

Choose a reason for hiding this comment

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

this actually might not solve the "leak" issue, since Go won't deallocate memory after you delete a key from a map golang/go#20135

Copy link
Contributor Author

Choose a reason for hiding this comment

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

The map itself won't shrink, but delete() does zero the keys and values in the map, so the *pgconn.StatementDescription value will be garbage collected. Additionally, delete() decrements the size of the map, which means its capacity will now be limited to the max number of prepared statements (with extra space for the map "fill factor"). This means this change should mean the amount of memory used by the c.preparedStatements is now fixed, rather than increasing without bound.

Additionally, my reproduction program on the original issue can run forever without running out of memory: #1456 (comment)

So: I'm pretty confident that this fix will resolve this specific bug at least. There could be others though! I would be happy to try to figure them out if we have a sample program that reproduces the problem.

Choose a reason for hiding this comment

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

delete() does zero the keys and values in the map

yes, only if they poiners

Additionally, delete() decrements the size of the map

I can be wrong, but regarding this example the allocated size of the map would be the same.

which means its capacity will now be limited to the max number of prepared statements

well I guess it's true if the pgx has limitations to prepared statement cache

}

err := pipeline.Sync()
Expand Down
55 changes: 55 additions & 0 deletions conn_internal_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package pgx

import (
"context"
"fmt"
"os"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)

func mustParseConfig(t testing.TB, connString string) *ConnConfig {
config, err := ParseConfig(connString)
require.Nil(t, err)
return config
}

func mustConnect(t testing.TB, config *ConnConfig) *Conn {
conn, err := ConnectConfig(context.Background(), config)
if err != nil {
t.Fatalf("Unable to establish connection: %v", err)
}
return conn
}

// Ensures the connection limits the size of its cached objects.
// This test examines the internals of *Conn so must be in the same package.
func TestStmtCacheSizeLimit(t *testing.T) {
const cacheLimit = 16

connConfig := mustParseConfig(t, os.Getenv("PGX_TEST_DATABASE"))
connConfig.StatementCacheCapacity = cacheLimit
conn := mustConnect(t, connConfig)
defer func() {
err := conn.Close(context.Background())
if err != nil {
t.Fatal(err)
}
}()

// run a set of unique queries that should overflow the cache
ctx := context.Background()
for i := 0; i < cacheLimit*2; i++ {
uniqueString := fmt.Sprintf("unique %d", i)
uniqueSQL := fmt.Sprintf("select '%s'", uniqueString)
var output string
err := conn.QueryRow(ctx, uniqueSQL).Scan(&output)
require.NoError(t, err)
require.Equal(t, uniqueString, output)
}
// preparedStatements contains cacheLimit+1 because deallocation happens before the query
assert.Len(t, conn.preparedStatements, cacheLimit+1)
assert.Equal(t, cacheLimit, conn.statementCache.Len())
}