Files
magpie/internal/sessions/trace_lines_test.go
T
yetone bb5930b71b sessions: a trace poll reads a long line once, at its own size
TraceReader.Poll, which the OTel exporter runs each tick while session
export is on, read every appended line with bufio.ReadBytes through a
4 KiB reader. Every line was a copy of its own, and a line longer than
4 KiB (a function output, a pasted image in a Codex rollout) was gathered
in 4 KiB clones and then copied whole: about twice the line.

- Lines are read through the pooled line reader every other session
  reader uses (scanBuffer's size, 16 KiB to 1 MiB), with ReadSlice. A
  line the buffer holds is handed to the cursor in it; the cursor's
  parse copies what it keeps (encoding/json copies into RawMessage and
  strings), so nothing outlives the read.
- A longer line is gathered into one buffer made at its length, read
  ahead with lineLen as scanAt does, and reused for the next long line
  of the same poll. It is dropped when the poll returns.
- A line with no newline yet (half-written) is left for the next poll,
  as before. When the read ahead finds no end the gathering stops at
  once instead of growing the line first. A file rewritten between the
  read ahead and the read only grows the buffer again, never cuts a
  line.

Measured (TotalAlloc of one cold Poll, a fresh TraceReader over one
Codex rollout in a sandbox CODEX_HOME, 5 runs averaged, 3 runs each,
all equal to within 0.1%):

  rollout                                     bodies  before    after
  3 turns, images of 1/3/5 MiB (9.5 MB)       off     38.2 MB   28.7 MB
                                              on      57.3 MB   47.6 MB
  300 turns, 20 KB images (9.9 MB, 760 spans) off     35.6 MB   20.8 MB
                                              on      60.0 MB   45.1 MB

pprof (memprofilerate 1) puts ReadBytes at 18.7 MB per poll before and
the new read at 9.2 MB after, exactly the long lines read once. The rest
is the cursor's own parse (RawMessage copies of payload and content),
which this change leaves alone.

Tests (internal/sessions/trace_lines_test.go):
- TestNextTraceLineReadsWhatReadBytesRead: lines and end offset equal
  ReadBytes' for long lines (1/3/5 MiB, past the 1 MiB buffer), a line
  of the buffer's size, empty lines, CRLF, a short and a long unended
  last line, no line yet, an empty file; from 0 and from the first
  line's end.
- TestNextTraceLineWaitsForALongLineToEnd: a 3 MiB line without its
  newline is not read, and is read whole once it has one.
- TestTracePollOfLongLinesIsUnchanged: the spans Poll exports (bodies
  off and on) from a rollout with 3 and 2 MiB images, written in three
  parts that end inside long lines, are reflect.DeepEqual to those a
  cursor fed the whole file's ReadBytes lines exports.
- TestTracePollReadsALongLineOnce: a poll of a 6 MiB reasoning line
  allocates at most 2.5 times the line (12.6-13.7 MB over -count=20).
  With Poll's ReadBytes loop put back by hand it is red 3 of 3: "a poll
  of a 6291589-byte line allocated 19025024 bytes, want at most
  15728972".

Run at this commit's tree on origin/main c84864ffc, macOS arm64, go1.26.8,
sandbox HOME: gofmt -l internal clean; go vet ./internal/... ok, and
GOOS=linux/windows go vet -tags nogui of sessions and usage ok;
go test -race -count=3 ./internal/sessions/ ok (512s); go test
-timeout 45m ./... exit 0, 65 packages ok, none failed. (On the older
base a9304efe0 the race run was red in TestManageReadsOnlyTheAgentsItShows,
TestOpenCodeSubagents and TestLongReadKeepsWhatItRead: test-only races
that 9afdeb89c and c84864ffc fixed on main.)
2026-10-21 02:44:22 +08:00

229 lines
8.9 KiB
Go

package sessions
import (
"bufio"
"fmt"
"io"
"math/rand"
"os"
"path/filepath"
"reflect"
"runtime"
"strings"
"testing"
"time"
"github.com/yetone/magpie/internal/testenv"
)
// readBytesLines is how TraceReader.Poll read a file before nextTraceLine:
// each whole line from off, its newline included, and where the lines end.
func readBytesLines(t *testing.T, p string, off int64) ([]string, int64) {
t.Helper()
f, err := os.Open(p)
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.Seek(off, io.SeekStart)
b := bufio.NewReader(f)
var out []string
for {
line, err := b.ReadBytes('\n')
if err != nil {
return out, off
}
off += int64(len(line))
out = append(out, string(line))
}
}
func nextTraceLines(t *testing.T, p string, off int64) ([]string, int64) {
t.Helper()
f, err := os.Open(p)
if err != nil {
t.Fatal(err)
}
defer f.Close()
f.Seek(off, io.SeekStart)
b, release := lineReader(f, scanBuffer(f, off))
defer release()
var out []string
var long []byte
for {
var line []byte
line, long, err = nextTraceLine(b, f, off, long)
if err != nil {
return out, off
}
off += int64(len(line))
out = append(out, string(line))
}
}
// A trace file's lines come out of nextTraceLine as they came out of
// ReadBytes: lines longer than the read buffer, one exactly its size,
// empty ones, CRLF, and a last line not yet ended, short or long, which
// is left for the next poll.
func TestNextTraceLineReadsWhatReadBytesRead(t *testing.T) {
r := rand.New(rand.NewSource(4))
long := func(n int) string {
b := make([]byte, n)
for i := range b {
b[i] = byte('a' + r.Intn(26))
}
return `{"type":"x","data":"` + string(b) + `"}`
}
for name, body := range map[string]string{
"long lines": long(3<<20) + "\n" + `{"a":1}` + "\n" + long(1<<20) + "\n" + long(5<<20) + "\n",
"buffer's size": long(1<<20-len(`{"type":"x","data":""}`)-1) + "\n" + long(1<<20) + "\n{}\n",
"empty lines": "\n\n{}\n\n" + long(2<<20) + "\n\n",
"crlf": "{}\r\n" + long(2<<20) + "\r\n",
"short unended": long(2<<20) + "\n{\"a\":",
"long unended": "{}\n" + long(3<<20),
"no lines yet": long(2 << 20),
"nothing at all": "",
} {
t.Run(name, func(t *testing.T) {
p := filepath.Join(t.TempDir(), "rollout.jsonl")
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
t.Fatal(err)
}
for _, off := range []int64{0, int64(strings.IndexByte(body, '\n') + 1)} {
want, wantEnd := readBytesLines(t, p, off)
got, gotEnd := nextTraceLines(t, p, off)
if gotEnd != wantEnd || !reflect.DeepEqual(got, want) {
t.Fatalf("from %d: %d lines ending at %d, want %d ending at %d", off, len(got), gotEnd, len(want), wantEnd)
}
}
})
}
}
// A line still being written is not read until its newline is there,
// however long it is, and is then read whole.
func TestNextTraceLineWaitsForALongLineToEnd(t *testing.T) {
p := filepath.Join(t.TempDir(), "rollout.jsonl")
line := `{"type":"x","data":"` + strings.Repeat("y", 3<<20) + `"}`
os.WriteFile(p, []byte("{}\n"+line), 0o600)
if got, end := nextTraceLines(t, p, 0); len(got) != 1 || end != 3 {
t.Fatalf("read %d lines to %d before the long one ended, want 1 to 3", len(got), end)
}
f, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0o600)
f.WriteString("\n")
f.Close()
if got, end := nextTraceLines(t, p, 3); len(got) != 1 || got[0] != line+"\n" || end != int64(4+len(line)) {
t.Fatalf("the ended long line read as %d lines to %d", len(got), end)
}
}
// pollEnv is a home with nothing in it but Codex's sessions, under codex.
func pollEnv(t *testing.T) (codex string) {
testenv.SetHome(t, t.TempDir())
t.Setenv("XDG_DATA_HOME", t.TempDir())
t.Setenv("CLAUDE_CONFIG_DIR", t.TempDir())
t.Setenv("OPENCODE_DB", "")
t.Setenv("GEMINI_CLI_HOME", t.TempDir())
t.Setenv("PI_CODING_AGENT_DIR", t.TempDir())
t.Setenv("PI_CODING_AGENT_SESSION_DIR", "")
codex = t.TempDir()
t.Setenv("CODEX_HOME", codex)
return codex
}
// imageTurns is a Codex rollout whose turns each begin with a user message
// carrying a pasted image of the size given, as the Codex CLI writes one.
func imageTurns(start time.Time, images []int) string {
r := rand.New(rand.NewSource(3))
const b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
ts := func(i int) string { return start.Add(time.Duration(i) * time.Millisecond).Format(time.RFC3339Nano) }
var b strings.Builder
b.WriteString(`{"timestamp":"` + ts(0) + `","type":"session_meta","payload":{"id":"01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd","cwd":"/Users/me/work/app","originator":"codex_cli_rs","cli_version":"0.99.0"}}` + "\n")
for i, n := range images {
img := make([]byte, n)
for k := range img {
img[k] = b64[r.Intn(64)]
}
fmt.Fprintf(&b, `{"timestamp":%q,"type":"turn_context","payload":{"turn_id":"turn_%d","cwd":"/Users/me/work/app","model":"gpt-5.5","effort":"medium"}}`+"\n", ts(10*i+1), i)
fmt.Fprintf(&b, `{"timestamp":%q,"type":"event_msg","payload":{"type":"task_started","turn_id":"turn_%d"}}`+"\n", ts(10*i+2), i)
fmt.Fprintf(&b, `{"timestamp":%q,"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"look"},{"type":"input_image","image_url":"data:image/png;base64,%s"}]}}`+"\n", ts(10*i+3), img)
b.WriteString("\n")
fmt.Fprintf(&b, `{"timestamp":%q,"type":"response_item","payload":{"type":"function_call","name":"shell","arguments":"{}","call_id":"call_%d"}}`+"\n", ts(10*i+4), i)
fmt.Fprintf(&b, `{"timestamp":%q,"type":"response_item","payload":{"type":"function_call_output","call_id":"call_%d","output":%q}}`+"\n", ts(10*i+5), i, strings.Repeat("out ", 3000))
fmt.Fprintf(&b, `{"timestamp":%q,"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}}`+"\n", ts(10*i+6))
fmt.Fprintf(&b, `{"timestamp":%q,"type":"event_msg","payload":{"type":"task_complete","turn_id":"turn_%d","last_agent_message":"done"}}`+"\n", ts(10*i+7), i)
}
return b.String()
}
// What Poll exports from a rollout with long lines, read across polls as
// it is written (a long line cut off mid-way at one poll's end), is what a
// cursor fed the same file's lines through ReadBytes exports.
func TestTracePollOfLongLinesIsUnchanged(t *testing.T) {
codex := pollEnv(t)
dir := filepath.Join(codex, "sessions", "2026", "10", "21")
os.MkdirAll(dir, 0o700)
p := filepath.Join(dir, "rollout-2026-10-21T10-00-00-01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd.jsonl")
since := time.Now().Add(-time.Hour)
body := imageTurns(time.Now().UTC(), []int{3 << 20, 100, 2 << 20})
for _, bodies := range []bool{false, true} {
os.WriteFile(p, nil, 0o600)
r := NewTraceReader(since)
var got []TraceSpan
// written in three parts, the first two ending inside a long line
for _, cut := range []int{len(body) / 4, len(body) * 3 / 4, len(body)} {
f, _ := os.OpenFile(p, os.O_APPEND|os.O_WRONLY, 0o600)
fi, _ := f.Stat()
f.WriteString(body[fi.Size():cut])
f.Close()
got = append(got, r.Poll(bodies)...)
}
c := newTraceCursor(file{path: p, agent: "codex"})
var want []TraceSpan
lines, _ := readBytesLines(t, p, 0)
for _, line := range lines {
for _, s := range c.line([]byte(line), bodies) {
if !s.End.Before(since) && !s.Start.IsZero() && !s.End.Before(s.Start) && s.Session != "" {
want = append(want, s)
}
}
}
if len(want) == 0 || !reflect.DeepEqual(got, want) {
t.Fatalf("bodies=%v: Poll exported %d spans, ReadBytes' lines %d (or they differ)", bodies, len(got), len(want))
}
}
}
// A poll reads a long line into one buffer of the line's own size. Read by
// ReadBytes, it was gathered in 4 KiB pieces and then copied whole, twice
// the line, and a poll of a rollout with pasted images allocated about 4
// times what it read with bodies off.
func TestTracePollReadsALongLineOnce(t *testing.T) {
if raceOn {
t.Skip("-race lets a pool's buffers go")
}
codex := pollEnv(t)
dir := filepath.Join(codex, "sessions", "2026", "10", "21")
os.MkdirAll(dir, 0o700)
p := filepath.Join(dir, "rollout-2026-10-21T10-00-00-01a0bdc9-b5fd-7e63-9658-68bc8dce5ecd.jsonl")
// a reasoning item's encrypted content, which the parse passes over
// without a copy, so what is left is the payload's copy and the read
line := fmt.Sprintf(`{"timestamp":%q,"type":"response_item","payload":{"type":"reasoning","summary":[],"encrypted_content":"%s"}}`, time.Now().UTC().Format(time.RFC3339Nano), strings.Repeat("Z", 6<<20))
os.WriteFile(p, []byte(imageTurns(time.Now().UTC(), nil)+line+"\n"), 0o600)
since := time.Now().Add(-time.Hour)
poll := func() { NewTraceReader(since).Poll(false) }
poll()
var a, b runtime.MemStats
runtime.GC()
runtime.ReadMemStats(&a)
poll()
runtime.ReadMemStats(&b)
got := b.TotalAlloc - a.TotalAlloc
t.Logf("a poll of a %d-byte line allocated %d bytes", len(line), got)
// the line once, its payload once, and room for the rest; through
// ReadBytes it was the line three times
if most := uint64(len(line)) * 5 / 2; got > most {
t.Fatalf("a poll of a %d-byte line allocated %d bytes, want at most %d", len(line), got, most)
}
}