sessions: a Codex rollout magpie rewrites keeps every line where it was

xybio (Discord #feedback): the Codex app often wouldn't reopen recent
threads: "invalid paginated history lineage for <id>: cutoff byte offset
is past the source rollout". Codex 0.162 keeps a fork's place in its
parent by byte (session_meta.history_base.end_byte_offset, checked by
rollout_lineage.rs validate_cutoff_bounds), and its state database keeps
turns and how far it has read by byte too. PortCodexRollouts (since
4896fc3ba, 10-21) wrote magpie's compaction item as Codex's summary
message, and since 79c8667c9 dropped Claude's sealed reasoning: both
shorter lines, so a parent shrank and every fork made before the pass
named a byte past its end.

Now every rewritten line keeps its length (fitLine): a shorter one is
padded with spaces after its JSON, which serde_json skips; a longer one
(a short summary under Codex's prefix) is left as it was in a paginated
rollout, and written as before in a legacy one, where Codex keeps no
place by byte. MoveCodexProvider, the sibling that rewrites session_meta,
pads the same way and refuses a longer provider id for a paginated
rollout. Forks already broken are repaired once per Codex home
(repairLineages): every line kept its count, and Codex names each line's
ordinal, so a fork's end_byte_offset is set again to where its parent's
line end_ordinal_exclusive-1 ends now, in a first line kept as long.

Run, at a47596ea6 plus this change:
- go test -count=1 ./internal/sessions/ ./internal/codexsummary/: ok;
  ./internal/agent/ -run 'Codex|Port|Move|Session': ok.
- gofmt -l internal/ clean; go vet ./internal/sessions/ ./internal/agent/,
  GOOS=windows and GOOS=linux go vet ./internal/sessions/: clean.
- Real, Codex 0.162.1 in a sandbox CODEX_HOME against a local mock
  Responses server that returns a magpie-claude1: reasoning item: codex
  exec made a paginated thread (50877 bytes), app-server thread/fork
  forked it, then a port pass. Old code: the parent went to 70570 bytes
  from 82912 and thread/resume and thread/read of the fork gave the
  reporter's exact error. New code: the parent kept 82912 bytes with no
  magpie-claude1: left, the fork resumed and read, the parent resumed,
  and codex exec resume ran a turn on the fork. A new-code pass over the
  old-code home repaired the fork (82912 -> 70570 in its history_base),
  after which it resumed and read.

Broken by hand:
- fitLine returning the rewrite as it is:
  TestPortCodexRolloutsKeepsBytePlaces red ("lines end at [... 11329],
  were at [... 14362]", the fork's offset past the end),
  TestPortCodexRolloutsLongerLine and TestMoveCodexProviderKeepsBytePlaces
  red.
- repairLineages a no-op: TestPortCodexRolloutsRepairsForks red.

Not tried: the Codex desktop app itself (the app-server it runs was);
a .zst parent against real Codex (the Go tests cover zst ports); Codex in
WSL, which the pass skips as before. The state database's turn offsets
for a parent already shrunk are left as they are; Codex 0.162.1 resumed
and forked such a parent in the sandbox.
This commit is contained in:
yetone
2026-10-27 23:33:26 +08:00
parent 6c063ac1b2
commit 67b12956ac
5 changed files with 397 additions and 3 deletions
File diff suppressed because one or more lines are too long
+198 -2
View File
@@ -12,10 +12,12 @@ import (
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/klauspost/compress/zstd"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexsummary"
@@ -59,6 +61,9 @@ type codexPortState struct {
type codexPortHome struct {
Since time.Time `json:"since"`
Pending []string `json:"pending,omitempty"`
// Lineage: every fork's place in its parent was looked at once
// (repairLineages), after magpie before it moved them
Lineage bool `json:"lineage,omitempty"`
}
// codexPortFirst is the first day magpie wrote a compaction item of its
@@ -75,6 +80,7 @@ func codexPortPath() string { return filepath.Join(settings.Dir(), "codex-portab
type CodexPort struct {
Rewritten []string // rollouts written portable
Held []string // rollouts with magpie's item a Codex holds, left for a later pass
Repaired []string // forks whose place in their parent was set again (repairLineages)
Done bool // every rollout due was looked at
}
@@ -165,7 +171,12 @@ func PortCodexRollouts(ctx context.Context, home string) (CodexPort, error) {
break
}
}
now := codexPortHome{Since: was.Since, Pending: pending}
now := codexPortHome{Since: was.Since, Pending: pending, Lineage: was.Lineage}
if res.Done && !was.Lineage {
fixed, whole := repairLineages(ctx, home)
res.Repaired = fixed
now.Lineage = whole
}
if res.Done {
now.Since = start
} else {
@@ -217,6 +228,19 @@ var claudeMark = []byte(claudeseal.Mark)
// portRollout writes the rollout at path portable, if it has magpie's
// compaction item, and says whether it did.
func portRollout(ctx context.Context, home, path string) (bool, error) {
return editRollout(ctx, home, path, func(line []byte, paged bool) ([]byte, bool) {
out, ok := portLine(line)
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) {
thread := codexThreadOf(filepath.Base(path))
if thread == "" {
return false, nil
@@ -252,13 +276,17 @@ func portRollout(ctx context.Context, home, path string) (bool, error) {
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 {
out, ok := portLine(line)
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
@@ -324,6 +352,174 @@ func portRollout(ctx context.Context, home, path string) (bool, error) {
return true, nil
}
// 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
// turn starts and ends and how far it has read (thread_turns,
// thread_history_projection_state). A rewritten line that is shorter or
// longer moves every place after it, and a rollout that shrinks leaves
// them past its end: Codex then won't open the thread ("invalid paginated
// history lineage …: cutoff byte offset is past the source rollout",
// xybio on Discord). So a line magpie rewrites keeps its length: a
// shorter one is padded with spaces after its JSON, which Codex's reader
// (serde_json) skips, and a longer one, in a rollout whose history is
// paginated, is not written at all.
// isMetaLine says whether a rollout line is a session_meta.
func isMetaLine(line []byte) bool {
return bytes.Contains(line[:min(len(line), 1024)], cxMeta) && gjson.GetBytes(line, "type").String() == "session_meta"
}
// paginated says whether a session_meta line's rollout keeps its history
// paginated, the one whose places Codex keeps by byte.
func paginated(meta []byte) bool {
return gjson.GetBytes(meta, "payload.history_mode").String() == "paginated"
}
// fitLine is out, a rewrite of line, as long as line: padded with spaces
// after its JSON when it is shorter (spaces line had there are taken
// first). One that is longer is out as it is, unless paged: then it is
// line, and false.
func fitLine(line, out []byte, paged bool) ([]byte, bool) {
body := bytes.TrimRight(line, "\r\n")
end := line[len(body):]
nb := bytes.TrimRight(bytes.TrimRight(out, "\r\n"), " ")
if len(nb) > len(body) {
if paged {
return line, false
}
return out, true
}
fit := make([]byte, 0, len(line))
fit = append(fit, nb...)
fit = append(fit, bytes.Repeat([]byte{' '}, len(body)-len(nb))...)
return append(fit, end...), true
}
// A fork made before magpie kept a parent's lines whole names a byte in
// it that a shorter parent no longer ends a line at, or no longer has:
// Codex refuses to open it. Every line kept its place by count, though,
// and Codex names each line's ordinal, so repairLineages sets each such
// place again to where the parent's line before history_base's
// end_ordinal_exclusive ends now, in the fork's session_meta, which keeps
// its own length (fitLine). It says which forks it wrote, and whether it
// looked at every one (none held by a Codex, ctx not done).
func repairLineages(ctx context.Context, home string) (fixed []string, whole bool) {
rollouts := map[string]string{} // rollout id → its file
var all []string
for _, folder := range []string{"sessions", "archived_sessions"} {
filepath.WalkDir(filepath.Join(home, folder), func(p string, d fs.DirEntry, err error) error {
if err != nil || d.IsDir() || !d.Type().IsRegular() {
return nil
}
if id := codexRolloutID(d.Name()); id != "" {
rollouts[id] = p
all = append(all, p)
}
return nil
})
}
whole = true
known := map[string]map[int64]int64{} // a parent's ordinalEnds
for _, p := range all {
if ctx.Err() != nil {
return fixed, false
}
meta := firstLine(p)
base := gjson.GetBytes(meta, "payload.history_base")
if !isMetaLine(meta) || !paginated(meta) || !base.IsObject() {
continue
}
parent, ok := rollouts[strings.ToLower(base.Get("thread_id").String())]
n := base.Get("end_ordinal_exclusive").Int()
if !ok || n <= 0 {
continue
}
ends, seen := known[parent]
if !seen {
ends = ordinalEnds(parent)
known[parent] = ends
}
at, ok := ends[n-1]
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
}
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:
whole = false
if !errors.Is(err, errRolloutHeld) {
log.Printf("codex rollout %s: %v", p, err)
}
case changed:
fixed = append(fixed, p)
}
}
return fixed, whole
}
// codexRolloutID is the id a rollout's file name gives it: a later
// rollout of a thread's own, else its thread's.
func codexRolloutID(name string) string {
m := codexRolloutName.FindStringSubmatch(name)
if m == nil {
return ""
}
if i := strings.IndexByte(name, '_'); i > 0 {
return strings.ToLower(strings.TrimSuffix(strings.TrimSuffix(name[i+1:], zstSuffix), ".jsonl"))
}
return strings.ToLower(m[1])
}
// firstLine is a rollout's first line, "" when it can't be read.
func firstLine(path string) []byte {
r, err := openLines(path)
if err != nil {
return nil
}
defer r.Close()
line, _ := bufio.NewReaderSize(r, 64<<10).ReadBytes('\n')
return line
}
// ordinalEnds is where, in a rollout's lines, each line Codex numbered
// ends, its newline included, up to the first line without an ordinal
// (after which there is no telling).
func ordinalEnds(path string) map[int64]int64 {
ends := map[int64]int64{}
r, err := openLines(path)
if err != nil {
return ends
}
defer r.Close()
br := bufio.NewReaderSize(r, 64<<10)
var at int64
for {
line, err := br.ReadBytes('\n')
if len(line) == 0 || line[len(line)-1] != '\n' {
return ends
}
at += int64(len(line))
o := gjson.GetBytes(line, "ordinal")
if o.Type != gjson.Number {
return ends
}
ends[o.Int()] = at
if err != nil {
return ends
}
}
}
// portLine is a rollout line with each of magpie's compaction items in it
// written as the message it stands for; any other line as it is, byte for
// byte. One of magpie's items whose summary can't be read is left out of
+152
View File
@@ -7,6 +7,7 @@ import (
"os"
"path/filepath"
"reflect"
"strconv"
"strings"
"testing"
"time"
@@ -263,3 +264,154 @@ func TestPortLineDropsClaudeBlocks(t *testing.T) {
}
}
}
// lineEnds is where each line of a rollout ends, newline included: the
// places Codex keeps by byte (history_base.end_byte_offset, the state
// database's turn and projection offsets).
func lineEnds(t *testing.T, path string) []int {
t.Helper()
in, err := openLines(path)
if err != nil {
t.Fatal(err)
}
defer in.Close()
var buf bytes.Buffer
buf.ReadFrom(in)
var ends []int
for i, c := range buf.Bytes() {
if c == '\n' {
ends = append(ends, i+1)
}
}
return ends
}
// xybio (Discord): the Codex app wouldn't reopen threads ("invalid
// paginated history lineage for …: cutoff byte offset is past the source
// rollout"). A fork or a revert names the byte its parent's history ends
// at (session_meta.history_base), and Codex's state database keeps turns
// and how far it has read by byte too; a ported line, a summary message
// shorter than magpie's base64 item, made the parent shorter, so every
// such place moved or went past its end. A rollout written portable keeps
// every line where it was, and a fork's place in it stays a line's end.
func TestPortCodexRolloutsKeepsBytePlaces(t *testing.T) {
for _, zst := range []bool{false, true} {
t.Run(map[bool]string{false: "plain", true: "zst"}[zst], func(t *testing.T) {
summary := strings.Repeat("Progress: build fixed in internal/x; next the suite. ", 80)
lines := portRolloutLines(summary)
lines[0] = strings.Replace(lines[0], `"model_provider":"openai"`, `"model_provider":"openai","history_mode":"paginated"`, 1)
sealed := claudeseal.Seal([]byte(`{"type":"thinking","thinking":"hm","signature":"` + strings.Repeat("s", 600) + `"}`))
lines = append(lines, `{"timestamp":"2026-10-20T09:00:06.000Z","type":"response_item","payload":{"type":"reasoning","summary":[{"type":"summary_text","text":"hm"}],"encrypted_content":"`+sealed+`"}}`)
home, path := portHome(t, lines, zst)
before := lineEnds(t, path)
// a fork of the thread made at its end, as the Codex app makes
// one from where it has read to
child := "01a1430d-e3a9-7a72-a466-071d2e3dd46b"
cpath := filepath.Join(filepath.Dir(path), "rollout-2026-10-20T18-00-00-"+child+".jsonl")
meta := `{"timestamp":"2026-10-20T10:00:00.000Z","type":"session_meta","payload":{"id":"` + child + `","history_mode":"paginated","history_base":{"thread_id":"` + portThread + `","end_ordinal_exclusive":` + strconv.Itoa(len(lines)) + `,"end_byte_offset":` + strconv.Itoa(before[len(before)-1]) + `}}}` + "\n"
if err := os.WriteFile(cpath, []byte(meta), 0o600); err != nil {
t.Fatal(err)
}
res, err := PortCodexRollouts(context.Background(), home)
if err != nil || len(res.Rewritten) != 1 || res.Rewritten[0] != path {
t.Fatalf("pass: %+v, %v", res, err)
}
if after := lineEnds(t, path); !reflect.DeepEqual(after, before) {
t.Fatalf("lines end at %v, were at %v", after, before)
}
got := readRollout(t, path)
want, _ := json.Marshal(codexsummary.UserMessage(codexsummary.Prefix + "\n" + summary))
var wantAny any
json.Unmarshal(want, &wantAny)
if p := decode(t, got[2])["payload"]; !reflect.DeepEqual(p, wantAny) {
t.Errorf("not written portable: %s", got[2])
}
for i, l := range got {
decode(t, l) // padded lines still read as JSON
if i != 1 && (strings.Contains(l, codexsummary.Mark) || strings.Contains(l, claudeseal.Mark)) {
t.Errorf("line %d still has magpie's item: %.200s", i, l)
}
}
if b, _ := os.ReadFile(cpath); string(b) != meta {
t.Error("the fork's rollout changed")
}
})
}
}
// A line whose portable form is longer (a short summary, under Codex's
// prefix) can't keep its length: in a paginated rollout it is left as it
// was, never moving what follows; in a legacy one, where Codex keeps no
// place by byte, it is written as before.
func TestPortCodexRolloutsLongerLine(t *testing.T) {
lines := portRolloutLines("short")
lines[0] = strings.Replace(lines[0], `"model_provider":"openai"`, `"model_provider":"openai","history_mode":"paginated"`, 1)
home, path := portHome(t, lines, false)
before := lineEnds(t, path)
if _, err := PortCodexRollouts(context.Background(), home); err != nil {
t.Fatal(err)
}
if after := lineEnds(t, path); !reflect.DeepEqual(after, before) {
t.Fatalf("lines end at %v, were at %v", after, before)
}
got := readRollout(t, path)
if got[2] != lines[2] {
t.Errorf("a longer line was written: %s", got[2])
}
if strings.Contains(got[4], "magpie1:%%%") {
t.Errorf("the shorter one wasn't: %s", got[4])
}
}
// A fork made before magpie kept its parent's lines whole names a byte
// the shorter parent doesn't end a line at, or doesn't have (xybio's
// thread). The pass after sets it again, once, from the ordinal the fork
// names, keeping the fork's first line as long as it was; a fork whose
// place is right keeps its bytes.
func TestPortCodexRolloutsRepairsForks(t *testing.T) {
parent := []string{
`{"timestamp":"2026-10-20T07:05:20.118Z","ordinal":0,"type":"session_meta","payload":{"id":"` + portThread + `","history_mode":"paginated","model_provider":"openai"}}`,
`{"timestamp":"2026-10-20T07:05:31.002Z","ordinal":1,"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"fix it"}]}}`,
`{"timestamp":"2026-10-20T07:05:40.002Z","ordinal":2,"type":"response_item","payload":{"type":"message","role":"assistant","content":[{"type":"output_text","text":"done"}]}}`,
}
home, path := portHome(t, parent, false)
ends := lineEnds(t, path)
dir := filepath.Dir(path)
fork := func(id string, ord, at int) string {
p := filepath.Join(dir, "rollout-2026-10-20T18-00-00-"+id+".jsonl")
b := `{"timestamp":"2026-10-20T10:00:00.000Z","ordinal":` + strconv.Itoa(ord) + `,"type":"session_meta","payload":{"id":"` + id + `","history_mode":"paginated","history_base":{"thread_id":"` + portThread + `","end_ordinal_exclusive":` + strconv.Itoa(ord) + `,"end_byte_offset":` + strconv.Itoa(at) + `}}}` + "\n" +
`{"timestamp":"2026-10-20T10:00:01.000Z","ordinal":` + strconv.Itoa(ord+1) + `,"type":"event_msg","payload":{"type":"task_started"}}` + "\n"
if err := os.WriteFile(p, []byte(b), 0o600); err != nil {
t.Fatal(err)
}
return p
}
// made when the parent was longer, at its end then
broken := fork("01a1430d-e3a9-7a72-a466-071d2e3dd46b", 3, 14362)
right := fork("01a1430d-ffff-7a72-a466-071d2e3dd46b", 2, ends[1])
was, _ := os.ReadFile(broken)
rightWas, _ := os.ReadFile(right)
res, err := PortCodexRollouts(context.Background(), home)
if err != nil || len(res.Repaired) != 1 || res.Repaired[0] != broken {
t.Fatalf("pass: %+v, %v", res, err)
}
now, _ := os.ReadFile(broken)
if len(now) != len(was) {
t.Fatalf("%d bytes, was %d", len(now), len(was))
}
first := decode(t, readRollout(t, broken)[0])
if at := first["payload"].(map[string]any)["history_base"].(map[string]any)["end_byte_offset"]; at != float64(ends[2]) {
t.Errorf("end_byte_offset %v, want %d", at, ends[2])
}
if b, _ := os.ReadFile(right); !bytes.Equal(b, rightWas) {
t.Error("a fork whose place was right changed")
}
// looked at once
os.WriteFile(broken, was, 0o600)
if res, err := PortCodexRollouts(context.Background(), home); err != nil || len(res.Repaired) != 0 {
t.Fatalf("second pass: %+v, %v", res, err)
}
}
+7
View File
@@ -525,6 +525,13 @@ func rewriteCodexProvider(path, to string) (bool, error) {
line, err := br.ReadBytes('\n')
if len(line) > 0 {
out, ok := setMetaProvider(line, to)
if ok {
// a session_meta names its own history_mode: Codex keeps
// places in a paginated rollout by byte (fitLine)
if out, ok = fitLine(line, out, paginated(line)); !ok {
return false, fmt.Errorf("%s keeps its history by byte, and %q is longer than the provider it names: Codex couldn't open it moved", filepath.Base(path), to)
}
}
changed = changed || ok
if _, werr := bw.Write(out); werr != nil {
return false, werr
+39
View File
@@ -179,3 +179,42 @@ func TestCodexProviderIn(t *testing.T) {
t.Fatalf("profile: %q", p)
}
}
// Codex keeps places in a paginated rollout by byte (xybio on Discord, see
// TestPortCodexRolloutsKeepsBytePlaces): a move keeps the session_meta
// line's length, padded after its JSON for a shorter id, and a longer id
// is refused with the files as they were; moving back gives the bytes it
// had.
func TestMoveCodexProviderKeepsBytePlaces(t *testing.T) {
_, codex := manageSetup(t)
main := filepath.Join(codex, "sessions", "2026", "09", "20", "rollout-2026-09-20T15-48-28-"+mgCX+".jsonl")
b, _ := os.ReadFile(main)
orig := bytes.Replace(b, []byte(`"model_provider":"openai"`), []byte(`"model_provider":"custom","history_mode":"paginated"`), 1)
old := time.Now().Add(-24 * time.Hour).Truncate(time.Second)
os.WriteFile(main, orig, 0o644)
os.Chtimes(main, old, old)
if _, err := MoveCodexProvider(mgCX, "cc"); err != nil {
t.Fatal(err)
}
now, _ := os.ReadFile(main)
if len(now) != len(orig) {
t.Fatalf("%d bytes, was %d", len(now), len(orig))
}
first := now[:bytes.IndexByte(now, '\n')]
if !bytes.HasSuffix(first, []byte("} ")) || !bytes.Contains(first, []byte(`"model_provider":"cc"`)) || !bytes.Equal(now[len(first):], orig[len(first):]) {
t.Fatalf("the file became\n%s", now)
}
if _, err := MoveCodexProvider(mgCX, "a-longer-provider"); err == nil {
t.Fatal("a longer id was written")
}
if b, _ := os.ReadFile(main); !bytes.Equal(b, now) {
t.Fatal("a refused move changed the file")
}
if _, err := MoveCodexProvider(mgCX, "custom"); err != nil {
t.Fatal(err)
}
if b, _ := os.ReadFile(main); !bytes.Equal(b, orig) {
t.Fatalf("moving back gave\n%s", b)
}
}