gateway: a conversation's tail is made in a slice of its size, so -race counts one copy (#4004)

TestTailOfReadsInPlace was red in both Race jobs at ca499953e (run
40696645744): 2686576 bytes allocated for a 1314661 byte tail, over its
want+body/4 budget. Under -race bytes.Buffer.Grow's append-make pattern
allocates the slice twice (a -memprofilerate 1 profile on mote:
bytes.growSlice 2576kB, two copies of the tail); without -race it is one
(1367680 bytes). tailOf now appends into make([]byte, 0, n), one
allocation either way. Same bytes out.

Run on mote (M5 Pro) at this tree:
- old code, -race -count=8: red 8 of 8, 2686576 bytes each time
- go test -race -count=5 of tool_loop_test.go's six tests: ok
- the same without -race, -count=5: ok
- go vet ./internal/gateway for darwin, linux, windows: ok
Not run: the full suite (one function body changed, its tests above).
This commit is contained in:
yetone
2026-10-28 22:09:53 +08:00
parent a8c71f1987
commit 4ca64c21b2
+9 -9
View File
@@ -110,19 +110,19 @@ func tailOf(from provider.Protocol, body []byte) []byte {
if len(items) <= tailItems {
return body
}
var b bytes.Buffer
b.Grow(len(body) - list.Index - len(list.Raw) + items[len(items)-1].Index + len(items[len(items)-1].Raw) - items[len(items)-tailItems].Index + list.Index + 2)
b.Write(body[:list.Index])
b.WriteByte('[')
// a slice made to its size, not a bytes.Buffer: under -race the
// Buffer's Grow allocates its slice twice
b := make([]byte, 0, len(body)-list.Index-len(list.Raw)+items[len(items)-1].Index+len(items[len(items)-1].Raw)-items[len(items)-tailItems].Index+list.Index+2)
b = append(b, body[:list.Index]...)
b = append(b, '[')
for i, v := range items[len(items)-tailItems:] {
if i > 0 {
b.WriteByte(',')
b = append(b, ',')
}
b.WriteString(v.Raw)
b = append(b, v.Raw...)
}
b.WriteByte(']')
b.Write(body[list.Index+len(list.Raw):])
return b.Bytes()
b = append(b, ']')
return append(b, body[list.Index+len(list.Raw):]...)
}
// toolLoop is a conversation's newest exchange and how many turns in a row