perf(wirecodec): bound node envelope compression memory (#7275)

The shared zstd encoder for master-to-node request bodies was built with
library defaults: one workspace per CPU, each holding a 16 MiB history for
the default 8 MiB window. The pool hands its workspaces out in rotation and
never frees them, so a 4-vCPU master kept about 70 MiB alive after its
first few pushes and a 16-core one about 280 MiB.

Build it with a 1 MiB window, at most four workers and zstd's low-memory
mode, which retains about 10 MiB whatever the CPU count. Callers queue for
a worker on a slot channel, so a cancelled push stops waiting instead of
blocking inside EncodeAll. Frames stay standard zstd: capability
negotiation, the SHA-256 of the uncompressed body and the node's decode
bounds are unchanged.

Closes #7274
This commit is contained in:
Hamed Sanaei
2026-11-30 01:28:42 +03:30
committed by Sanaei
parent 4a680cb859
commit bd8648de73
3 changed files with 120 additions and 3 deletions
+27 -2
View File
@@ -4,6 +4,7 @@
package wirecodec
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
@@ -39,12 +40,20 @@ const (
// maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from
// an (authenticated) node-API caller.
maxDecodeBytes = 16 << 20
// Node requests reuse a small history and keep a fixed upper bound on
// retained encoder workspaces, even on a master with many CPUs.
encoderWindow = 1 << 20
maxEncoderWorkers = 4
)
// EncodeAll/DecodeAll on these shared instances are safe for concurrent use.
var (
encoderWorkers = min(maxEncoderWorkers, runtime.GOMAXPROCS(0))
encoderSlots = make(chan struct{}, encoderWorkers)
zstdEncoder, _ = zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow),
zstd.WithEncoderConcurrency(encoderWorkers), zstd.WithLowerEncoderMem(true))
decoderWorkers = runtime.GOMAXPROCS(0)
zstdEncoder, _ = zstd.NewWriter(nil)
zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes),
zstd.WithDecodeAllCapLimit(true), zstd.WithDecoderConcurrency(decoderWorkers))
// decodeSlots keeps callers waiting for a decoder worker from each holding an output buffer.
@@ -54,7 +63,23 @@ var (
// Compress zstd-compresses b.
func Compress(b []byte) []byte {
return zstdEncoder.EncodeAll(b, nil)
out, _ := CompressContext(context.Background(), b)
return out
}
// CompressContext lets a caller cancel while waiting for an encoder. Once
// EncodeAll starts it runs synchronously.
func CompressContext(ctx context.Context, b []byte) ([]byte, error) {
select {
case encoderSlots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-encoderSlots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return zstdEncoder.EncodeAll(b, nil), nil
}
// Decompress zstd-decompresses src, rejecting output larger than maxOut (and any
+89
View File
@@ -2,9 +2,16 @@ package wirecodec
import (
"bytes"
"context"
"errors"
"fmt"
"runtime"
"strings"
"sync"
"testing"
"time"
"github.com/klauspost/compress/zstd"
)
func TestCompressRoundTrip(t *testing.T) {
@@ -64,3 +71,85 @@ func TestDecompressOfManyFramesAllocatesTheOutputOnce(t *testing.T) {
t.Fatalf("decoding %d bytes of frames allocated %d MiB", len(src), allocated>>20)
}
}
func TestCompressBoundsFrameWindow(t *testing.T) {
orig := bytes.Repeat([]byte("synthetic node configuration"), 150_000)
packed := Compress(orig)
var header zstd.Header
if err := header.Decode(packed); err != nil {
t.Fatal(err)
}
window := header.WindowSize
if header.SingleSegment {
window = header.FrameContentSize
}
if window > 1<<20 {
t.Fatalf("zstd frame needs %d bytes of window, want at most 1 MiB", window)
}
}
func TestCompressConcurrentFramesAreCompatible(t *testing.T) {
decoder, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1))
if err != nil {
t.Fatal(err)
}
defer decoder.Close()
var callers sync.WaitGroup
for i := range 16 {
callers.Go(func() {
raw := bytes.Repeat([]byte(fmt.Sprintf("client-%d", i)), 40_000)
packed, err := CompressContext(t.Context(), raw)
if err != nil {
t.Errorf("encode %d: %v", i, err)
return
}
got, err := decoder.DecodeAll(packed, nil)
if err != nil || !bytes.Equal(got, raw) {
t.Errorf("decode frame %d with the default decoder: %v", i, err)
}
})
}
callers.Wait()
encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1))
if err != nil {
t.Fatal(err)
}
defer encoder.Close()
raw := bytes.Repeat([]byte("legacy envelope"), 300_000)
decoded, err := Decompress(encoder.EncodeAll(raw, nil), len(raw))
if err != nil || !bytes.Equal(decoded, raw) {
t.Fatalf("decode frame with the legacy default window: %v", err)
}
}
func TestCompressCancelsWhileWaitingForAnEncoder(t *testing.T) {
for range cap(encoderSlots) {
encoderSlots <- struct{}{}
}
defer func() {
for range cap(encoderSlots) {
<-encoderSlots
}
}()
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
called := make(chan struct{})
result := make(chan error, 1)
go func() {
close(called)
_, err := CompressContext(ctx, []byte("waiting for a slot"))
result <- err
}()
<-called
cancel()
select {
case err := <-result:
if !errors.Is(err, context.Canceled) {
t.Fatalf("compression returned %v, want context.Canceled", err)
}
case <-time.After(time.Second):
t.Fatal("compression waited for a slot after cancellation")
}
}