Files
magpie/internal/redact/heldsize_test.go
T
yetone 2dfaf75539 redact: a masked body is held at its size, not in a buffer grown by doubling (#3383)
With masking on, the masked body is what a request holds while it
streams (MaskJSON, 285 MB live in the report's heap). walk built it in a
bytes.Buffer grown by doubling, up to twice the body. It now makes room
for the body and a sixteenth at the first value it masks, and copies the
result to its size when placeholders grew it past an eighth spare.

Run:
- the heap probe, 8 requests of 9.7 MB held mid-stream with Privacy
  masking on: 138 MB before, 86 MB after (Anthropic to Anthropic);
  translated to Chat 235 MB before, 183 MB after.
- TestMaskedBodyHeldAtItsSize: green; red with both changes off
  ("the masked body of 4356589 bytes is held in 7077888").
- go test ./internal/redact/ ./internal/masking/ ok; gateway -run
  'Mask|Redact|…' ok (see the commit before).
2026-10-24 21:00:05 +08:00

38 lines
1.1 KiB
Go

package redact
import (
"fmt"
"strings"
"testing"
)
// A masked body is held as the request's body while it streams (#3383),
// so it is held at about its size: a buffer grown by doubling was up to
// twice that, with few values masked or with many placeholders longer
// than what they stand for.
func TestMaskedBodyHeldAtItsSize(t *testing.T) {
for _, every := range []int{1, 400} {
var sb strings.Builder
sb.WriteString(`{"messages":[`)
for i := 0; i < 4000; i++ {
if i > 0 {
sb.WriteString(",")
}
text := strings.Repeat("some words about the build, nothing to mask in them. ", 20)
if i%every == 0 {
text += fmt.Sprintf("mail me at user%d@example.com or call 1380013%04d", i, i)
}
fmt.Fprintf(&sb, `{"role":"user","content":%q}`, text)
}
sb.WriteString(`]}`)
body := []byte(sb.String())
out, n := MaskJSON(body, Options{Personal: true})
if n == 0 {
t.Fatalf("every %d: nothing masked", every)
}
if slack := cap(out) - len(out); slack > len(out)/8+len(body)/16+64 {
t.Errorf("every %d: the masked body of %d bytes is held in %d", every, len(out), cap(out))
}
}
}