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

Use proper zstd decoder pool for binlog event compression handling #17042

Merged
merged 8 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 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
61 changes: 36 additions & 25 deletions go/mysql/binlog_event_compression.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@ package mysql
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"sync"

"github.com/klauspost/compress/zstd"

"vitess.io/vitess/go/stats"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/vterrors"

vtrpcpb "vitess.io/vitess/go/vt/proto/vtrpc"
Expand Down Expand Up @@ -89,23 +89,14 @@ var (
// allocations and GC overhead so this pool allows us to handle
// concurrent cases better while still scaling to 0 when there's no
// usage.
statefulDecoderPool sync.Pool
statefulDecoderPool = &decoderPool{}
)

func init() {
var err error
statelessDecoder, err = zstd.NewReader(nil, zstd.WithDecoderConcurrency(0))
if err != nil { // Should only happen e.g. due to ENOMEM
log.Errorf("Error creating stateless decoder: %v", err)
}
statefulDecoderPool = sync.Pool{
New: func() any {
d, err := zstd.NewReader(nil, zstd.WithDecoderMaxMemory(zstdInMemoryDecompressorMaxSize))
if err != nil { // Should only happen e.g. due to ENOMEM
log.Errorf("Error creating stateful decoder: %v", err)
}
return d
},
panic(fmt.Errorf("failed to create stateless decoder: %v", err))
Copy link
Contributor

Choose a reason for hiding this comment

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

Should we panic here and prevent the process from launching? Option is for the decompress() to return an error if statefulDecoderPool failed to initialize.

Copy link
Contributor Author

@mattlord mattlord Oct 22, 2024

Choose a reason for hiding this comment

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

It's better to panic, I think, as this is only allocated once at init() time. If we can't initialize it, we won't be able to run properly. The way the code was previously, it would just continually log errors w/o being able to do much. This should only ever fail if you're very low on memory (ENOMEM). This isn't the decoder pool here, it's the global shared stateless decoder used for smaller payloads.

Copy link
Contributor

Choose a reason for hiding this comment

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

Only for compressed payloads, right? Is it documented that this failure can only happen for ENOMEM. In case there is some other issue with zstd preventing the executable from launching seems excessive and risky.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, that's true.... maybe I'll just go back to logging like I was before then. It also has the benefit of limiting the changes.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I went ahead and got rid of the panic and init(): e7191f0

No reason for us NOT to try initializing it again the next time we retry...

}
}

Expand Down Expand Up @@ -304,22 +295,16 @@ func (tp *TransactionPayload) decompress() error {
// larger payloads.
if tp.uncompressedSize > zstdInMemoryDecompressorMaxSize {
in := bytes.NewReader(tp.payload)
streamDecoder := statefulDecoderPool.Get().(*zstd.Decoder)
if streamDecoder == nil {
return vterrors.New(vtrpcpb.Code_INTERNAL, "failed to create stateful stream decoder")
}
if err := streamDecoder.Reset(in); err != nil {
return vterrors.Wrap(err, "error resetting stateful stream decoder")
streamDecoder, err := statefulDecoderPool.Get(in)
if err != nil {
return err
}
compressedTrxPayloadsUsingStream.Add(1)
tp.reader = streamDecoder
return nil
}

// Process smaller payloads using only in-memory buffers.
if statelessDecoder == nil { // Should never happen
return vterrors.New(vtrpcpb.Code_INTERNAL, "failed to create stateless decoder")
}
decompressedBytes := make([]byte, 0, tp.uncompressedSize) // Perform a single pre-allocation
decompressedBytes, err := statelessDecoder.DecodeAll(tp.payload, decompressedBytes[:0])
if err != nil {
Expand All @@ -340,11 +325,8 @@ func (tp *TransactionPayload) decompress() error {
func (tp *TransactionPayload) Close() {
switch reader := tp.reader.(type) {
case *zstd.Decoder:
if err := reader.Reset(nil); err == nil || err == io.EOF {
readersPool.Put(reader)
}
statefulDecoderPool.Put(reader)
default:
reader = nil
}
tp.iterator = nil
}
Expand All @@ -368,3 +350,32 @@ func (tp *TransactionPayload) GetNextEvent() (BinlogEvent, error) {
//func (tp *TransactionPayload) Events() iter.Seq[BinlogEvent] {
// return tp.iterator
//}

// decoderPool manages a sync.Pool of *zstd.Decoders.
type decoderPool struct {
pool sync.Pool
}

// Get gets a pooled OR new *zstd.Decoder.
func (dp *decoderPool) Get(reader io.Reader) (*zstd.Decoder, error) {
var decoder *zstd.Decoder
if pooled := dp.pool.Get(); pooled != nil {
decoder = pooled.(*zstd.Decoder)
rohit-nayak-ps marked this conversation as resolved.
Show resolved Hide resolved
} else {
d, err := zstd.NewReader(nil, zstd.WithDecoderMaxMemory(zstdInMemoryDecompressorMaxSize))
if err != nil { // Should only happen e.g. due to ENOMEM
return nil, vterrors.Wrap(err, "failed to create stateful stream decoder")
}
decoder = d
}
if err := decoder.Reset(reader); err != nil {
return nil, vterrors.Wrap(err, "error resetting stateful stream decoder")
}
return decoder, nil
}

func (dp *decoderPool) Put(decoder *zstd.Decoder) {
if err := decoder.Reset(nil); err == nil || err == io.EOF {
dp.pool.Put(decoder)
rohit-nayak-ps marked this conversation as resolved.
Show resolved Hide resolved
}
}
78 changes: 78 additions & 0 deletions go/mysql/binlog_event_compression_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/*
Copyright 2024 The Vitess Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package mysql

import (
"bytes"
"io"
"testing"

"github.com/klauspost/compress/zstd"
"github.com/stretchr/testify/require"
)

func TestDecoderPool(t *testing.T) {
type args struct {
r io.Reader
}
tests := []struct {
name string
reader io.Reader
wantErr bool
}{
{
name: "happy path",
reader: bytes.NewReader([]byte{0x68, 0x61, 0x70, 0x70, 0x79}),
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// It's not guaranteed that we get the same decoder back from the pool
// that we just put in, so we use a loop and ensure that it worked at
// least one of the times. Without doing this the test would be flaky.
used := false

for i := 0; i < 20; i++ {
decoder, err := statefulDecoderPool.Get(tt.reader)
require.NoError(t, err)
require.NotNil(t, decoder)
require.IsType(t, &zstd.Decoder{}, decoder)
statefulDecoderPool.Put(decoder)

decoder2, err := statefulDecoderPool.Get(tt.reader)
require.NoError(t, err)
require.NotNil(t, decoder2)
require.IsType(t, &zstd.Decoder{}, decoder)
if decoder2 == decoder {
used = true
}
statefulDecoderPool.Put(decoder2)

decoder3, err := statefulDecoderPool.Get(tt.reader)
require.NoError(t, err)
require.NotNil(t, &zstd.Decoder{}, decoder3)
require.IsType(t, &zstd.Decoder{}, decoder3)
if decoder3 == decoder || decoder3 == decoder2 {
used = true
}
statefulDecoderPool.Put(decoder)
}

require.True(t, used)
})
}
}
Loading