sessions: a Codex rollout with nothing to change is only read, never written out again (#4735)

portRollout and repairLineages ran every rollout they looked at through
editRollout, which opened a temp file (and a zstd encoder for a packed
one) and wrote the whole rollout out before it could know whether any
line changed; a rollout with nothing to change was then thrown away. On
every pass over ~/.codex/sessions that was a full rewrite per file.

editRollout now reads first (eachEditedLine with no writer, which stops
at the first line that changes) and only then makes the temp file and the
encoder. If the second, writing pass changes nothing the file moved
between the reads and is held (errRolloutHeld), as a stat change already
was. The edit is built afresh per pass, so per-file state (portRollout's
"ours") starts over. Lines are read with ReadSlice into a 64KB buffer; a
longer line is gathered whole. The encoder is closed on every early
return now; it was left open before.

Run on mote (macOS 27.2), 10 rollouts of 4MB each with nothing to change:
- plain: 686ms -> 106ms per pass, 46MB -> 0.66MB allocated,
  232k -> 120 allocations.
- zst: 127ms -> 120ms per pass, 237MB -> 0.67MB allocated; the process's
  CPU (with the same setup) 2.55s -> 1.43s, sys 0.6s -> 0.17s.
- TestPortCodexRolloutsOnlyReadsWhatHasNothingToChange, plain and zst,
  with a 300KB line: nothing written out and the bytes the same; then
  with one line to change it is rewritten, the long line kept. With the
  reading pass taken out by hand it fails: "1 rollouts written out for
  nothing".
- TestPortCodex* and TestPortLine*: ok.
- go test ./internal/sessions ./internal/agent: ok (36.7s, 228.9s).
- GOOS=windows and GOOS=linux go vet of both: ok. gofmt -l: clean.

Not tried: a real ~/.codex/sessions pass in the app; the numbers are the
benchmark's, not a sample of the reporter's machine.
This commit is contained in:
yetone
2026-11-01 17:41:02 +08:00
parent 85fcac4a47
commit bd5152ce3b
2 changed files with 140 additions and 55 deletions
+102 -55
View File
@@ -14,6 +14,7 @@ import (
"regexp"
"strconv"
"strings"
"sync/atomic"
"time"
"github.com/klauspost/compress/zstd"
@@ -289,27 +290,32 @@ func unsealedReasoning(line []byte) bool {
// compaction item (or, left, a reasoning item OpenAI didn't seal), and
// says whether it did.
func portRollout(ctx context.Context, home, path string, left bool) (bool, error) {
ours := true // begun on OpenAI's provider or magpie's
return editRollout(ctx, home, path, func(line []byte, paged bool) ([]byte, bool) {
if isMetaLine(line) {
switch gjson.GetBytes(line, "payload.model_provider").String() {
case "", "openai", "magpie":
default:
ours = false
return editRollout(ctx, home, path, func() func(line []byte, paged bool) ([]byte, bool) {
ours := true // begun on OpenAI's provider or magpie's
return func(line []byte, paged bool) ([]byte, bool) {
if isMetaLine(line) {
switch gjson.GetBytes(line, "payload.model_provider").String() {
case "", "openai", "magpie":
default:
ours = false
}
}
out, ok := portLineAs(line, left && ours)
if ok {
out, ok = fitLine(line, out, paged)
}
return out, ok
}
out, ok := portLineAs(line, left && ours)
if ok {
out, ok = fitLine(line, out, paged)
}
return out, ok
})
}
// editRollout writes the rollout at path with each line as edit gives it,
// if edit changed one, and says whether it did; paged is whether the
// rollout's history is paginated.
func editRollout(ctx context.Context, home, path string, edit func(line []byte, paged bool) ([]byte, bool)) (bool, error) {
// editRollout writes the rollout at path with each line as an edit from
// edits gives it, if one changed a line, and says whether it did; paged is
// whether the rollout's history is paginated. The rollout is read once to
// see whether a line changes, and only then again to write it: most
// rollouts a pass looks at have nothing to change, and writing each one
// out, compressed for a .zst, cost a pass more than reading it (#4735).
func editRollout(ctx context.Context, home, path string, edits func() func(line []byte, paged bool) ([]byte, bool)) (bool, error) {
thread := codexThreadOf(filepath.Base(path))
if thread == "" {
return false, nil
@@ -318,24 +324,26 @@ func editRollout(ctx context.Context, home, path string, edit func(line []byte,
if err != nil {
return false, err
}
in, err := openLines(path)
if err != nil {
if changed, err := eachEditedLine(ctx, path, edits(), nil); err != nil || !changed {
return false, err
}
defer in.Close()
tmp, err := os.CreateTemp(filepath.Dir(path), ".magpie-"+filepath.Base(path)+"-*")
if err != nil {
return false, err
}
rolloutWrites.Add(1)
done := false
var z *zstd.Encoder
defer func() {
if !done {
if z != nil {
z.Close()
}
tmp.Close()
os.Remove(tmp.Name())
}
}()
var w io.Writer = tmp
var z *zstd.Encoder
if packed(path) {
if z, err = zstd.NewWriter(tmp); err != nil {
return false, err
@@ -343,39 +351,20 @@ func editRollout(ctx context.Context, home, path string, edit func(line []byte,
w = z
}
bw := bufio.NewWriterSize(w, 64<<10)
br := bufio.NewReaderSize(in, 64<<10)
changed := false
paged, metaSeen := false, false
for n := 0; ; n++ {
if n%4096 == 0 && ctx.Err() != nil {
return false, ctx.Err()
}
line, err := br.ReadBytes('\n')
if len(line) > 0 {
if !metaSeen && isMetaLine(line) {
paged, metaSeen = paginated(line), true
}
out, ok := edit(line, paged)
changed = changed || ok
if _, werr := bw.Write(out); werr != nil {
return false, werr
}
}
if err == io.EOF {
break
}
if err != nil {
return false, err
}
changed, err := eachEditedLine(ctx, path, edits(), bw)
if err != nil {
return false, err
}
if !changed {
return false, nil
return false, errRolloutHeld // it changed between the reads
}
if err := bw.Flush(); err != nil {
return false, err
}
if z != nil {
if err := z.Close(); err != nil {
err := z.Close()
z = nil
if err != nil {
return false, err
}
}
@@ -388,7 +377,6 @@ func editRollout(ctx context.Context, home, path string, edit func(line []byte,
if err := tmp.Close(); err != nil {
return false, err
}
in.Close()
os.Chtimes(tmp.Name(), fi.ModTime(), fi.ModTime())
// published as Codex publishes a compressed rollout: under the
@@ -421,6 +409,63 @@ func editRollout(ctx context.Context, home, path string, edit func(line []byte,
return true, nil
}
// rolloutWrites counts the rollouts editRollout began to write out.
var rolloutWrites atomic.Int64
// eachEditedLine reads the rollout at path through edit, writing each
// line as edit gives it to w (when there is one), and says whether edit
// changed a line.
func eachEditedLine(ctx context.Context, path string, edit func(line []byte, paged bool) ([]byte, bool), w io.Writer) (bool, error) {
in, err := openLines(path)
if err != nil {
return false, err
}
defer in.Close()
br := bufio.NewReaderSize(in, 64<<10)
changed := false
paged, metaSeen := false, false
for n := 0; ; n++ {
if n%4096 == 0 && ctx.Err() != nil {
return false, ctx.Err()
}
line, err := br.ReadSlice('\n')
if errors.Is(err, bufio.ErrBufferFull) {
var long []byte
long, err = readLongLine(br, line)
line = long
}
if len(line) > 0 {
if !metaSeen && isMetaLine(line) {
paged, metaSeen = paginated(line), true
}
out, ok := edit(line, paged)
changed = changed || ok
if w == nil && changed {
return true, nil
}
if w != nil {
if _, werr := w.Write(out); werr != nil {
return false, werr
}
}
}
if err == io.EOF {
return changed, nil
}
if err != nil {
return false, err
}
}
}
// readLongLine is the rest of a line longer than br's buffer, after its
// start: ReadSlice's, which the next read writes over, so it is copied.
func readLongLine(br *bufio.Reader, start []byte) ([]byte, error) {
line := append([]byte{}, start...)
rest, err := br.ReadBytes('\n')
return append(line, rest...), err
}
// Codex keeps places in a rollout by byte: a fork's or a revert's
// rollout names where its parent's history ends (session_meta's
// history_base.end_byte_offset), and Codex's state database where each
@@ -513,15 +558,17 @@ func repairLineages(ctx context.Context, home string) (fixed []string, whole boo
if !ok || at == base.Get("end_byte_offset").Int() {
continue
}
changed, err := editRollout(ctx, home, p, func(line []byte, paged bool) ([]byte, bool) {
r := gjson.GetBytes(line, "payload.history_base.end_byte_offset")
if !isMetaLine(line) || r.Index <= 0 || r.Type != gjson.Number {
return line, false
changed, err := editRollout(ctx, home, p, func() func(line []byte, paged bool) ([]byte, bool) {
return func(line []byte, paged bool) ([]byte, bool) {
r := gjson.GetBytes(line, "payload.history_base.end_byte_offset")
if !isMetaLine(line) || r.Index <= 0 || r.Type != gjson.Number {
return line, false
}
out := append([]byte{}, line[:r.Index]...)
out = strconv.AppendInt(out, at, 10)
out = append(out, line[r.Index+len(r.Raw):]...)
return fitLine(line, out, true)
}
out := append([]byte{}, line[:r.Index]...)
out = strconv.AppendInt(out, at, 10)
out = append(out, line[r.Index+len(r.Raw):]...)
return fitLine(line, out, true)
})
switch {
case err != nil:
+38
View File
@@ -175,6 +175,44 @@ func TestPortCodexRollouts(t *testing.T) {
}
}
// #4735: a pass over a rollout with nothing of magpie's in it only reads
// it. It wrote each one out again, compressed for a .zst, and threw that
// away, which cost a pass more than the read. A line longer than the read
// buffer is read whole, and one of magpie's after it is still written.
func TestPortCodexRolloutsOnlyReadsWhatHasNothingToChange(t *testing.T) {
long := `{"timestamp":"2026-10-20T07:06:00.000Z","type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"` + strings.Repeat("x", 300<<10) + `"}]}}`
for _, zst := range []bool{false, true} {
t.Run(map[bool]string{false: "plain", true: "zst"}[zst], func(t *testing.T) {
all := portRolloutLines("Progress: done.")
lines := []string{all[0], all[1], long, all[5], all[6]}
home, path := portHome(t, lines, zst)
before, _ := os.ReadFile(path)
was := rolloutWrites.Load()
res, err := PortCodexRollouts(context.Background(), home)
if err != nil || !res.Done || len(res.Rewritten) != 0 {
t.Fatalf("pass: %+v, %v", res, err)
}
if n := rolloutWrites.Load() - was; n != 0 {
t.Errorf("%d rollouts written out for nothing", n)
}
if after, _ := os.ReadFile(path); !bytes.Equal(after, before) {
t.Error("the rollout changed")
}
lines = []string{all[0], all[1], long, all[2], all[6]}
home, path = portHome(t, lines, zst)
res, err = PortCodexRollouts(context.Background(), home)
if err != nil || len(res.Rewritten) != 1 {
t.Fatalf("pass: %+v, %v", res, err)
}
got := readRollout(t, path)
if len(got) != len(lines) || got[2] != long || got[4] != lines[4] || strings.Contains(got[3], codexsummary.Mark) {
t.Errorf("rewritten: %d lines, long kept %v, item %.200s", len(got), len(got) > 2 && got[2] == long, got[min(3, len(got)-1)])
}
})
}
}
// A rollout whose thread a Codex has open (its writer lock held) is never
// written under it: it is left as it was, kept for a later pass, and
// written once the Codex lets it go. A Codex home without