From 4ca64c21b22f599c0404280fe9d6ef4726c56510 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 28 Oct 2026 22:09:39 +0800 Subject: [PATCH] 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). --- internal/gateway/tool_loop.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/internal/gateway/tool_loop.go b/internal/gateway/tool_loop.go index e29e0b47a..cc95f03f8 100644 --- a/internal/gateway/tool_loop.go +++ b/internal/gateway/tool_loop.go @@ -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