sessions: Codex identities are kept while no rollout changes (#2278)

Every Sessions and Requests poll built the Codex thread identities again
over every rollout (CodexIdentities, CallSourcesAndCodexIdentities, List,
Stats, ListAgent, Get), though nothing had changed since the last poll.
codexIdentitySnapshot now keeps the identities it built for the last four
file lists, with what each Codex rollout gave them from: its key, the
cached identity's value and whether it conflicts. A list whose rollouts
give the same is handed the kept map. The maps are now shared, so only
read: CodexIdentities' comment says so, and the old test that deleted from
one is replaced by TestCodexIdentitiesKeptWhileNoRolloutChanges.

Run at this head (5637cca14 + this change):
- mote: GOOS=linux/windows/darwin go vet -tags nogui ./internal/sessions/
  ./internal/usage/ ok; go test -timeout 45m ./internal/sessions/
  ./internal/usage/ ./internal/usageapi/ ok.
- magpie-desktop (Linux): the same three packages ok.
- Broken by hand: madeFrom not comparing what a rollout gave, so a
  changed rollout got the kept map: the new test is red ("a rollout
  changed and the identities kept from before were handed out").
- A/B on mote, the #2278 bench (real history copy, 10 endpoints polled
  every 5s, 4 gateway calls/s from 60s), v0.1.1968 vs v0.1.1968 + this,
  load ~27: codexIdentitySnapshot's allocations 280 MB -> 0 per 80s;
  total allocated 7942 -> 7538 MB per 80s; peak footprint 761 -> 733 MB;
  madvise 11.0% -> 9.2% of CPU samples; avg CPU 40.8% -> 39.3%. Poll
  times within the box's noise (0.43s vs 0.44s mean).

Not run: the full suite and the GUI suite (no GUI change).
This commit is contained in:
yetone
2026-10-29 07:08:23 +08:00
parent 5637cca141
commit 905166d786
2 changed files with 122 additions and 5 deletions
+82 -1
View File
@@ -6,6 +6,7 @@ import (
pathpkg "path"
"slices"
"strings"
"sync"
"time"
"github.com/tidwall/gjson"
@@ -346,7 +347,8 @@ func noteCodexIdentity(s *state, identity CodexIdentity, conflict bool) {
s.CodexIdentity = &merged
}
// CodexIdentities returns an independent snapshot of the native thread identities.
// CodexIdentities returns a snapshot of the native thread identities. It is
// shared with every caller asking while no rollout changed: only read it.
func CodexIdentities() map[string]CodexIdentity { return codexIdentitiesOf(codexFiles()) }
// codexIdentitiesOf is CodexIdentities with codex the rollouts codexFiles
@@ -486,7 +488,86 @@ func setSessionCodexTaskTitle(s *Session, titles map[codexTaskTitle]string) {
}
}
// codexIdentityMemo is the identities codexIdentitySnapshot built last, with
// what each Codex rollout gave them from. Every Sessions and Requests poll
// asks for them over every rollout, and building them again while no
// rollout's identity had changed was ~277 MB of what 80 s of polls allocated
// while an agent worked (#2278). The maps it hands out are shared: they are
// only read.
var codexIdentityMemo struct {
sync.Mutex
kept []keptIdentities // the last used first
}
// codexIdentityMemoSize is how many file lists' identities are kept: the
// whole history's, and a session's or an agent's own.
const codexIdentityMemoSize = 4
type keptIdentities struct {
from []codexIdentityFrom
identities map[string]CodexIdentity
}
// codexIdentityFrom is what one Codex rollout gives the identities from.
type codexIdentityFrom struct {
key string
identity CodexIdentity
known bool
conflict bool
}
func codexIdentityFromOf(f file) codexIdentityFrom {
from := codexIdentityFrom{key: f.key}
if s := cache[f.path]; s != nil && s.CodexIdentity != nil {
from.identity, from.known, from.conflict = *s.CodexIdentity, true, s.CodexIdentityConflict
}
return from
}
// madeFrom reports whether files' Codex rollouts give what k was built from.
func (k *keptIdentities) madeFrom(files []file) bool {
n := 0
for _, f := range files {
if f.agent != "codex" {
continue
}
if n == len(k.from) || codexIdentityFromOf(f) != k.from[n] {
return false
}
n++
}
return n == len(k.from)
}
// codexIdentitySnapshot is the native thread identities of files' Codex
// rollouts, kept while none of them changes.
func codexIdentitySnapshot(files []file) map[string]CodexIdentity {
m := &codexIdentityMemo
m.Lock()
defer m.Unlock()
for i := range m.kept {
if m.kept[i].madeFrom(files) {
k := m.kept[i]
copy(m.kept[1:i+1], m.kept[:i])
m.kept[0] = k
return k.identities
}
}
k := keptIdentities{identities: codexIdentitiesBuilt(files)}
for _, f := range files {
if f.agent == "codex" {
k.from = append(k.from, codexIdentityFromOf(f))
}
}
if len(m.kept) < codexIdentityMemoSize {
m.kept = append(m.kept, keptIdentities{})
}
copy(m.kept[1:], m.kept[:len(m.kept)-1])
m.kept[0] = k
return k.identities
}
func codexIdentitiesBuilt(files []file) map[string]CodexIdentity {
identities := map[string]CodexIdentity{}
conflicts := map[string]bool{}
for _, f := range files {
+40 -4
View File
@@ -90,10 +90,6 @@ func TestCodexIdentityParentChainsAndSummaryCache(t *testing.T) {
t.Errorf("identity %s = %+v, want %+v", id, got, want)
}
}
delete(identities, "main-a")
if got := CodexIdentities()["main-a"]; got.Role != codexRoleMain || got.RootSession != "main-a" {
t.Fatalf("identity snapshot shares its map: %+v", got)
}
if sources, ids := CallSourcesAndCodexIdentities(); !reflect.DeepEqual(sources, CallSources()) || !reflect.DeepEqual(ids, CodexIdentities()) {
t.Fatalf("one walk for both differs: %d sources, %d identities", len(sources), len(ids))
}
@@ -291,3 +287,43 @@ func TestCodexIdentityInvalidatesOldSummaryCache(t *testing.T) {
t.Fatalf("old summary cache hid current identity: %+v", got)
}
}
// While no rollout changes, the identities are the ones built before, not
// built again; a rollout whose identity changed has them built afresh, the
// same as building them with nothing kept (#2278).
func TestCodexIdentitiesKeptWhileNoRolloutChanges(t *testing.T) {
d := setupCalls(t)
spawn := `{"subagent":{"thread_spawn":{"parent_thread_id":"main-k","depth":1}}}`
codexIdentityRollout(t, d.codex, "main-k", codexIdentityMeta(t, "main-k", "s-k", `"vscode"`, "", ""), codexIdentityUsage(1, "r-main", "s-k", ""))
child := codexIdentityRollout(t, d.codex, "child-k", codexIdentityMeta(t, "child-k", "s-k", `"vscode"`, "", ""), codexIdentityUsage(2, "r-child", "s-k", ""))
built := func() map[string]CodexIdentity {
mu.Lock()
defer mu.Unlock()
return codexIdentitiesBuilt(append(codexFiles(), wslFiles("codex")...))
}
same := func(a, b map[string]CodexIdentity) bool {
return reflect.ValueOf(a).UnsafePointer() == reflect.ValueOf(b).UnsafePointer()
}
first := CodexIdentities()
if got := first["child-k"]; got.Role != codexRoleMain {
t.Fatalf("child-k before it is a subagent: %+v", got)
}
if again := CodexIdentities(); !same(first, again) {
t.Fatal("the identities were built again with no rollout changed")
}
if !reflect.DeepEqual(first, built()) {
t.Fatalf("kept identities differ from built ones\n got: %+v\nwant: %+v", first, built())
}
// the child's rollout is written again as a subagent of main-k
writeLines(t, child, codexIdentityMeta(t, "child-k", "s-k", spawn, "", ""), codexIdentityUsage(2, "r-child", "s-k", ""), codexIdentityUsage(3, "r-child2", "s-k", ""))
after := CodexIdentities()
if same(first, after) {
t.Fatal("a rollout changed and the identities kept from before were handed out")
}
if got := after["child-k"]; got.Role != codexRoleSubagent || got.RootSession != "main-k" {
t.Fatalf("child-k after its rollout changed: %+v", got)
}
if !reflect.DeepEqual(after, built()) {
t.Fatalf("identities after a change differ from built ones\n got: %+v\nwant: %+v", after, built())
}
}